• How to Create a Website
  • How to Make a Wordpress Website
  • How to Start a Blog
  • How Much Does a Website Cost?
  • Best Website Builders
  • Squarespace
  • Best Web Hosting
  • Wordpress Hosting
  • Shared Hosting
  • Dedicated Web Hosting
  • Managed Hosting
  • How Do I Switch Web Hosting?
  • Compare Hosts
  • Best E-commerce Platforms
  • How to Sell on Amazon
  • Shopify Tips
  • BigCommerce
  • WooCommerce
  • A Complete Guide to Online Marketing
  • Marketing Tools
  • Email Marketing Platforms
  • CRM Software
  • Create Your Own Email Address with Gmail
  • How to Set Up a VPN
  • Best VPN Services
  • Password Managers
  • Password Generators
  • How to Prepare a P&L
  • HR Software
  • Accounting Software
  • Payroll Software
  • Software & Service Reviews
  • Who is Hosting This?
  • What's Your IP Address
  • Hosting Speed Test
  • HTML Cheat Sheet
  • / How to Build a Website
  • How To Build a Website With Python

Michael Levanduski

By: Michael Levanduski Network Technical Engineer

Python is a programming language that was developed in 1991, it has grown in popularity over the last decade. Python developers are among the most in-demand in the tech world today.

The Python programming language is a general-purpose option, meaning it can be used to create almost any type of computer program, including websites. It’s surprisingly easy to learn, yet still powerful enough for some of the most advanced applications out there, making it a programming language that benefits any developer.

If you want to learn how to build a website with Python, you’ll need to have a good grasp of this language as well as a good understanding of how websites work. This page is a high-level introduction to how to build a website with Python to help you get started.

In the end, there will be links to some additional resources that can help you to learn Python so you can create your site. As you read through this page, you’ll learn information like:

  • Why many people choose to use Python to build a website
  • Examples of popular sites created using Pythonbuild
  • Basic steps required for building a website using Python
  • Resources for learning more about Python

Installing Python

  • Why You Can Use Python To Build a Website

The Python programming language can be used to create a huge variety of different types of things, including websites. Making websites with Python is easier than most people think because of the fact that this language makes use of something called “frameworks.”

Frameworks are prebuilt selections of code that are made to perform specific tasks. When creating a website, for example, there are frameworks that’ll give your site structure, perform common functionalities, and much more. To put it simply, you can use a framework to dramatically cut down the total amount of actual coding you need to perform, which will save you a ton of time.

  • Examples of Sites Created Using Python

Here are some examples of websites that have been created using the Python programming language. These illustrate the coding language’s versatility:

  • Google : The most popular search engine in the world uses Python
  • Instagram : Python was used to create the backend of Instagram
  • Spotify : Python is one of the reasons Spotify can serve up audio files with virtually no delay
  • Netflix : Much of the Netflix website and overall service was coded in Python
  • Uber : Uber revolutionized the ride-sharing industry and its service is built with Python

Of course, millions of other websites use Python for some or all of their programming with that number growing daily.

No matter what language you use, building a website from scratch is going to take some time and effort. Python makes many things about website building faster and easier, but you still need to make sure you have everything in place and complete all the essential steps. The following are just some of the critical things you need to do to launch a website coded in Python successfully.

Set Up Python Web Hosting

As with any website, you’ll need to have good hosting in place. Almost all web hosting companies today will support running pages that are made using Python. There are some, however, that are better than others or specialize in hosting these types of sites.

Taking the time to find the right hosting company for your Python website will help ensure you don’t run into trouble down the road. While most hosting companies can run Python-based sites, those that don’t have it as a focus may not keep their systems updated to the latest versions of Python. This can cause your website to load incorrectly if you begin using updated versions before the hosting provider is ready. If you’re looking for a good option to consider, we have ranked and reviewed the top Python hosting companies to help ensure you pick the right one.

It Always Seems Impossible Until Its Done

Choose Your Framework

One of the most important steps when creating a website with Python is choosing your framework. There are quite a few different popular frameworks that will make it faster and easier to make a website. The following are among the most popular Python frameworks used today:

There are, of course, dozens of other frameworks to choose from. Finding the one that’s right for you based on your needs may take a little time, but it’s well worth the effort.

Code Your Website

Once you have your framework picked out and in place, you’ll be ready to begin coding your website. This is where you’ll be spending most of your time, though many first-time users are surprised at just how quickly it can go. The bulk of the steps that need to be manually coded when using other languages are already in place, thanks to the established Python frameworks.

An experienced Python developer can have a website up and running relatively quickly. Using the right frameworks, you could have an extremely basic site up in well under an hour. A typical website will typically take about a day, if you don’t include creating the actual content for the site. Remember that, after initially coding your site, you’ll constantly update and improve it to keep it current and functioning properly.

If you don’t already know Python, or this will be your first time using it for web development, you’ll need to learn some key points to get started. Python is widely considered one of the easiest programming languages to learn today. Additionally, no matter what level of learning you require, there are resources available to you.

Consider some of the following great options:

Installing VirtualEnv

You can spend countless hours researching and investigating your options for creating a website. In the end, however, it’s best to try it out. One of the best things about Python is that it’s easy to learn, and you can see real results very quickly. If you think that you want to make a website with Python, the best thing to do is just give it a try. You’ll likely be surprised at how easy it is.

Table of Contents

Related posts, why small businesses are choosing headless e-commerce, javascript: how to get started developing interactive websites, 7 ways to make your e-commerce call to action irresistible, prolog programming: give your ai bot it’s best life., 6 essential components of an e-commerce website.

© 2019 Digital.com

How to create a website using Python (an introduction)

User Avatar

Can you make a website using Python?

Why create a website with python, relatively easier to learn, a vast collection of libraries, faster development time, excellent data visualization capabilities, budget-friendly, secure and scalable, what other websites were made using python, how to code a website in python using web frameworks, which framework should you use to build your website using python, a step-by-step guide to create a website using python, step 1: get a handle on html and css, step 2: master the basics of javascript, step 3: master the document object model, step 4: backend development with python, step 5: choose your framework and database, final words.

Article thumbnail

Talk to one of our Technical Co-Pilots to help with your project

Recommended articles just for you.

Article Thumbnail

Mastering Data Analytics

Related Articles

Create Basic Webpage with Pyscript

In this article, we will cover how we can create a basic webpage with Pyscript

The Pyscript is a python framework/library that allows us to write python code inside HTML directly with the help[ of pyscript tag. Pyscript is a new project and is currently under development, but it has gained a lot of attention recently. It can make a page generate dynamically with the help of python. We will see the basic web page created with the pyscript library in this article.

Creating a Template

We’ll create a basic template in HTML in which we will further add the pyscript framework as a link and a script to the pyscript CDN.  You can create an index.html in a folder in your desired location. 

A simple HTML template can be created as per your preferences, we’ll leave it empty body right now to start afresh instance of the pyscript code.

Embedding Python inside HTML

We first need the script files that help us in allowing the runtime of python from the pyscript CDN.  So, we will have to add a few link tags and the script tag that will bring in the Python Pyodide runtime.

<link rel=”stylesheet” href=”https://pyscript.net/alpha/pyscript.css” /> <script defer src=”https://pyscript.net/alpha/pyscript.js”></script>

The first link for the stylesheet will allow us to format the output generated from the python code. The next link which is a script tag will bring in the javascript source file that will work with the browser for interacting with the python runtime. Finally, we can use the pyscript tags for embedding the python code.

The python code can be embedded by adding inside the  <py-script> tags.  We can use the  <py-script> tags to write python code. Normal python code can be embedded inside the <py-script> tags. The tags are not self-closing and hence like other HTML tags it needs a closing tag as </py-script>

The python code inside the py-script tags should be indented, as you write the python code. The formatting of the indentation is not strictly from the start of the line, though it needs to be consistent throughout while being inside the tags.

Here, we have used a simple python code for printing a variable name. The print function is parsed inside the pyscript that will in turn process the python and display the result as a native HTML tag. Though output from pyscript tags is native HTML, the generation is done with the help of Pyodide and WASM which generates the native HTML from the pyscript tags.

The webpage takes a few seconds to load in its entirety of the webpage. That’s because the python code has to be rendered and converted to a native HTML.

Creating and Displaying List in Pyscript using loop

We can generate a list of elements in the HTML using a pure python list. We can simply use python syntax to print the elements of a list. The output will be generated as a distinct line which is the default behavior of the print statement in pyscript.

We can see the elements of the list are printed on the webpage using simple python code in the embedded pyscript tag. 

Creating and Displaying a dictionary using a conditional statement

To create a dictionary in python, we will be creating a simple dictionary and will display the key-value pairs one by one using a simple for loop. 

Here, we have created a string and will further create a frequency map of each letter in the string. To create a frequency map of letters in the string, we will initialize an empty dictionary,  we will iterate over the string, and check if the character in the string is present as a key in a dictionary or not, if it is present we will increment the value of the key as the character in the string, else the key is initialized to one.

So, we can see the dictionary has the key values as the character of the strings and the frequency of that character in the string.

Use the HTTP server to render the pyscript page

We can even use the HTTP server to render the pyscript page. We can do that using the http.server module to render the HTML page.

Note – You need to be in the same directory as your index.html file else you need to specify the directory for rendering the HTML file.

The d flag is provided to locate the file in the directory without actually changing the directory in the terminal to run the HTTP server. After running the server, you need to locate the 127.0.0.1:8000 or localhost:8000 for viewing your HTML file.

Please Login to comment...

how to create a web page with python

Data Structures & Algorithms in Python - Self Paced

how to create a web page with python

Python Backend Development with Django - Live

how to create a web page with python

Python Programming Foundation -Self Paced

how to create a web page with python

Complete Machine Learning & Data Science Program

how to create a web page with python

Complete Test Series for Service-Based Companies

how to create a web page with python

Master Java Programming - Complete Beginner to Advanced

how to create a web page with python

JAVA Backend Development - Live

how to create a web page with python

Data Structures and Algorithms - Self Paced

how to create a web page with python

Full Stack Development with React & Node JS - Live

Improve your coding skills with practice, start your coding journey now.

Unsupported browser

This site was designed for modern browsers and tested with Internet Explorer version 10 and later.

It may not look or work correctly on your browser.

Python From Scratch: Create a Dynamic Website

Giles Lavelle

How do you get started creating websites with Python? Well, you could do it all yourself and write a program that runs on a web server, accepting page requests and serving up responses in the form of HTML and other resources. However, that’s a lot of work, so why go to all the trouble when there are plenty of existing tools out there to do the job for you? These tools are called frameworks, and they're what we’ll use today to create our website.

Python Frameworks

There are quite a few Python web frameworks, but here are some of the best:

A more comprehensive list can be found on the Python website if you're in need of additional options. Today we’re going to set Django up for development on a local machine, and then build a simple blog. We're also going to review the process of installing it on a remote web server.

Installing Django

We'll be performing most of our work today in the terminal. This should all work on Mac and Linux; however, if you're running Windows, the process is somewhat different. A familiarity with the command line isn't necessary if you're only writing Python, although if you're planning on using Django or running a dynamic website in general, it's worth learning.

Terminal Tutorials

Consider reviewing these tutorials to get yourself up and running with the Terminal:

Here are the commands you need to install Django. You'll need to install version Python 3 to get it running. First, you need to create a virtual environment with the venv module. From the Python docs:

The venv module provides support for creating lightweight “virtual environments” with their own site directories, optionally isolated from system site directories. Each virtual environment has its own Python binary (which matches the version of the binary that was used to create this environment) and can have its own independent set of installed Python packages in its site directories.

Create a project directory and a virtual environment inside the project directory.

Activate the virtual environment and create a new Django project.

The project directory looks like this:

Django project directory

What do each of these files do?

However, none of these files on their own make a functional website. For that, we need apps. Apps are where you write the code that makes your website function, but before we take a look at them, we need to understand a bit about Django’s design principles.

First, Django is an MVC framework, which stands for Model View Controller. Django refers to itself as an MTV framework, which stands for Model Template View. It’s a slightly different approach than MVC, but fundamentally, they’re quite similar. Anyhow, MVC is an architectural pattern that provides a method for structuring your projects. It separates the code that’s used to process data from the code that manages the user interface.

Secondly, Django subscribes to the DRY, or Don’t Repeat Yourself philosophy, which means that you should never be writing code that performs a certain task more than once. For example, in our blog, if we wrote a feature that picked a random article from the archive and implemented this feature on multiple pages, we wouldn’t code it again each time it was needed. We’d code it once and then use it on each page.

So how does this relate to apps? Well, apps allow you to write your website in a DRY style. Each project, like the one we have here, can contain multiple apps. Conversely, each app can be part of multiple projects. Using the example from earlier, this means that if we made another site in the future that also needed a random page feature, we wouldn’t have to write it all over again. We could simply import the app from this project.

Because of this, it’s important that each app serves one distinct purpose. If you write all the functionality of your site within one app, and then you need to use part of it again later, you have to import it all. If you were making an eCommerce website, for example, you wouldn’t want to import all the blog features. However, if you make one app for the random feature and one app for the blog publishing system, you could pick and choose the bits that you require.

This also means that within the site, the code is well organized. If you want to alter a feature, you don’t have to search through one massive file; you can instead browse to the relevant app and change it without worrying about interfering with anything else.

The directory structure now looks like this:

Django project

Again, we’ve got an __init__.py file to make it a package, and three other files: models, tests, and views. We don’t need to worry about tests for now, but the other two are important. Models and Views are the M and V parts of MVC.

In models, we define our data structures.

If you’ve ever worked with PHP before, you might have used PhpMyAdmin to create your MySQL tables, and then written out your SQL queries manually in your PHP scripts. In Django, it’s much easier. We define all the data structures we need in this models file, then run a command and all the necessary databases are made for us.

When you wish to access that data, you go via these models by calling a method on them, instead of running raw queries. This is very helpful because Django can use several database programs. We’re going to use MySQL today because it’s the most powerful and is what most hosts provide, but if we needed to switch to a different database in the future, all of the code would still be valid! In other languages, if you wanted to switch to SQLite or something similar, you would need to rewrite the code that accesses your database.

In the views file, we write the code that actually generates the webpages. This ties all the other parts together. When a user types in a URL, it is sent by the urls script we saw earlier to the views script, which then gets relevant data from the models, processes it, and passes it into a template, which finally gets served up as the page the user sees. We’ll take a look at those templates shortly. They’re the easiest part—mostly HTML.

Add the blog app to the list of INSTALLED_APPS in the settings.py file.

For a blog, we’ll need a table of posts, with several fields for the title, body text, author, the time it was written, and so on. A real blog would have comments, but that’s beyond the scope of today's demo.

These models are just a description. We need to make an actual database from them. First, however, we need MySQL running on our system. On an actual web server, this wouldn’t be a problem, because they usually have it preinstalled. 

To install MySQL, type:

To check if the installation is successful, use:

This should return something like this:

Now, create a MySQL database for the Django project. Run MySQL with sudo mysql , and at the prompt, enter:

Start the Development Server

You can now run python3.8 manange.py runserver in a new tab to start the development server.

But first, we need to configure the database settings. Let's take a look at settings.py .

You need to change the database settings first.

Now run the server and go to 127.0.0.1:8000 in your web browser. You should see the default Django page.

default Django page.

Configure the Blog in Django

Now, let's turn our Django site into a blog. First, we need to use our models to create tables in the database by creating the following migration to effect changes made to the models.

Now, run the migration to create tables in the database.

Create a Superuser

Now, you can create a superuser to administer your Django app.

Set Up the App URLs

Let's set up the URLs for the app in the urls.py file. We'll include the blog URLs from a separate file.

Create the First View

Let's create our first view, which will render a simple HTML page. Open blog/views.py and add the following code.

Create the View Template

This index.html file doesn't exist yet. Django will automatically load templates from the template directory. Create a folder called templates in the blog app and, inside it, create a file called index.html . The folder directory should look like this:

Add the following code in index.html . 

Now, we'll create our blog URLs. Create the file urls.py in the blog directory and write the URL path for serving the index page.

Now, if you navigate to http://127.0.0.1:8000/home , you should see the following page updated with this new content.

home page

Embed Data From the Database

The next step is to add dynamic content from the database. To accomplish this, Django has a templating language that allows you to embed variables with curly braces. Change the middle section of your page to look like this:

We can then pass in values to these variable placeholders from the views.py file by creating a dictionary of values.

Save and refresh, and you should see that you're now passing in content to a template from your views file. The final step is to get data from our database and pass that in instead. Luckily, we can do this without SQL queries by using Django's models. Go to blog/views.py and update the code to fetch data from the database.

Next, update the template to access this data.

Here, we can access all the data in our table in the views.py file, and then select only the first ten entries. We pass this data into the template, loop through the entries, and display the data with the HTML of our site.

Django's Admin System

The last thing we need to do today is review Django's administration system. This is a really powerful feature of Django that lets you manage your site without writing any more code, as you would have to if you were creating a site from scratch. To let the admin control your posts table, we'll register our Post model in Django admin and add some data in the database. Open blog/admin.py and add the following code.

You should now be able to add new blog entries by visiting http://127.0.0.1:8000/admin/blog/post/ .

That's all there is to do. You've just created a fully functioning, albeit simple, blog. To finish this lesson, we're going to look at installing Django on a web server.

Installing on a Web Server

There are two types of web hosting, and which one you have will affect whether you can use Django. If you have shared hosting, you're entirely at the mercy of your host.

Many cheap web hosts don’t support Python. While PHP is nearly guaranteed, support for other languages often isn’t. You'll have to check the control panel to determine if Python (and Django) are available. Obviously, the process is slightly different with every host. Almost all hosting runs on Apache, and we can use it to host Django, using the mod_wsgi or mod_python Apache modules.

Most web hosts run scripts in several languages using CGI. Django can run on FastCGI, and also, theoretically, on CGI, but this is not officially supported and would be far too slow for an actual production website. You’ll need to check if these are installed. They’re usually found under a heading, like “CGI and Scripting Language Support”.

If you have VPS hosting, or are lucky enough to have a dedicated server, your life is much easier. Usually these come with Python preinstalled, and from there, you only need to follow the same steps we went through to get a local copy of Django running. If you don't have Python, you can install it with a package manager. Your system may even come with Django.

Once you've installed Django on your server, upload the site you just made using any file transfer client. You can put the files anywhere, but keep them out of the public folder, or anyone will be able to see the source code of your site. I use /home for all my projects.

Next, create a MySQL database called django_blog  on your server. You'll have to create your account for the admin control panel again, but this is a one-time thing.

If you try to run this, you might receive an error, and that's because the settings for the server are different from those on your local computer. You may need to change the database password within settings.py , but depending on your server configuration, you may also encounter other issues. Google is your friend in these situations!

To run the server this time, the command is slightly different. You have to specify an IP address and port so that you can access the site over the internet.

If you visit your site in a web browser, on port 8000, you should see your site!

That's it for this lesson... and our series. I hope you've learned a number of useful skills over these past five lessons, and that you're ready to go on and learn even more Python in the future. If you like the look of Django and wish to continue increasing your knowledge of the framework, here are some additional tutorials on the subject:

how to create a web page with python

As always, I’m happy to discuss any questions about this tutorial or Python in general within the comments. Thanks for reading.

This post has been updated with contributions from  Esther Vaati . Esther is a software developer and writer for Envato Tuts+.

how to create a web page with python

how to create a web page with python

// Tutorial //

How to make a web application using flask in python 3.

Default avatar

By Abdelhadi Dyouri

How To Make a Web Application Using Flask in Python 3

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 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.

Prerequisites

Before you start following this guide, you will need:

Step 1 — Installing Flask

In this step, you’ll activate your Python environment and install Flask using the pip package installer.

If you haven’t already activated your programming environment, make sure you’re in your project directory ( flask_blog ) and use the following command to activate the environment:

Once your programming environment is activated, your prompt will now have an env prefix that may look as follows:

This prefix is an indication that the environment env is currently active, which might have another name depending on how you named it during creation.

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 env directory in your .gitignore file to avoid tracking files not related to the project.

Now you’ll install Python packages and isolate your project code away from the main Python system installation. You’ll do this using pip and python .

To install Flask, run the following command:

Once the installation is complete, run the following command to confirm the installation:

You use the python command line interface with the option -c to execute Python code. Next you import the flask package with import flask; then print the Flask version, which is provided via the flask.__version__ variable.

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 Application

Now 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 flask_blog directory, open a file named hello.py for editing, use nano or your favorite text editor:

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 :

In the preceding code block, you first import the Flask object from the flask package. You then use it to create your Flask application instance with the name app . You pass the special variable __name__ that holds the name of the current Python module. It’s used to tell the instance where it’s located—you need this because Flask sets up some paths behind the scenes.

Once you create the app instance, you use it to handle incoming web requests and send responses to the user. @app.route is a decorator that turns a regular Python function into a Flask view function , which converts the function’s return value into an HTTP response to be displayed by an HTTP client, such as a web browser. You pass the value '/' to @app.route() to signify that this function will respond to web requests for the URL / , which is the main URL.

The hello() view function returns the string 'Hello, World!' as a response.

Save and close the file.

To run your web application, you’ll first tell Flask where to find the application (the hello.py file in your case) with the FLASK_APP environment variable:

Then run it in development mode with the FLASK_ENV environment variable:

Lastly, run the application using the flask run command:

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 http://127.0.0.1:5000/ , you will receive the string Hello, World! as a response, this confirms that your application is successfully running.

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 hello.py is located, activate the virtual environment, set the environment variables FLASK_ENV and FLASK_APP , and continue to the next steps. (These commands are listed earlier in this step.)

Note : When opening a new terminal, it is important to remember activating the virtual environment and setting the environment variables FLASK_ENV and FLASK_APP .

While a Flask application’s development server is already running, it is not possible to run another Flask application with the same flask run command. This is because flask run uses the port number 5000 by default, and once it is taken, it becomes unavailable to run another application on so you would receive an error similar to the following:

To solve this problem, either stop the server that’s currently running via CTRL+C , then run flask run again, or if you want to run both at the same time, you can pass a different port number to the -p argument, for example, to run another application on port 5001 use the following command:

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 templates

Currently 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 render_template() helper function that allows use of the Jinja template engine . This will make managing HTML much easier by writing your HTML code in .html files as well as using logic in your HTML code. You’ll use these HTML files, ( templates ) to build all of your application pages, such as the main page where you’ll display the current blog posts, the page of the blog post, the page where the user can add a new post, and so on.

In this step, you’ll create your main Flask application in a new file.

First, in your flask_blog directory, use nano or your favorite editor to create and edit your app.py file. This will hold all the code you’ll use to create the blogging application:

In this new file, you’ll import the Flask object to create a Flask application instance as you previously did. You’ll also import the render_template() helper function that lets you render HTML template files that exist in the templates folder you’re about to create. The file will have a single view function that will be responsible for handling requests to the main / route. Add the following content:

The index() view function returns the result of calling render_template() with index.html as an argument, this tells render_template() to look for a file called index.html in the templates folder . Both the folder and the file do not yet exist, you will get an error if you were to run the application at this point. You’ll run it nonetheless so you’re familiar with this commonly encountered exception. You’ll then fix it by creating the needed folder and file.

Save and exit the file.

Stop the development server in your other terminal that runs the hello application with CTRL+C .

Before you run the application, make sure you correctly specify the value for the FLASK_APP environment variable, since you’re no longer using the application hello :

Opening the URL http://127.0.0.1:5000/ in your browser will result in the debugger page informing you that the index.html template was not found. The main line in the code that was responsible for this error will be highlighted. In this case, it is the line return render_template('index.html') .

If you click this line, the debugger will reveal more code so that you have more context to help you solve the problem.

The Flask Debugger

To fix this error, create a directory called templates inside your flask_blog directory. Then inside it, open a file called index.html for editing:

Next, add the following HTML code inside index.html :

Save the file and use your browser to navigate to http://127.0.0.1:5000/ again, or refresh the page. This time the browser should display the text Welcome to FlaskBlog in an <h1> tag.

In addition to the templates folder, Flask web applications also typically have a static folder for hosting static files, such as CSS files, JavaScript files, and images the application uses.

You can create a style.css style sheet file to add CSS to your application. First, create a directory called static inside your main flask_blog directory:

Then create another directory called css inside the static directory to host .css files. This is typically done to organize static files in dedicated folders, as such, JavaScript files typically live inside a directory called js , images are put in a directory called images (or img ), and so on. The following command will create the css directory inside the static directory:

Then open a style.css file inside the css directory for editing:

Add the following CSS rule to your style.css file:

The CSS code will add a border, change the color to brown, center the text, and add a little padding to <h1> tags.

Next, open the index.html template file for editing:

You’ll add a link to the style.css file inside the <head> section of the index.html template file:

Here you use the url_for() helper function to generate the appropriate location of the file. The first argument specifies that you’re linking to a static file and the second argument is the path of the file inside the static directory.

Upon refreshing the index page of your application, you will notice that the text Welcome to FlaskBlog is now in brown, centered, and enclosed inside a border.

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 index.html template. You can avoid unnecessary code repetition with the help of a base template file, which all of your HTML files will inherit from. See Template Inheritance in Jinja for more information.

To make a base template, first create a file called base.html inside your templates directory:

Type the following code in your base.html template:

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 <meta> tags provide information for the web browser, the <link> tag links the Bootstrap CSS files, and the <script> tags are links to JavaScript code that allows some additional Bootstrap features, check out the Bootstrap documentation for more.

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 index.html file:

Then replace its contents with the following:

In this new version of the index.html template, you use the {% extends %} tag to inherit from the base.html template. You then extend it via replacing the content block in the base template with what is inside the content block in the preceding code block.

This content block contains an <h1> tag with the text Welcome to FlaskBlog inside a title block, which in turn replaces the original title block in the base.html template with the text Welcome to FlaskBlog . This way, you can avoid repeating the same text twice, as it works both as a title for the page and a heading that appears below the navigation bar inherited from the base template.

Template inheritance also gives you the ability to reuse the HTML code you have in other templates ( base.html in this case) without having to repeat it each time it is needed.

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.

Index Page with Bootstrap

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 Database

In 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 sqlite3 module, which we will use to interact with the database, is readily available in the standard Python library. For more information about SQLite, check out this tutorial .

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 posts with the necessary columns. You’ll create a .sql file that contains SQL commands to create the posts table with a few columns. You’ll then use this file to create the database.

Open a file called schema.sql inside your flask_blog directory:

Type the following SQL commands inside this file:

The first SQL command is DROP TABLE IF EXISTS posts; , this deletes any already existing tables named posts so you don’t get confusing behavior. Note that this will delete all of the content you have in the database whenever you use these SQL commands, so ensure you don’t write any important content in 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:

Now that you have a SQL schema in the schema.sql file, you’ll use it to create the database using a Python file that will generate an SQLite .db database file. Open a file named init_db.py inside the flask_blog directory using your preferred editor:

And then add the following code.

You first import the sqlite3 module and then open a connection to a database file named database.db , which will be created once you run the Python file. Then you use the open() function to open the schema.sql file. Next you execute its contents using the executescript() method that executes multiple 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, you commit the changes and close the connection.

Save and close the file and then run it in the terminal using the python command:

Once the file finishes execution, a new file called database.db will appear in your flask_blog directory. This means you’ve successfully set up your database.

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 Posts

Now that you’ve set up your database, you can now modify the index() view function to display all the posts you have in your database.

Open the app.py file to make the following modifications:

For your first modification, you’ll import the sqlite3 module at the top of the file:

Next, you’ll create a function that creates a database connection and return it. Add it directly after the imports:

This get_db_connection() function opens a connection to the database.db database file, and then sets the row_factory attribute to sqlite3.Row so you can have name-based access to columns. This means that the database connection will return rows that behave like regular Python dictionaries. Lastly, the function returns the conn connection object you’ll be using to access the database.

After defining the get_db_connection() function, modify the index() function to look like the following:

In this new version of the index() function, you first open a database connection using the get_db_connection() function you defined earlier. Then you execute an SQL query to select all entries from the posts table. You implement the fetchall() method to fetch all the rows of the query result, this will return a list of the posts you inserted into the database in the previous step.

You close the database connection using the close() method and return 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 index page.

Open the index.html file:

Then, modify it to look as follows:

Here, the syntax {% for post in posts %} is a Jinja for loop, which is similar to a Python for loop except that it has to be later closed with the {% endfor %} syntax. You use this syntax to loop over each item in the posts list that was passed by the index() function in the line return render_template('index.html', posts=posts) . Inside this for loop, you display the post title in an <h2> heading inside an <a> tag (you’ll later use this tag to link to each post individually).

You display the title using a literal variable delimiter ( {{ ... }} ). Remember that post will be a dictionary-like object, so you can access the post title with post['title'] . You also display the post creation date using the same method.

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.

Index Page with Posts Displayed

Now that you’ve modified the index() view function to display all the posts you have in the database on your application’s homepage, you’ll move on to display each post in a single page and allow users to link to each individual post.

Step 6 — Displaying a Single Post

In 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 http://127.0.0.1:5000/1 will be a page that displays the first post (because it has the ID 1 ). The http://127.0.0.1:5000/ ID URL will display the post with the associated ID number if it exists.

Open app.py for editing:

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 get_post() . You can call it by passing it an ID and receive back the blog post associated with the provided ID, or make Flask respond with a 404 Not Found message if the blog post does not exist.

To respond with a 404 page, you need to import the abort() function from the Werkzeug library, which was installed along with Flask, at the top of the file:

Then, add the get_post() function right after the get_db_connection() function you created in the previous step:

This new function has a post_id argument that determines what blog post to return.

Inside the function, you use the get_db_connection() function to open a database connection and execute a SQL query to get the blog post associated with the given post_id value. You add the fetchone() method to get the result and store it in the post variable then close the connection. If the post variable has the value None , meaning no result was found in the database, you use the abort() function you imported earlier to respond with a 404 error code and the function will finish execution. If however, a post was found, you return the value of the post variable.

Next, add the following view function at the end of the app.py file:

In this new view function, you add a variable rule <int:post_id> to specify that the part after the slash ( / ) is a positive integer (marked with the int converter) that you need to access in your view function. Flask recognizes this and passes its value to the post_id keyword argument of your post() view function. You then use the get_post() function to get the blog post associated with the specified ID and store the result in the post variable, which you pass to a post.html template that you’ll soon create.

Save the app.py file and open a new post.html template file for editing:

Type the following code in this new post.html file. This will be similar to the index.html file, except that it will only display a single post, in addition to also displaying the contents of the post:

You add the title block that you defined in the base.html template to make the title of the page reflect the post title that is displayed in an <h2> heading at the same time.

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 3 so far):

Going back to the index page, you’ll make each post title link to its respective page. You’ll do this using the url_for() function. First, open the index.html template for editing:

Then change the value of the href attribute from # to {{ url_for('post', post_id=post['id']) }} so that the for loop will look exactly as follows:

Here, you pass 'post' to the url_for() function as a first argument. This is the name of the post() view function and since it accepts a post_id argument, you give it the value post['id'] . The url_for() function will return the proper URL for each post based on its ID.

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 Posts

Now 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 Post

Up 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 app.py file for editing:

First, you’ll import the following from the Flask framework:

Add the imports to your file like the following:

The flash() function stores flashed messages in the client’s browser session, which requires setting a secret key . This secret key is used to secure sessions, which allow Flask to remember information from one request to another, such as moving from the new post page to the index page. The user can access the information stored in the session, but cannot modify it unless they have the secret key, so you must never allow anyone to access your secret key. See the Flask documentation for sessions for more information.

To set a secret key , you’ll add a SECRET_KEY configuration to your application via the app.config object. Add it directly following the app definition before defining the index() view function:

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:

This creates a /create route that accepts both GET and POST requests. GET requests are accepted by default. To also accept POST requests, which are sent by the browser when submitting forms, you’ll pass a tuple with the accepted types of requests to the methods argument of the @app.route() decorator.

To create the template, open a file called create.html inside your templates folder:

Add the following code inside this new file:

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 {{ request.form['title'] }} and the text area has the value {{ request.form['content'] }} , this is done so that the data you enter does not get lost if something goes wrong. For example, if you write a long post and you forget to give it a title, a message will be displayed informing you that the title is required. This will happen without losing the post you wrote since it will be stored in the request global object that you have access to in your templates.

Now, with the development server running, use your browser to navigate to the /create route:

You will see a Create a New Post page with a box for a title and content.

Create a New Post Page

This form submits a POST request to your create() view function. However, there is no code to handle a POST request in the function yet, so nothing happens after filling in the form and submitting it.

You’ll handle the incoming POST request when a form is submitted. You’ll do this inside the create() view function. You can separately handle the POST request by checking the value of request.method . When its value is set to 'POST' it means the request is a POST request, you’ll then proceed to extract submitted data, validate it, and insert it into your database.

Modify the create() view function to look exactly as follows:

In the if statement you ensure that the code following it is only executed when the request is a POST request via the comparison request.method == 'POST' .

You then extract the submitted title and content from the request.form object that gives you access to the form data in the request. If the title is not provided, the condition if not title would be fulfilled, displaying a message to the user informing them that the title is required. If, on the other hand, the title is provided, you open a connection with the get_db_connection() function and insert the title and the content you received into the posts table.

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 redirect() function passing it the URL generated by the url_for() function with the value 'index' as an argument.

Now, navigate to the /create route using your web browser:

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 base.html template to have easy access to this new page. Open the template file:

Edit the file by adding a new <li> tag following the About link inside the <nav> tag. Then add a new for loop directly above the content block to display the flashed messages below the navigation bar. These messages are available in the special get_flashed_messages() function Flask provides:

Save and close the file. The navigation bar will now have a New Post item that links to the /create route.

Editing a Post

For 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 app.py file. Its view function will receive the ID of the post that needs to be edited, the URL will be in the format / post_id /edit with the post_id variable being the ID of the post. Open the app.py file for editing:

Next, add the following edit() view function at the end of the file. Editing an existing post is similar to creating a new one, so this view function will be similar to the create() view function:

The post you edit is determined by the URL and Flask will pass the ID number to the edit() function via the id argument. You add this value to the get_post() function to fetch the post associated with the provided ID from the database. The new data will come in a POST request, which is handled inside the if request.method == 'POST' condition.

Just like when you create a new post, you first extract the data from the request.form object then flash a message if the title has an empty value, otherwise, you open a database connection. Then you update the posts table by setting a new title and new content where the ID of the post in the database is equal to the ID that was in the URL.

In the case of a GET request, you render an edit.html template passing in the post variable that holds the returned value of the get_post() function. You’ll use this to display the existing title and content on the edit page.

Save and close the file, then create a new edit.html template:

Write the following code inside this new file:

This code follows the same pattern except for the {{ request.form['title'] or post['title'] }} and {{ request.form['content'] or post['content'] }} syntax. This 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 current database data.

Now, navigate to the following URL to edit the first post:

You will see an Edit “First Post” page.

Edit a 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 index.html template file:

Edit the file to look exactly like the following:

Here you add an <a> tag to link to the edit() view function, passing in the post['id'] value to link to the edit page of each post with the Edit link.

Deleting a Post

Sometimes 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 / ID /delete route that accepts POST requests, similar to the edit() view function. Your new delete() view function will receive the ID of the post to be deleted from the URL. Open the app.py file:

Add the following view function at the bottom of the file:

This view function only accepts POST requests. This means that navigating to the / ID /delete route on your browser will return an error because web browsers default to GET requests.

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 get_post() function.

Then you open a database connection and execute a DELETE FROM SQL command to delete the post. You commit the change to the database and close the connection while flashing a message to inform the user that the post was successfully deleted and redirect them to the index page.

Note that you don’t render a template file, this is because you’ll just add a Delete button to the edit page.

Open the edit.html template file:

Then add the following <form> tag after the <hr> tag and directly before the {% endblock %} line:

You use the confirm() method to display a confirmation message before submitting the request.

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.

This 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:

Want to deploy your application quickly? Try Cloudways, the #1 managed hosting provider for small-to-medium businesses, agencies, and developers - for free. DigitalOcean and Cloudways together will give you a reliable, scalable, and hassle-free managed hosting experience with anytime support that makes all your hosting worries a thing of the past. Start with $100 in free credits!

Learn more here

Still looking for an answer?

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Excellent tutorial! It isn’t common that a posted tutorial runs exactly as staged as the instructions suggest, but everything went according to plan (with the exception of running this under Windows 10 as opposed to Linux).

Made sure to sign up just to leave this comment, but this guide deserves it. Thank you very much!

This is a great tutorial! This as definitely helped me understand the basics of web development using Flask!Do you have anymore articles/ resources that you would recommend a beginner?

There’s a slight part that the tutorial didn’t cover. The blog posts don’t render newlines

This tutorial is GREAT! Everything works as it should and is well explained (with the exception of how to use ‘set’ instead of ‘export’ to set environment variables in Windows).

thank you for such an easy to follow tutorial and all your brilliant explanations.

In Step 5 it doesn’t show the post line like in the screenshot. I’ve tried several times from the start to make sure and the result is still the same no change. There seems to be a missing part in this tutorial. Hope admin check it again. 🙏

This tutorial is awesome! It helped me understand the basics so easily and it works as expected in each step as explained with screenshots. Thanks for taking the time out to put this together.

This has to be the best tutorial I’ve ever read. Loving how much effort you have put into this - from carefully explaining the concepts and how all the code works, to even visually highlighting the code that we’re supposed to modify in each snippet. I signed up just so I could leave a comment, because this article greatly deserves it. Awesome, just awesome <3

This comment has been deleted

Creative Commons

Popular Topics

Try DigitalOcean for free

Join the tech talk.

Please complete your information!

Python Tutorial

How do you use Python to make websites?

In this article, we will discuss how to use Python to make websites.

Python is a 1991 programming language that has increased in popularity over the last decade. Python coders are in high demand in the computer industry nowadays.

Python is a general-purpose programming language, which means it can be used to develop practically any kind of computer program, including websites. It's a programming language that benefits any developer because it's very simple to learn while still being powerful enough for some of the most complex applications available.

If you want to learn how to design a website with Python, you need to be familiar with the language as well as with how websites work.

Why Should You Use Python to Develop a Website?

Python is a computer language that may be used to develop a wide range of different things, including websites. Making websites with Python is simpler than most people believe due to the fact that this language makes use of "frameworks."

Frameworks are prebuilt selections of code designed to do specific tasks. When building a website, for example, frameworks provide structure, execute common operations, and much more. Simply put, you may utilize a framework to drastically reduce the amount of real code you must execute, saving you a significant lot of time.

Some Sites Created Using Python

The following are some examples of websites made with the Python programming language. These demonstrate the coding language's versatility:

Google − Python is used by Google, the world's most prominent search engine.

Instagram − Instagram's backend was built with Python.

Spotify − Python is one of the reasons Spotify can offer audio files virtually with almost no delay.

Netflix − Python was used to code most of the Netflix website and overall service.

Uber  − Uber has transformed the ride-sharing industry, and its service is developed in Python.

Of course, millions of other websites use Python for some or all of their programming, and the number is increasing on a daily basis.

Using Python to make websites

Building a website from scratch will take time and work regardless of the language you select. Python makes many aspects of website development faster and easier, but you must still ensure that everything is in place and that all necessary steps are taken. The following are only a few of the important steps to effectively building a Python-coded website.

Set Up Python Web Hosting

You'll need good hosting, just like any other website. Almost all web hosting firms today will enable running Python-based pages. However, some are better than others or specialize in hosting these types of sites.

Taking the time to pick the correct hosting company for your Python website can help you avoid problems later on. While most hosting firms can support Python-based sites, those that do not focus on it may not keep their systems up to date with the latest Python versions. If you start using new versions before the hosting provider is ready, this can cause your website to load incorrectly.

Choose Framework

Choosing a framework is one of the most crucial tasks in building a website using Python. There are numerous popular frameworks that will make creating a website faster and easier. The following Python frameworks are among the most widely used today:

Django, is a free and open-source Python framework, that allows developers to fastly create complex code and apps. The Django framework aids in the development of high-quality web applications. It is one of the greatest Python frameworks for the rapid creation of APIs and web applications.

The Django framework has been used to create over 12,000 well-known projects. Furthermore, it is one of the more experienced Python web development frameworks.

This high-level framework simplifies web application development by providing a variety of powerful features. It features a massive library collection and emphasizes effectiveness, less coding, and component reusability.

Web2py is a Python-based platform for creating dynamic web content. The technology has included a code editor, debugger, and deployment tools from its initial release in 2007. Web2py is a Python library that allows you to create dynamic web content.

Flask is a Python framework inspired by the Sinatra Ruby framework that is accessible under the BSD licence. Flask is dependent on the Werkzeug WSGI toolbox and the Jinja2 template. The main goal is to assist in the development of a robust web application base.

The Python backend framework can be developed in any way that developers require; however, it was built for open-ended applications. Flask has been employed by large corporations such as LinkedIn and Pinterest. Flask, in comparison to Django, is best suited for tiny and simple projects. As a result, you may predict web server development, Google App Engine support, and built-in unit testing.

The bottle is a WSGI microweb framework, which means it is a single file with no dependencies other than a distributed module in the Python Standard Library. All of this is included in the framework, as well as request dispatching through URL, key/value databases and templates, and built-in HTTP server support.

AIOHTTP is an asynchronous framework with both server and client-side functions, making it ideal for a wide range of websites.

Not only these we have many more like NumPy, Pandas, Matplotlib, CherryPy, etc.

Code Your Website

Once you've chosen and installed your framework, you'll be ready to start coding your website. This is where you'll spend the majority of your time, and many first-time users are amazed at how fast it can go.

The majority of the tasks that must be manually coded when using other languages are already in place, due to the established Python frameworks.

An expert Python developer can have a website up and running in a few hours. Using the correct frameworks, you could get a very simple site up and running in under an hour. A typical website will take around a day to complete, excluding the creation of the site's content.

Note that when you've created your site, you'll need to regularly update and improve it to keep it current and function properly.

Some Popular Resources

Digital.com’s Python for Beginners Page

Python’s Official Website

Python Class from Google

Python Videos

Languages and Frameworks

You can spend numerous hours researching and investigating your alternatives for developing a website. In the end, it's best to give it a chance. One of the best things about Python is that it is simple to learn and produces measurable results rapidly. If you want to create a website with Python, the best thing you can do is give it a shot.

Vikram Chiluka

Tutorials Point

how to create a web page with python

Build a Website with Python

To begin with, install flask:

Step #1: Minimal Web Application

The minimal application can be found at https://flask.palletsprojects.com/en/2.0.x/quickstart/#a-minimal-application . This is a web page that displays “Hello World”. The first thing we did was create an instance of Flask() with “__name__” as the argument. The route decorator is used to inform Flask the URL that will activate the function we wrote.

Next, in the terminal of PyCharm, type the following (where the name of my Python file is main.py; in your case, replace main.py with your Python’s filename):

Once you run “flask run”, the terminal will chuck out a URL with a port. This URL:PORT is where the web page is loaded. You can always press Control + c to quit. In my case, it says “Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)”. So, open up your web browser, and copy and paste the URL given. In my case, I copied and pasted “http://127.0.0.1:5000/”. Please also note that the previous lines must be run every time you restart PyCharm for it to work:

how to create a web page with python

Step #2: Adding HTML

The first thing you’ll need to do is open the folder where the Python script is located and create a folder called “templates”. When I first ran this, I tried putting the name “template” as the folder name, and the whole program crashed and didn’t work. So, it’s imperative that you call the folder “ templates ”. Within this “templates” folder, create an index.html file with your HTML code. Then, use render_template() and pass “index.html” as the argument. Now, if you run “flask run” in the terminal, your HTML code should be rendered:

My html code (index.html) for the moment is as follows:

And, my Python file code (main.py) is as follows:

The latter will render a simple HTML page.

Step #3: Adding CSS

Now, I want to add CSS to my HTML. To do this, create a folder called “static” and create a file called “main.css”. Here, the name of the actual CSS file can be anything. I’ve decided to call mine “main.css”. However, the name of the folder must be “static”! In fact, in the “static” folder, one can place anything that is static, such as CSS, JavaScript, and images. So, if you’re going to put images, JavaScript, and CSS, you may wish to create sub-folders.

how to create a web page with python

First, let’s write out the CSS (main.css) I want:

Here, in the index.html, we need to write & lt;link rel=”stylesheet” type=”text/css” href=”{{ url_for(‘static’, filename=’main.css’)}}”> in the head of the HTML file. Here, the filename is the name of the CSS file (mine is main.css). If for instance the “main.css” is located with a sub-folder called “css”, then you’d write the following:

After that, you can use the CSS you have created. For instance, I created one called “styled”, and used it in the h1 class.

My index.html file would be as follows:

The main Python file – main.py – stays the same.

Step #4: Adding an Image

Now, let’s add an image to the HTML page we created! For this, we use the “static” folder we created. Within the “static” folder, I created another folder called “images”. Within the images folder, I placed an image. Now, let’s add the image to the HTML code as follows: <img src=”/static/images/kalyani.jpg” height=”200″ /> . In this case, I set the height of the image to 200, but you can change it to whatever you want and add CSS if you want.

how to create a web page with python

The HTML code would look as follows:

Alternatively, one can also use the following:

Step #5: Adding JavaScript

There are two ways you can add JavaScript. In this first demo, I will create a button. When the button is pressed, it would activate a function called myFunction() which will be JavaScript (found in the <script> tag). For this, set up the button. Then, set up a script tag in the head of the HTML code and within it, define a function. In my case, I’ve defined a function that will add the “whole resume” to a p element upon button click.

You can add it to the index.html file as follows:

However, in most cases, JavaScript files tend to be documents themselves, and not one liners. In such cases, we’d have a .js file that we have to link. In my case, I’d write: <script src=”/static/javascript/javascript.js”> </script> . So, much like the image file, we link the js file as follows:

Alternatively, you can also use this: <script src=”{{ url_for(‘static’, filename=’javascript/javascript.js’)}}”></script> . The latter would generate this HTML code:

About the author

how to create a web page with python

Kalyani Rajalingham

I'm a linux and code lover.

how to create a web page with python

Towards Data Science

Daniel Ellis Research

Nov 23, 2020

Member-only

Using Python to create static web pages — the easy way!

Substituting data into a text template using python and jinja2. this can be used for document, report and script generation — as well as static html pages., introduction and aims.

For the purpose of this article, I wish to create web page summarising all my Medium articles. I start with a list of Titles, Subtitles and URLs and convert them into a static HTML page for viewing on my personal GitHub .io site.

This can be done in one of three ways:

Side Note: It is possible to accomplish the same task using Flask, however render_template already uses Jinja2 under the hood and we do not want the additional requirement of needing a webserver — so we ignore this solution.

The Copy Paste Method

This is probably the most widely used, but least efficient method. For a small number of files, this can be a quick and easy implementation, however, with >10 data points, this becomes time-consuming and prone to error.

An example of our desired output for 3 image tags can be in the form of:

Python string Formatting

We can also use pythons string manipulation capabilities to generate a string in the correct format, and then write it to file. This can be done in one of two ways:

List format

If we have our data in a nested list format:

We can generate the above using the following script:

Dictionary Format

If our data is a dictionary format — say from a pandas data frame or JSON file, we can again use string formatting to assemble a file template.

Here we can iterate over each object in the dictionary using the values() function and proceed similarly to before. Note that I have used the naming ability of python’s c-style formatting ( Python2 and Python3 compatible )

This method works well for small files but can get confusing when you have many different datasets, which need to be inserted in different locations. Similarly, it would be convenient not to have long strings HTML code within our python program, for readability purposes — this is when Jinja comes in.

Using Jinja2

Jinja is a templating language for use with Python. In essence, it populates sections within a text template with data that is provided within it. It has most likely already been installed with your Python distribution, but if not we can obtain it from the PiPy repository pip install Jinja2 .

Creating a Template

The first thing we need to do when using Jinja is to create a template. This can be done by opening an empty file e.g. template.html in a text editor and populating it with any code that will not change.

Next, we can add sections that we wish to update using our python program. To start off I want to add a title.

Note how we include our variable name (in this case title ) within two sets of curly braces. This tells Jinja where it needs to substitute information.

Getting Python to populate the template

Now we have a template we want to be able to tell python to use it to create a new file. To do this we can make use of the following program:

Here we create a Jinja environment and read template.html from the current ( ./ ) directory. Within this, we supply the variable title which was defined in python and produce a formatted string from the template. Finally, we take this string and write it to a file of our choosing to produce:

Lists in Jinja

Now we have a working program, we can make use of Jinja’s ability to iteratively create elements within our template. To do this we can recreate the output from the ‘List Formatting’ section by adding the following lines to our template:

This goes through all items in the arbitrarily named mydata variable and creates an image element for it.

We also need to update the python script so that it knows what the value of my data is before re-running.

Dictionaries in Jinja

Similar to lists, we can also use dictionaries for more complex substitutions. To do this we change our iterator to go through each item, and can even access additional elements using their keys (e.g. value['src'] )

This example requires the same python program as before but using the data from the ‘Dictionary Formatting’ example (earlier).

Pandas and dictionaries

If you have loaded your data as a pandas dataframe, it is possible to convert this into a row-wise dictionary containing all the columns as variables. To do this we take the transpose of the dataframe and use the to_dict function:

Composite, Nested Example

Finally to conclude it is possible to use a mixture of item types and even nest them. For the image strips shown in the headline image, I was required to separate my images into separate div (groups) of 8. To do this I started with a list, where each element contained the data for 8 images — For simplicity, we shall use two elements of two for the example.

We now iterate over each of the two elements of the list and create a new <div> element:

Within each of those, we want to create as many images exist in the variable I have named divitem . This can be done by placing another loop within the existing one:

And there we have it, an HTML template with the format

We have successfully used Jinja to iteratively substitute data into a pre-defined template and greatly reduce the amount of manual work needed. Jinja allows us to automate document and file construction tasks and does not require a webserver to view any generated HTML pages. The final result of my project can be seen on my github.io page using the link below.

Dan's Published Medium Articles

In october 2019 i started to write medium articles as a way of recording information from projects i was on. here is a….

wolfiex.github.io

Other formats

Jinja can also work for many other text file formats, including LaTeX , CSVs and even other scripts . It has the ability to run conditionals, filter data or escape character and whitespace in your formatting. To find out more, have a look at the additional resources section below.

Resources / Documentation:

Template designer documentation - jinja documentation (2.11.x), this document describes the syntax and semantics of the template engine and will be most useful as a reference to those….

jinja.palletsprojects.com

More from Towards Data Science

Your home for data science. A Medium publication sharing concepts, ideas and codes.

About Help Terms Privacy

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store

Daniel Ellis Research

Research Software Engineer specialising in High-Performance Computing and Data Visualisation. — PhD in Atmospheric Chemistry and Masters in Theoretical Physics.

Text to speech

IMAGES

  1. Python BeautifulSoup Tutorial: Web Scraping In 20 Lines Of Code

    how to create a web page with python

  2. Create Web Application Using Python : Python Web Development Tutorials Real Python : That's the

    how to create a web page with python

  3. Python

    how to create a web page with python

  4. A Complete Guide to Web Development in Python

    how to create a web page with python

  5. Get Free Website Hosting Python Pics

    how to create a web page with python

  6. Category: pro

    how to create a web page with python

VIDEO

  1. create web page.... help with HTML & BASIC CSS

  2. How to design Video Player in HTML

  3. Website by Google App Script (Part-3: Code.gs + Html + CSS + JavaScript)

  4. lecture 11 -part 2 (Web Development

  5. lecture 7 -1 (Web Design)

  6. Opening Website with python #developer #python #programming #pythonprogramming #codes #code #coder

COMMENTS

  1. How To Build a Website With Python

    Examples of Sites Created Using Python · Google: The most popular search engine in the world uses Python · Instagram: Python was used to create the backend of

  2. Make A Python Website As Fast As Possible!

    Welcome to another video! In this video, I'm going to show you how to create a website using python as fast as possible.

  3. Python Website Full Tutorial

    In this video, I'm going to be showing you how to make a website with Python, covering Flask, authentication, databases, and more.

  4. How to create a website using Python (an introduction)

    A step-by-step guide to create a website using Python · Step 1: Get a handle on HTML and CSS · Step 2: Master the basics of JavaScript · Step 3:

  5. Create Basic Webpage with Pyscript

    The Pyscript is a python framework/library that allows us to write python code inside HTML directly with the help[ of pyscript tag. Pyscript is

  6. Python From Scratch: Create a Dynamic Website

    Add the following code in index.html. ... Now, we'll create our blog URLs. Create the file urls.py in the blog directory and write the URL path

  7. How To Make a Web Application Using Flask in Python 3

    Flask uses the Jinja template engine to dynamically build HTML pages using familiar Python concepts such as variables, loops, lists, and so on.

  8. How do you use Python to make websites

    Web2py is a Python-based platform for creating dynamic web content. The technology has included a code editor, debugger, and deployment tools

  9. Build a Website with Python

    Build a Website with Python · Step #1: Minimal Web Application · Step #2: Adding HTML · Step #3: Adding CSS · Step #4: Adding an Image · Step #5: Adding JavaScript.

  10. Using Python to create static web pages

    Python string Formatting · data = [ ['image1.png','This is image1'], ['image2. · for src,alt in data: xmlcode+= '<img src="%s" alt="%s"></img>\n'%