Starting the Flask App
00:00
The foundation of your code image generator is a Flask web application that will live in an app.py
file. Go ahead and create the file,
00:11 and then open it in your editor.
00:14
In app.py
, you first need to import the Flask
class from Flask, so from flask import Flask
. Then create a variable named app
and instantiate the Flask
class with the argument __name__
: that’s two underscores name
and two underscores.
00:35 That’s the unique identifier of your module, and this is a convenient way of giving your Flask app a name, which Flask needs to work.
00:44
Then you need to create a route for your app, and you do this by using a decorated function @app.
route()
and then as an argument you can use the slash, so that’s the root route.
00:59
So root with double O and route with OU. In other words, that’s the homepage. The function you can basically name any way you want. Here I’m using code
because basically when we visit our web page, I want to see the code later on.
01:15
So I name this function code
and this function needs to return some HTML. For now, the HTML is not so important, so let’s just use an <h1>
tag and let’s say Hello!
inside the tag, close the tag and save the file.
01:33
So now when you start a Flask server and you visit the root route, then the Hello!
headline will be served to you. Let’s try this out. Open a terminal, make sure that your virtual environment is activated, and then run Flask by using python -m flask
and then the command run
.
01:57
So the full command is python -m flask run
.
02:02
That works because you named your Python file app.py
. So if you would name your Python file differently, you would have to have an --app
flag, but with the app.py
file you can use this basic command.
02:18
Once you hit Enter, the development server of Flask starts and there you will see an IP address that you need to copy and open in the browser. For me, that’s 127.0.0.1
:5000
.
02:32 That’s the port. For you, it should be the same, but if there is another URL showing on your end, use the one on your end of course. If you’re using VS Code, you can start the Command Palette and look for Simple Browser: Show, and paste the URL there.
02:49 And then a new browser window inside VS Code opens with our Hello! headline. But of course, you can also open another browser on your system and paste the URL there. Visually, there is not much happening so far, but the groundwork is done and I think that’s pretty amazing.
03:06
You’ve just created a Flask server and you are serving your first website. If you want, you can play around with the HTML code in the code
function.
03:15
If you play around, make sure to later have an <h1>
tag in the return string again, because that’s what you need to have in the next lesson where you’ll start working with Playwright.
Become a Member to join the conversation.