The author selected the Free and Open Source Fund to receive a donation as part of the Write for DOnations program.
Introduction
Flask is a small and lightweight Python web framework that provides Useful tools and features that make it easy to build web applications in Python. It gives developers flexibility and is a more accessible framework for new developers as you can quickly build a web application using just a single Python file. Flask is also extensible and doesn’t force a particular directory structure or require complicated boilerplate code before you get started.
As part of this tutorial, you’ll use the Bootstrap toolkit to design your app to be more visually attractive. Bootstrap will help you incorporate responsive web pages into your web application so that it also works well on mobile browsers without writing your own HTML, CSS, and JavaScript code to achieve these goals. The toolset will allow you to focus on learning how Flask works.
Flask uses the Jinja templating engine to dynamically create HTML pages using familiar Python concepts such as variables, loops, lists, etc. You’ll use these templates as part of this project.
In this tutorial, you’ll create a small web blog using Flask and SQLite in Python 3. Application users can view all posts in your database and click click a post title to view its contents with the ability to add a new post to the database and edit or delete an existing post.
Prerequisites
Before To get started by following this guide, you will need:
- A local Python 3 programming environment, follow the tutorial for your distribution in How to install and configure a local programming environment for the Python 3 series for your local machine . In this tutorial, we’ll call our project directory flask_blog.
- An understanding of Python 3 concepts such as data types, conditional statements, for loops, functions, and the like. If you’re new to Python, check out our How To Program in Python 3 series.
Step 1: Install Flask
In this step, you’ll activate your Python environment and install Flask using the pip package installer.
If you haven’t activated your programming environment yet, make sure you are in your project directory (flask_blog) and use the following command to activate the environment:
- source env/bin/activate
Once your programming environment is activated, your request will now have an env prefix that might look like this:
This prefix is an indication that the env environment is currently active, which may have another name depending on how you named it during creation.
You will now install Python packages and isolate the code from your project away from the main Python system installation. It will do this using pip and python.
To install Flask, run the following command:
- pip install Flask
Once complete installation, run the following command to confirm the installation:
- python -c “import Flask; print(flask.__version__)”
Use the interface python command line with the -c option to run the python code. Next, import the flask package with the import flask; then print the version of Flask, which is provided via the Flask.__version__ variable.
The result will be a version number similar to the following:
Output1.1.2
You have created the project folder, a virtual environment and Flask installed. You are now ready to proceed with setting up your base application.
Step 2: Creating a base application
Now that you have your programming environment set up, you’ll start using Flask. In this step, you’ll create a small web application inside a Python file and run it to start the server, which will display information in the browser.
In your flask_blog directory, open a file named hello . py to edit, use nano or your favorite text editor:
- nano hello.py
This hello.py file will serve as a minimal example of how to handle HTTP requests. Inside it, you’ll import the Flask object and create a function that returns an HTTP response. Write the following code inside hello.py:
from Flask import Flask app = Flask(__name__) @app.route(‘/’) def hello(): return ‘Hello world!’
In the code block above, you first import the Flask object from the Flask package. You then use it to create your Flask app instance with the name app. Pass the special variable __name__ that contains the name of the current Python module. It is used to tell the instance where it is; You need it because Flask sets up some routes behind the scenes.
Once you create the application instance, you use it to handle incoming web requests and send responses to the user. @application.route is a decorator that turns a normal Python function into a Flask view function, which turns the function’s return value into an HTTP response for display by an HTTP client, such as a web browser. Pass the value ‘/’ to @app.route() to indicate that this function will respond to web requests for the URL /, which is the main URL.
The view function hello() returns the string ‘Hello world!’ as a response.
Save and close the file.
To run your web app, you’ll first tell Flask where to find the app (the hello.py file in your case) with the FLASK_APP environment variable:
- export FLASK_APP=hello
Then run it in development mode with the FLASK_ENV environment variable:
<ol
Finally, run the application with the run flask command:
- run flask
Once the application is running, the output will look something like this:
Output * Serving Flask application “hello” (lazy loading) * Environment: development * Debug mode: enabled * Running at http://127.0. 0.1:5000/ (Press CTRL C to exit) * Rebooting with stat * Debugger is active! * Debugger PIN: 813-894-335
The above output has various data, such as:
- The name of the application you are running.
- The environment The one in which the application is running.
- Debugging mode: On means the Flask debugger is running. This is useful during development because it gives us detailed error messages when things go wrong, making it easier to troubleshoot.
- The application runs locally at the URL http://127.0.0.1: 5000/, 127.0. 0.1 is the IP that represents the localhost of your machine and :5000 is the port number.
Open a browser and type the URL http://127.0.0.1:5000/, you will receive the rope Hello world! in response, this confirms that your application is running correctly.
Now you can leave the development server running in the terminal and open another terminal window. Navigate to the project folder where hello.py is located, activate the virtual environment, set the FLASK_ENV and FLASK_APP environment variables, and continue with the following steps. (These commands are listed earlier in this step.)
You now have a small Flask web application. You ran your application and displayed information in the web browser. Next, you’ll use HTML files in your app.
Step 3: Using HTML Templates
Currently, your app just displays a simple message with no HTML. Web applications primarily use HTML to display information to the visitor, so now you’ll work to embed HTML files in your application, which can be displayed in the web browser.
Flask provides a helper function render_template() which allows the use of the Jinja templating engine. This will make HTML management much easier when writing your HTML code in .html files and using logic in your HTML code. You will use these HTML files (templates) to create all the pages of your application, such as the main page where you will display current blog posts, the blog post page, the page where the user can add a new post, and so on. .
In this step, you will create your main Flask app in a new file.
First, in your Flask_blog directory, use nano or your favorite editor to create and edit your app file .py. This will contain all the code you will use to create the blogging app:
- nano app.py
In this new file, you will import the Flask object to create an instance of the Flask app as you did above. It will also import the render_template() helper function that allows you to render HTML template files that exist in the templates folder you are about to create. The file will have a single view function that will handle requests to the main/ path. Add the following content:
from Flask import Flask, render_template app = Flask(__name__) @app.route(‘/’) def index(): return render_template(‘index.html’)
The index( ) view function returns the result of calling render_template() with index.html as argument, this tells render_template() to look for a file named index.html in the templates folder. Both the folder and the file do not exist yet, you will get an error if you were to run the application at this point. However, you will run it so that you are familiar with this common exception. It will then fix it by creating the necessary folder and file.
Save and exit the file.
Stop the development server in your other terminal running the hello application with CTRL C .
Before running the application, make sure to correctly specify the value of the FLASK_APP environment variable, since you are no longer using the application hello:
- export FLASK_APP =app
- flask run
When you open the URL http://127.0.0.1:5000/ in your browser, the debugger page will inform you that index. HTML template not found.The main line of code responsible for this error will be highlighted. In this case, it’s the return render_template(‘index.html’) line.
Clicking this line will reveal more code in the debugger so you have more context to help you solve the problem.
To correct this error , create a directory called templates inside your Flas_blog directory. Then inside, open a file called index.html for editing:
- mkdir templates
- nano templates/index.html
A Then add the following HTML inside index.html:
css” integrity=”sha384-ggOyR0iXCbMQv3Xipma34MD dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T” crossorigin=”anonymous”To learn more about SQLite, check out this tutorial.
First, because data in SQLite is stored in tables and columns, and since your data consists mostly of blog posts, you must first create a table called posts with the necessary columns. You will create a .sql file that contains SQL commands to create the post table with some columns. Next, you’ll use this file to create the database.
Open a file called schema.sql inside your flask_blog directory:
- nano schema.sql
Type the following SQL commands into this file:
DROP TABLE IF EXISTS posts; CREATE TABLE posts (id INTEGER PRIMARY KEY AUTOINCREMENT, created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, title TEXT NOT NULL, content TEXT NOT NULL);
Save and close the file.
The first SQL command is DROP TABLE IF EXISTS posts; this removes any already existing tables named posts so it doesn’t have confusing behavior. Note that this will delete all the content you have in the database as long as you use these SQL commands, so make sure you don’t write any important content to the web application until you finish this tutorial and experiment with the final result. Next, CREATE TABLE posts is used to create the posts table with the following columns:
- id – an integer representing a primary key, will be assigned a unique value by the database for each entry (which is a blog post).
- created: The time the blog post was created. NOT NULL means that this column must not be empty and the DEFAULT value is the CURRENT_TIMESTAMP value, which is the time the publication was added to the database. Like id, you don’t need to specify a value for this column as it will be filled in automatically.
- title – The title of the post.
- content – The content of the post .
Now that you have an SQL schema in the schema.sql file, you’ll use it to create the database using a Python file that will generate a SQLite .db database file. Open a file named init_db.py inside the flask_blog directory using your preferred editor:
- nano init_db.py
And then add the following code.
import sqlite3 connection = sqlite3.connect(‘database.db’) with open(‘schema.sql’) as f: connection.executescript(f.read()) cur = connection.cursor() cur.execute (” INSERT INTO posts (title, content) VALUES (?, ?)”, (‘First Post’, ‘First Post Content’) ) cur.execute(“INSERT INTO posts (title, content) VALUES (?, ?) “, (‘Second Post’, ‘Second Post Content’) ) connection.commit() connection.close()
First you import the sqlite3 module and then open a connection to a database file named database.db, which will be created after you run the Python file. Then use the open() function to open the schema.sql file. It then executes its content using the executescript() method which executes several SQL statements at once, which will create the posts table. You create a Cursor object that allows you to use its execute() method to execute two INSERT SQL statements to add two blog posts to your posts table. Finally, commit the changes and close the connection.
Save and close the file and then run it in the terminal using the python command:
- python init_db.py </li
Once the file finishes running, a new file called database.db will appear in your flask_blog directory. This means that you have successfully configured your database.
In the next step, you will retrieve the posts you inserted into your database and display them on your app’s home page.
Step 5 — Show all posts
Now that you’ve set up your database, you can now modify the index() view function to show all the posts you have in your database.
Open the app.py file to make the following modifications:
- nano app.py
For your first modification, you will import the module sqlite3 at the top of the file:
import sqlite3from Flask import Flask, render_template . . .
Next, you’ll create a function that creates a database connection and returns it. Add it directly after imports:
. . . from flask import Flask, render_template def get_db_connection(): conn = sqlite3.connect(‘database.db’) conn.row_factory = sqlite3.Rowreturn conn. . .
This get_db_connection() function opens a connection to the database file database.db and then sets the row_factory attribute to sqlite3.Row so you can access columns based on name. This means that the database connection will return rows that behave like regular Python dictionaries. Finally, the function returns the conn connection object that you will use to access the database.
After defining the get_db_connection() function, modify the index() function to look like this:
. . . @app.route(‘/’) def index(): conn = get_db_connection()posts = conn.execute(‘SELECT * FROM posts’).fetchall()conn.close()return render_template(‘index.html’, posts=posts)
In this new version of the index() function, you first open a connection to the database using the get_db_connection() function you defined earlier. It then runs an SQL query to select all entries from the posts table. Implement the fetchall() method to fetch all rows from the query result, this will return a list of the posts you inserted into the database in the previous step.
Close the database connection data using the close() command and returns the result of rendering the index.html template. You also pass the posts object as an argument, which contains the results you got from the database, this will allow you to access the blog posts in the index.html template.
With these modifications in place , save and close the app.py file.
Now that you’ve passed the posts you fetched from the database to the index.html template, you can use a for loop to display each post on your page. index.
Open the file index.html:
- nano templates/index.html
Then, modify it to look like the following way:
{% extends ‘base.html’ %} {% blocks content %}html’, post=post)
In this new view function, add a variable ruleexecute(‘SELECT * FROM posts’).fetchall() conn.close() return render_template(‘index.html’, posts=posts) . . .
Remember that the secret key must be a long random string.
After you set a secret key, you’ll create a view function that will generate a template that displays a form that you can fill out to create a new entry. from blog. Add this new function to the end of the file:
. . . @app.route(‘/create’, method=(‘GET’, ‘POST’)) def create(): return render_template(‘create.html’)
This creates a /create route that accepts both GET and POST requests. GET requests are accepted by default. To also accept POST requests, which the browser sends when submitting forms, it will pass a tuple with the types of requests accepted to the @app.route() decorator method argument.
Save and close the file.
To create the template, open a file called create.html inside your templates folder:
- nano templates/create.html
Add the following code inside this new file:
{% extends ‘base.html’ %} {% block content %}Once you submit the form, you’ll see the new post on the index page.
Finally, you’ll display flashing messages and add a link to the navigation bar in the base.html template to make it easy to access. new page. Open the template file:
- nano templates/base.html
Edit the file by adding a newThis displays the data stored in the request if it exists; otherwise, it displays the data from the post variable that was passed to the template containing the current database data.
Now, navigate to the following URL to edit the first post :
http://127.0.0.1:5000/1/edit
You will see a Edit “First Post” page.
Edit the post and submit the form, then make sure the post was updated.
Now you need to add a link pointing to the edit page for each post on the index page. Open the template file index.html:
- nano templates/index.html
Edit the file so that it looks exactly like this:
{ % extends ‘base.html’ %} {% content block %}See the Flask documentation for more information.
Flask has many community-created Flask extensions. The following is a list of extensions that you might consider using to ease your development process:
- Flask-Login: manages user session and handles logon/logoff and reminds users who logged in.
- Flask-SQLAlchemy – Simplifies using Flask with SQLAlchemy, a Python SQL and Object Relational Mapper toolkit for interacting with SQL databases.
- Flask-Mail – Helps with the task of sending emails in your Flask application.
.