Creating Flask Server
Author: Joe HutchesonWhether you are working as an advanced developer creating a simple server or just getting your feet wet with RESTful APIs, Flask is a minimalistic Python framework that makes it easy to create microservices.
From the Flask documentation: “Flask provides configuration and conventions, with sensible defaults, to get started.” Sounds easy enough. And fortunately, in practice, it is!
First things first, let’s get Flask installed. Flask supports Python 3.7 and newer, but recommends using the latest version of Python (which is 3.11.2 at the time of this post.) It might be time to step it up and update Python.
On a Linux Ubuntu machine, you may install with:
sudo apt install python3-pip
# install python3.x and the python package installer pip
Flask will install automatically with the following dependencies: Werkzeug (implements Web Service Gateway Interface), Jinja (templating language which renders the pages of your application), MarkupSafe (works with Jinja to identify and avoid untrusted input), ItsDangerous (protects Flask’s session cookies), and Click (for writing command line applications). Clearly, developers will be in good hands with the basic install. Furthermore, Flask will detect and use the following dependencies: Blinker, python-dotenv, and Watchdog (more about these dependencies can be found at the Flask documentation.)
In order to manage the dependencies of your project in both a development and a production setting, Flask does recommend the use of a virtual environment using the venv module. Remember to set up your virtual environment within your project directory.
Once set up in your virtual environment, simply run the following line of code:
python3 -m pip install Flask
# for python3 versions
In its simplest form, we would like our Flask application to return something to our user should they hit a particular endpoint on our server.
First, we need to import Flask. To keep this simple application lightweight, we will only import Flask from flask.
from flask import Flask
The import above is our constructor which creates an object of Flask class, taking in the name of our current module which will be assigned to the dunder variable __name__
. The convention is to assign this instance to a variable called app.
app = Flask(__name__)
‘app’ is our application, which is an iteration of the Flask class. Now we can make it our own.
For routing, Flask makes use of decorators, notated with the @ symbol:
@app.route("/")
The above decorator will handle our users accessing the root url of our application. A function attached to this decorator will tell Flask how to handle this:
@app.route("/") # our decorator from above
def hello_world():
return "Hello World"
In layman’s terms, we are telling Flask that when our user hits the base URL of our application, return “Hello World” to them.
We can also “stack” decorators to associate the same function with different endpoints; this can anticipate user behaviors such as trying to access the home page of an application with different endpoints:
@app.route("/")
@app.route("/home")
def hello_world():
return "Hello World"
Both endpoints above will render the same result.
When we reach the familiar if __name__ == "__main__":
portion of our script, instead of calling a function, we want to run our server. The following example is only used in a development mode (for deployment options, reference the following: Flask Deploying to Production):
if __name__ == "__main__":
app.run(host="0.0.0.0", port=2224)
Flask also provides a debug mode, an interactive debugger which will reload when content changes.
if __name__ == "__main__":
app.run(host="0.0.0.0", port=2224, debug=True)
The full script would look something like this:
#!/usr/bin/python3
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
return "Hello World"
if __name__ == "__main__":
app.run(host="0.0.0.0", port=2224)
And there we go. Clearly, we could build this out to be much more useful and functional depending on the application we want to create. But with this script, we have the foundation for any simple Flask server.