In this blog post, we will learn how to set up a web server using flask.
Introduction
Flask is a Python web framework built with a small core and easy-to-extend philosophy.
Getting started
Before getting started, let us make sure we have python3 installed in our system.
Follow Python download link to get python installed in your system. Once the python installation is completed, let start with creating a server.
Before proceeding with the setup, let us create a folder named flask-app. Run the below command to make a folder.
$ mkdir flask-app
Now cd into the newly created flask-app
folder.
$ cd flask-app
Now let us set up a virtual environment using python3
for the app. To set up a virtual environment, let us run the below command.
$ python3 -m venv env
After creating a virtual environment, we need to activate the environment.
$ source env/bin/activate
Now, finally, we can start with creating a web server using a flask.
Setting up flask
As python Flask is an external module, to start working on it, we need to install it.
$ pip install Flask
Now, let us create a file called app.py
in the root directory of our project. You can use the terminal or code editor of your choice.
$ touch app.py
Once the file is created, let us add the following lines of code in the file.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
return "<p>Hello world</p>"
Running flask server
To run the application, use the flask command or python -m flask
. Before you can do that, you need to tell your terminal the application to work with by exporting the FLASK_APP
environment variable:
export FLASK_APP=app
$ flask run
* Running on http://127.0.0.1:5000/
Finally, our server is running on Port 5000
. Go to your browser and open localhost:5000. You should see Hello World in the browser. How cool is that? Amazing right?
If you check the flask code
@app.route("/")
def hello_world():
return "<p>Hello world</p>"
We are saying in the code above that if anyone hits /
in the browser. Then the flask app will run the hello_word
function. Since we were returning <p>Hello world</p>
, this gets rendered in the browser.
Rendering index.html and CSS using flask
So far, we returned a string from the server. In this section, let us try to return HTML, CSS, Javascript files when we hit /
in the browser. To do that, we need to create two folders named static
and templates
$ mkdir static
$ mkdir templates
We will place all the views file, HTML files in the template folder; js and CSS files inside the static folder.
Let's create an index.html
file inside the template
folder and add the snippet.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Document</title>
<link rel="stylesheet" type="text/css" href="static/index.css" />
<link
rel="shortcut icon"
href="{{ url_for('static', filename='favicon.ico') }}"
/>
</head>
<body>
<div>
<p>Pratap</p>
</div>
<script src="static/index.js"></script>
</body>
</html>
Also css
and js
file inside static
folder.
index.css
body {
background-color: red;
}
index.js
console.log("I am running");
If you check the index.html
file
<!-- Loading the css file using this line -->
<link rel="stylesheet" type="text/css" href="static/index.css" />
<!-- Linking the javascript file using this line -->
<script src="static/index.js"></script>
Now let's update our app.py
file and some more code there.
from flask import Flask, render_template
app = Flask(
__name__,
template_folder="./templates",
static_folder="./static",
)
@app.route("/")
def hello_world():
return render_template('index.html')
If you observe the code above. We have updated the Flask
function. We let the flask know where it should load the templates
and static
files.
app = Flask(
__name__,
template_folder="./templates",
static_folder="./static",
)
By default Flask will look for
template
andstatic
folders.
And then, we also updated the /
route we return render_template(index.html)
. So, the flask app will load the index.html
file and pass it to the render_template
function.
@app.route("/")
def hello_world():
return render_template('index.html')
Re-run the flask app and hit localhost:5000 from the browser. Alas! The HTML file is now loading. Amazing!
I hope you are going well.
Working with JSON
Until now, we are only working on HTML snippets. In this section, let's return a JSON object.
from flask import Flask, render_template, jsonify
app = Flask(
__name__,
template_folder="./templates",
static_folder="./static",
)
@app.route("/")
def hello_world():
return render_template('index.html')
@app.route("/json")
def json_response():
response = {"name": "Pratap", "age": 24}
return jsonify([response])
So if look json_response()
function carefully we are now returning a dictionary
. We than pass it to jsonify()
function which we imported from Flask
@app.route("/json")
def json_response():
response = {"name": "Pratap", "age": 24}
return jsonify([response])
If you re-run the application and hit localhost:5000/json from the browser. You will see a JSON object being displayed in the browser.
Turning on auto-reload
Until now, after making each change, you need to restart the app. We can also tell the flask
app to restart after we make any changes. We need to update the app.py
and add the following snippet at the bottom of the file. We have added a condition that if we are running the file directly, add debug=True
. This will make sure to run the app in debug mode
if __name__ == "__main__":
app.run(debug=True)
Now, when running the app, we can run the app by running it in the terminal.
$ python app.py
We can also mention which port to run on. Currently, it's running on 5000 port by default.
if __name__ == "__main__":
app.run(port=8000, debug=True)
Folder strucure
Things to remember
- To build a python web application, we need to import the Flask module.
- We need to pass the name of the current module, i.e., name, as an argument into the Flask constructor.
- The
route()
function of the class defines the URL mapping of the associated function.app.run()
method is used to run our Flask Application.
To sum it up
This is it from this article. I hope I'm able to give you an overview of how the Flask application work. You can find the source code here.
💌 If you'd like to receive more tutorials in your inbox, you can sign up for the newsletter here.
Please don't hesitate to drop a comment here if I miss anything. Also, let me know if I can make the post better.
Top comments (2)
Nice pratap, keep them coming 😊
Thanks Shiva