Flask webserver - getting started
Martin McBride, 2020-01-22
Tags installing web server
In this article we will learn how to install Flask and run up a very simple local webserver.
The code for and all other examples can be found on github in the python-libraries/flask folder.
Open a command (cmd) window and use pip to install flask:
pip install flask
You should first create a working folder for the project, somewhere suitable. For example c:\web-server, although you will probably want to create it where ever you keep the rest of your work.
Create a new file in your Python editor (IDLE, or whatever editor you prefer). Type in the following code:
from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'My first Flask site' if __name__ == '__main__': app.run(debug=True, port=80, host='0.0.0.0')
This code can be found on github.
Save the code as server.py in your working folder. Then run the code. You should see something like this in the IDLE console:
RESTART: C:\web-server\server.py * Running on http://0.0.0.0:80/ (Press CTRL+C to quit) * Restarting with stat
Your web server is running!
View the page in a browser
Open a browser and type the following into the address field:
This is a special URL. Instead of going out on to the web to find a page, it looks for a web server on your own PC. With most browsers you can shorten this to 127.0.0.1, and it will still work. Or, instead of the numbers, you can just type in localhost if you find it easier to remember. They all do the same thing.
If all is well, you should see your message ('My first Flask site') in your browser.
What the code does
Here is the code, line by line. First we import the Flask module:
from flask import Flask
Next we create a Flask object, called app. This object runs the web server. We pass in name, the name of the module. This tells Flask where to look for the extra files we will add later - don't worry about this too much, you would only need to play with this parameter to create complex web sites.
app = Flask(__name__)
Now we get to the function index() which actually creates the web page content. In this case it is very simple, just the text My first Flask site.
The line @app.route('/'), just before the index function, is called a decorator. It tells Flask that any path which matches '/' should use the index() function to create its content. The path '/ ' is the home page of the website.
@app.route('/') def index(): return 'My first Flask site'
The final part should be familiar, it just causes app.run if this file is executed as a python program. The parameters are set to default values which allow a browser to view our page.
if __name__ == '__main__': app.run(debug=True, port=80, host='0.0.0.0')