How to create a website using python flask
The author selected the Free and Open Source Fund to receive a donation as part of the Write for DOnations program. Show
IntroductionFlask is a small and lightweight Python web framework that provides useful tools and features that make creating web applications in Python easier. It gives developers flexibility and is a more accessible framework for new developers since you can build a web application quickly using only a single Python file. Flask is also extensible and doesn’t force a particular directory structure or require complicated boilerplate code before getting started. As part of this tutorial, you’ll use the Bootstrap toolkit to style your application so it is more visually appealing. Bootstrap will help you incorporate responsive web pages in 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 toolkit will allow you to focus on learning how Flask works. Flask uses the Jinja template engine to dynamically build HTML pages using familiar Python concepts such as variables, loops, lists, and so on. You’ll use these templates as part of this project. In this tutorial, you’ll build a small web blog using Flask and SQLite in Python 3. Users of the application can view all the posts in your database and click on the title of a post to view its contents with the ability to add a new post to the database and edit or delete an existing post. PrerequisitesBefore you start following this guide, you will need:
Step 1 — Installing FlaskIn this step, you’ll activate your Python environment and install Flask using the
If you haven’t already activated your programming environment, make sure you’re in your project directory (
Once your programming environment is activated, your prompt will now have an
This prefix is an indication that the environment Note: You can use Git, a version control system, to effectively manage and track the development process for your project. To learn how to use Git, you might want to check out our Introduction to Git Installation Usage and Branches article. If you are using Git, it is a good idea to ignore the newly created Now you’ll install Python packages and isolate your project code away from the main Python system installation. You’ll do this using To install Flask, run the following command:
Once the installation is complete, run the following command to confirm the installation:
You use the The output will be a version number similar to the following:
You’ve created the project folder, a virtual environment, and installed Flask. You’re now ready to move on to setting up your base application. Step 2 — Creating a Base ApplicationNow that you have your programming environment set up, you’ll start using Flask. In this step, you’ll make a small web application inside a Python file and run it to start the server, which will display some information on the browser. In your
This flask_blog/hello.py
In the preceding code block, you first import the Once you create the The Save and close the file. To run your web application, you’ll first tell
Flask where to find the application (the
Then run it in development mode with the
Lastly, run the application using the
Once the application is running the output will be something like this:
The preceding output has several pieces of information, such as:
Open a browser and type in the URL Warning Flask uses a simple web server to serve our application in a development environment, which also means that the Flask debugger is running to make catching errors easier. This development server should not be used in a production deployment. See the Deployment Options page on the Flask documentation for more information, you can also check out this Flask deployment tutorial. You can now leave the development server running in the terminal and open another terminal window. Move into the project folder where Note: When opening a new terminal, it is important to remember activating the virtual environment and setting the environment variables While a Flask application’s development server is already running, it is not possible to run another Flask application with the same
To solve this problem, either stop the server that’s currently running via
You now have a small Flask web application. You’ve run your application and displayed information on the web browser. Next, you’ll use HTML files in your application. Step 3 — Using HTML templatesCurrently your application only displays a simple message without any HTML. Web applications mainly use HTML to display information for the visitor, so you’ll now work on incorporating HTML files in your app, which can be displayed on the web browser. Flask provides a In this step, you’ll create your main Flask application in a new file. First, in your
In this new file, you’ll import the flask_blog/app.py
The Save and exit the file. Stop the development server in your other terminal that runs the Before you run the application, make sure you correctly specify the value for the
Opening the URL If you click this line, the debugger will reveal more code so that you have more context to help you solve the problem. To fix this error, create a directory called
Next, add the following HTML code inside flask_blog/templates/index.html
Save the file and use your browser to navigate to In addition to the You can create a
Then create another directory called
Then open a
Add the following CSS rule to your flask_blog/static/css/style.css
The CSS code will add a border, change the color to brown, center the text, and add a little padding to Save and close the file. Next, open the
You’ll add a link to the flask_blog/templates/index.html
Here you use the Save and close the file. Upon refreshing the index page of your application, you will notice that the text You can use the CSS language to style the application and make it more appealing using your own design. However, if you’re not a web designer, or if you aren’t familiar with CSS, then you can use the Bootstrap toolkit, which provides easy-to-use components for styling your application. In this project, we’ll use Bootstrap. You might have guessed that making another HTML template would mean repeating most of the HTML code you already wrote in the To make a base template, first create a file called
Type the following code in your flask_blog/templates/base.html
Save and close the file once you’re done editing it. Most of the code in the preceding block is standard HTML and code required for Bootstrap. The However, the following highlighted parts are specific to the Jinja template engine:
Now that you have a base template, you can take advantage of it using inheritance. Open the
Then replace its contents with the following: flask_blog/templates/index.html
In this new version of the This Template inheritance also gives you the ability to reuse the HTML code you have in other templates ( Save and close the file and refresh the index page on your browser. You’ll see your page with a navigation bar and styled title. You’ve used HTML templates and static files in Flask. You also used Bootstrap to start refining the look of your page and a base template to avoid code repetition. In the next step, you’ll set up a database that will store your application data. Step 4 — Setting up the DatabaseIn this step, you’ll set up a database to store data, that is, the blog posts for your application. You’ll also populate the database with a few example entries. You’ll use a SQLite database file to store your data because the First, because data in SQLite is stored in tables and columns, and since your data mainly consists of blog posts, you first need to create a table called Open a file called
Type the following SQL commands inside this file: flask_blog/schema.sql
Save and close the file. The first SQL command is
Now that you have a SQL schema in the
And then add the following code. flask_blog/init_db.py
You first import the Save and close the file and then run it in the terminal using
the
Once the file finishes execution, a new file called In the next step, you’ll retrieve the posts you inserted into your database and display them in your application’s homepage. Step 5 — Displaying All PostsNow that you’ve set up your database, you can now modify the Open the
For your first modification, you’ll import the flask_blog/app.py
Next, you’ll create a function that creates a database connection and return it. Add it directly after the imports: flask_blog/app.py
This After defining the flask_blog/app.py
In this new version of the You close the
database connection using the With these modifications in place, save and close the Now that you’ve passed the posts you fetched from the database to the Open the
Then, modify it to look as follows: flask_blog/templates/index.html
Here, the syntax You display the title using a literal variable delimiter ( Once you are done editing the file, save and close it. Then navigate to the index page in your browser. You’ll see the two posts you added to the database on your page. Now that you’ve modified the Step 6 — Displaying a Single PostIn this step, you’ll create a new Flask route with a view function and a new HTML template to display an individual blog post by its ID. By the end of this step, the URL Open
Since
you’ll need to get a blog post by its ID from the database in multiple locations later in this project, you’ll create a standalone function called To respond with a flask_blog/app.py
Then, add the flask_blog/app.py
This new function has a
Inside the function, you use the Next, add the following view function at the end of the flask_blog/app.py
In this new view function, you add a variable rule Save the
Type the following code in this new flask_blog/templates/post.html
You add the Save and close the file. You can now navigate to the
following URLs to see the two posts you have in your database, along with a page that tells the user that the requested blog post was not found (since there is no post with an ID number of
Going back to the index page, you’ll make each post title link to its respective page. You’ll do this using the
Then change the value of the flask_blog/templates/index.html
Here, you pass Save and close the file. The links on the index page will now function as expected. With this, you’ve now finished building the part of the application responsible for displaying the blog posts in your database. Next, you’ll add the ability to create, edit, and delete blog posts to your application. Step 7 — Modifying PostsNow that you’ve finished displaying the blog posts that are present in the database on the web application, you need to allow the users of your application to write new blog posts and add them to the database, edit the existing ones, and delete unnecessary blog posts. Creating a New PostUp to this point, you have an application that displays the posts in your database but provides no way of adding a new post unless you directly connect to the SQLite database and add one manually. In this section, you’ll create a page on which you will be able to create a post by providing its title and content. Open the
First, you’ll import the following from the Flask framework:
Add the imports to your file like the following: flask_blog/app.py
The To set a secret key, you’ll add a flask_blog/app.py
Remember that the secret key should be a long random string. After setting a secret key, you’ll create a view function that will render a template that displays a form you can fill in to create a new blog post. Add this new function at the bottom of the file: flask_blog/app.py
This creates a Save and close the file. To create the template, open a file called
Add the following code inside this new file: flask_blog/templates/create.html
Most of this code is standard HTML. It will display an input box for the post title, a text area for the post content, and a button to submit the form. The value of the post title input is Now, with the development server running, use your browser to navigate to the
You will see a Create a New Post page with a box for a title and content. This form submits a POST request to your You’ll handle the incoming POST request when a form is submitted. You’ll do this inside the Open the
Modify the flask_blog/app.py
In the You then extract the submitted title and content from the You then commit the changes to the database
and close the connection. After adding the blog post to the database, you redirect the client to the index page using the Save and close the file. Now, navigate to the
Fill in the form with a title of your choice and some content. Once you submit the form, you will see the new post listed on the index page. Lastly,
you’ll display flashed messages and add a link to the navigation bar in the
Edit the file by adding a new flask_blog/templates/base.html
Save and close the file. The navigation bar will now have a Editing a PostFor a blog to be up to date, you’ll need to be able to edit your existing posts. This section will guide you through creating a new page in your application to simplify the process of editing a post. First, you’ll add a new route to the
Next, add the following flask_blog/app.py
The post you edit is determined by the URL and Flask will pass the ID number to the Just like when you create a new post, you first extract the data from the In the case of a GET request, you render an Save and close the file, then create a new
Write the following code inside this new file: flask_blog/templates/edit.html
Save and close the file. This code follows the same pattern except for the Now, navigate to the following URL to edit the first post:
You will see an Edit “First Post” page. Edit the post and submit the form, then make sure the post was updated. You now need to add a link that points to the edit page for each post on the index page. Open the
Edit the file to look exactly like the following: flask_blog/templates/index.html
Save and close the file. Here you add an Deleting a PostSometimes a post no longer needs to be publicly available, which is why the functionality of deleting a post is crucial. In this step you will add the delete functionality to your application. First, you’ll add a new
Add the following view function at the bottom of the file: flask_blog/app.py
This view function only accepts POST requests. This means that navigating to the However you can access this route via a form that sends a POST request passing in the ID of the post you want to delete. The
function will receive the ID value and use it to get the post from the database with the Then you open a database connection and execute a Note that you don’t render a template file, this is because you’ll just add a Open the
Then add the following flask_blog/templates/edit.html
You use the Now navigate again to the edit page of a blog post and try deleting it:
At the end of this step, the source code of your project will look like the code on this page. With this, the users of your application can now write new blog posts and add them to the database, edit, and delete existing posts. ConclusionThis tutorial introduced essential concepts of the Flask Python framework. You learned how to make a small web application, run it in a development server, and allow the user to provide custom data via URL parameters and web forms. You also used the Jinja template engine to reuse HTML files and use logic in them. At the end of this tutorial, you now have a fully functioning web blog that interacts with an SQLite database to create, display, edit, and delete blog posts using the Python language and SQL queries. If you would like to learn more about working with Flask and SQLite check out this tutorial on How To Use One-to-Many Database Relationships with Flask and SQLite. You can further develop this application by adding user authentication so that only registered users can create and modify blog posts, you may also add comments and tags for each blog post, and add file uploads to give users the ability to include images in the post. See the Flask documentation for more information. Flask has many community-made Flask extensions. The following is a list of extensions you might consider using to make your development process easier:
Can I create a website with Flask?Flask is a known as a micro web framework. This means it provides some basic functionality to allow developers to build simple websites. It does not come with all the bells and whistles like some other web frameworks like django have and therefore is typically not used for complex websites.
How do I make a simple Flask website?Both are Pocco projects.. Installation: ... . virtualenv pip install virtualenv.. Create Python virtual environment virtualenv venv.. Activate virtual environment windows > venv\Scripts\activate linux > source ./venv/bin/activate.. Flask pip install Flask. ... . Example: ... . Output: geeksforgeeks.. Can I create a website with Python?Can you make a website using Python? The answer is yes, you can make a website with Python - quite easily in fact. Although Python is a general-purpose programming language, that naturally extends into web programming.
How do I host a Python Flask web application?Python Web Applications: Deploy Your Script as a Flask App. Brush Up on the Basics. Distribute Your Python Code. ... . Build a Basic Python Web Application. Set Up Your Project. ... . Deploy Your Python Web Application. ... . Convert a Script Into a Web Application. ... . Improve the User Interface of Your Web Application. ... . Conclusion.. |