- Beginners guide to setting up and running Flask web server
- Setting up flask
- Running flask server
- Rendering index.html and CSS using flask
- Working with JSON
- Turning on auto-reload
- Folder strucure
- To sum it up
- Adding CSS styling to your website
- Flask webserver — adding HTML and CSS
- Creating the HTML page
- Changing the Python code
- Adding CSS
- See also
- Join the PythonInformer Newsletter
Beginners guide to setting up and running Flask web server
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.
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.
Setting up 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.
from flask import Flask app = Flask(__name__) @app.route("/") def hello_world(): return "Hello world
"
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 "Hello world
"
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
Hello world
, 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
lang="en"> charset="UTF-8" /> http-equiv="X-UA-Compatible" content="IE=edge" /> Document rel="stylesheet" type="text/css" href="static/index.css" /> rel="shortcut icon" href=">" /> Pratap src="static/index.js">
body background-color: red; >
rel="stylesheet" type="text/css" href="static/index.css" /> src="static/index.js">
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", )
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
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)
if __name__ == "__main__": app.run(port=8000, debug=True)
Folder strucure
- 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.
Adding CSS styling to your website
So far, our website consists of a Python script, and three HTML documents. The Python script handles the communication between the web server and the web client (i.e., browser) while the HTML documents are responsible for the structure of the page content.
Now we need to add some style formatting to the HTML structure using CSS (Cascading Style Sheets). That is done by creating a CSS file and connecting it to our HTML files. CSS is a style language that likewise HTML, it is also easy to learn. Python is much harder to learn than CSS. So, a rule of thumb is if you know Python, learning CSS should be a breeze.
Remember that HTML template files HTML goes inside the templates’ folder. CSS stylesheets are considered static files. There is no interaction with their code, like there is with HTML templates. Therefore, flask has reserved a separate folder where you should put static files such as CSS, Javascript, images or other files. That folder should be created by you and should be named static. It’s also good practice to create another folder inside static and name it css.
Now, create an empty file inside the css and name the file something like main.css.
Then, put this code inside the CSS file:
body margin: 0;
padding: 0;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
color: #444;
>
/*
* Formatting the header area
*/
header background-color: #DFB887;
height: 35px;
width: 100%;
opacity: .9;
margin-bottom: 10px;
>
header h1.logo margin: 0;
font-size: 1.7em;
color: #fff;
text-transform: uppercase;
float: left;
>
header h1.logo:hover color: #fff;
text-decoration: none;
>
/*
* Centering the body content
*/
.container width: 1200px;
margin: 0 auto;
>
div.home padding: 10px 0 30px 0;
background-color: #E6E6FA;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
>
div.about padding: 10px 0 30px 0;
background-color: #E6E6FA;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
>
h2 font-size: 3em;
margin-top: 40px;
text-align: center;
letter-spacing: -2px;
>
h3 font-size: 1.7em;
font-weight: 100;
margin-top: 30px;
text-align: center;
letter-spacing: -1px;
color: #999;
>
.menu float: right;
margin-top: 8px;
>
.menu li display: inline;
>
.menu li + li margin-left: 35px;
>
.menu li a color: #444;
text-decoration: none;
>
I assume the CSS file is quite self-explanatory. What the code is basically doing is referring to the HTML tags and div class names and applying fonts, colors, text size, padding, margins and background colors to those HTML elements.
Alright, we have a CSS file, but our HTML documents still don’t know how to link to it. The idea is we should link each page to the CSS, but because our layout.html code is at every page, we can insert the linking code to that. So, open your layout.html page and add a head section so that the code looks like this:
As you see, we added a title and link tags to inside head tags. Inside the link tag, we declared we are relating to a stylesheet document, and then we specified the path to that style sheet.
Navigating to localhost:5000 now should display the website you saw in the screenshot further above.
You can now add more content to it and tweak the HTML files by adding more divs if you want more sections in your webpages.
But, what does a website serve for if it’s vegetating in your localhost?
It’s completely useless if no one sees it.
No worries, though, we will fix that right away by deploying the website in the Heroku cloud so that anyone can visit it through a public URL.
Let’s move on to the next lesson.
Flask webserver — adding HTML and CSS
In the previous example, our web page wasn’t a true web page at all. It was just a line of text, not HTML. A browser will display that as plain text, but you cannot format it in any way.
Flask allows us to create HTML files and use them as templates for our web pages.
Creating the HTML page
Create a basic HTML page, like this:
html> head> head> body> h1>Home pageh1> p>My first Flask sitep> body> html>
Save this file is a folder called templates, under your working folder. Name the file index.html.
Changing the Python code
You will need to make a couple of changes to server.py. First you must import render_template from the Flask module. Change your first line to this:
from flask import Flask, render_template
Then you must change your index function to this:
@app.route('/') def index(): return render_template('index.html')
Here, instead of returning a string, our index() function returns the result of render_template() . This function reads is the html file index.html, and returns its content as a string. Flask looks in the templates folder to find the html file.
Run the program and view the file in your browser. It should look like this:
Adding CSS
The page so far looks pretty boring, like a web page from 1995. We can improve things a little bit by adding come colour and using different fonts. We do this using a CSS (cascading style sheets) file, like this:
body background: Linen; margin-top: 50px; margin-left: 100px; > p font-family: Georgia, serif; font-size: 1.2em; color: DarkSlateGray; > h1 font-family: Verdana, Geneva, sans-serif; font-size: 2.5em; color: FireBrick; >
This code adds a background colour, and sets margins so that the text isn’t crammed into the top corner. It also sets the font, size and colour of the heading text (h1) and the paragraph text (p). You can change these values if you wish.
Create a folder called static, under your working folder. Name the file main.css and store it in the folder.
You will also need to edit your html file to include the CSS file. Add the extra line in the head section like this:
html> head> link rel="stylesheet" href='/static/main.css' /> head> body> h1>Home pageh1> p>My first Flask sitep> body> html>
Your page should now look like this:
See also
If you found this article useful, you might be interested in the book NumPy Recipes or other books by the same author.
Join the PythonInformer Newsletter
Sign up using this form to receive an email when new content is added: