Most newbie programmers think of Python as the language of data scientists. However, Python is a lot more versatile. It is a general-purpose programming language, which means you can use it to create video games, automate tasks, and even build websites.
Picking up Python is easier than learning heavily-typed languages like Java and low-level languages like C. What's more, Python is feature-packed, so much so that you can build surprisingly advanced web apps with it. So, Python makes an excellent addition to any web developer and new programmer's toolkit.
In this guide, we explore how you can build a website with Python as a beginner.
How to Create a Website with Python
Building a website with Python is much easier than you'd think. This is because you can use a Python framework to build it. But what even is a framework?
A framework is a set of libraries, tools, and conventions that make creating software faster and easier. In simple words, frameworks comprise reusable code that follows the best practices.
With a framework, a developer can focus on building specific functionalities into their software or website without having to write its base components from scratch. You'd be surprised to learn that Google's "webapp2" framework drives most of the company's web services, including Google Drive and Maps.
In fact, nearly every popular online platform – Uber, Netflix, and Instagram included – uses Python in some capacity.
But it's important to note that even if you use a potent framework, you will need to spend some time and effort to build a website. Moreover, you will need to set up all of a website's essential components before you can launch it.
In other words, there is no avoiding the use of HTML for creating your website's structure. You will also need to purchase a domain and hosting for your website. But it all begins by choosing a Python framework to build your site. The Django and Flask frameworks are excellent options for beginners who want to build a site using Python.
Step #1: Choose and Install a Framework
The Django framework for Python boasts several features that make it the ideal choice for creating large applications. On the other hand, Flask is a lightweight Python framework ideal for smaller, simpler websites.
In this guide, we explore how you can use both of these frameworks. However, you must pick between them. To install Django, navigate to your terminal and run:
pip install Django
To install Flask, type the following in your terminal:
pip install flask
Step #2: Set Up Your Project
Now that your framework of choice is ready to use, you must initialize it in your new project's folder. The setup process is slightly different for Django and Flask.
Setting Up a Django Project
If you've chosen to work with Django, you do not have to set up your project's files yourself. You can do it by running the following command in the command prompt or terminal:
django-admin startproject projectname
Of course, the command above will only work if you're using Django. Note that you must change "projectname" to the name you wish to give your project. Running this command creates a directory with the project name you supply and also sets up your Django project's basic structure. Here's what it looks like:
- The outer directory (projectname) contains the project's configuration files.
- Inside the project directory, you'll find a manage.py file, which is a command-line utility to interact with your project.
- There will be another directory with the same name as your project, which is the main project package.
After your project's files are ready, you must run the development server. To do this, go to your project's directory, and run this command:
python manage.py runserver
The command launches a local server, allowing you to access the site you build at http://localhost:8000/.
Setting Up a Flask Project
If you've chosen Flask as your framework, you won't need to initialize it with a command. However, you will need to create your project's files manually.
Begin by creating a Python file that serves as your application. You can do this in your IDE or create a new text file and save it with the .py extension. Inside this file, you must create an instance of the Flask class with the following code:
from flask import Flask app = Flask(__name__)
You must also define the routes and views of your website in this same file. The routes are the URLs that you allow your site's visitors to access. The views are functions that can handle the requests your users make. We discuss how to create views and templates in detail in the sections to follow.
Like in Django, you must run the development server in Flask, too. You can do this by putting the following lines at the bottom of your Flask project:
if __name__ == '__main__': app.run(debug=True)
Now that the server is set to run, you can start it. In the folder with your .py file, open the terminal and run the following command:
python filename.py
This command starts the development server, and you can access your website at http://localhost:5000/ in your web browser.
Both Django and Flask offer more features and functionalities to help you build complex web applications. Once your project is set up, you can proceed to create views and templates and add other components to develop your website further.
Step #3: Define Your Website's Structure
This step entails designing the overall structure of your website. You must define URL routes, create HTML templates, and organizing static files such as CSS, JavaScript, and images. Let's see how you can do all this using both Django and Flask:
Defining a Website's Structure in Django
You must begin with URL routing. In Django, URL routing is defined in the urls.py file of your project. This file maps your site's URLs to their corresponding views, which are responsible for handling user requests. Here's what this file should look like:
# projectname/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('about/', views.about, name='about'), # Additional URL patterns must be mentioned here (if required) ]
Next, you must define the views. Again, views are Python functions that receive user requests and return HTTP responses. In Django, views are typically defined in the views.py file of your app. Here's what this file should look like:
# appname/views.py from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse("Welcome to the home page") def about(request): return HttpResponse("This is the about page")
Now, you're ready to set up a template for your website. Django uses templates to render dynamic HTML content. In simple words, templates are HTML files that typically include placeholders (variables) for dynamic data.
To create a template, you must create a "templates" directory inside your project folder and store your HTML files in it. For instance, your website's home page will have a template like this:
<!-- home.html --> <!DOCTYPE html> <html> <head> <title>Home Page</title> </head> <body> <h1>{{ title }}</h1> <p>Welcome to our website!</p> </body> </html>
Finally, you must add all the relevant static files to your project. Static files are the images, JavaScript, and CSS files that are visible on your website. To store these files, you must create a "static" folder inside your project's directory.
The images, JavaScript, and CSS files must be moved inside folders named "img," "js," and "css," respectively. But placing these files in your project's folder won't make them appear on your website. You must link the files to your website within each page's HTML template, like so:
<!-- home.html --> <!DOCTYPE html> <html> <head> <title>Home Page</title> <link rel="stylesheet" href="{% static 'css/style.css' %}"> </head> <body> <h1>{{ title }}</h1> <p>Welcome to our website!</p> <img src="{% static 'img/logo.png' %}" alt="Logo"> <script src="{% static 'js/script.js' %}"></script> </body> </html>
Defining a Website's Structure in Flask
The URL routes for your site must be defined using Python decorators. As mentioned earlier, the routes are typically defined in the main Python file but can be defined in separate modules.
Here's an example of what decorators should look like inside your Python file:
# app.py from flask import Flask app = Flask(__name__) @app.route('/') def home(): return 'Welcome to the home page' @app.route('/about/') def about(): return 'This is the about page'
Flask uses the Jinja2 templating engine to render dynamic HTML content. Like in a Django project, you must create a "templates" folder in your project's directory and place your HTML templates inside it.
Of course, you also need to place your project static files – the images, CSS, and JavaScript files – inside a "static" folder in your project's directory. Just like in Django, the files must be placed in the "css," "js," and "img" folders.
However, unlike in Django, you must use the url_for function to include the static files in your template:
<!-- home.html --> <!DOCTYPE html> <html> <head> <title>Home Page</title> <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}"> </head> <body> <h1>{{ title }}</h1> <p>Welcome to our website!</p> <img src="{{ url_for('static', filename='img/logo.png') }}" alt="Logo"> <script src="{{ url_for('static', filename='js/script.js') }}"></script> </body> </html>
Now that your site's structure is defined, it's time to concretize the responses your website is supposed to cater to your users.
Step #4: Create Routes and Views
Handling user requests is an essential aspect of any functional and dynamic website. To do this in Django, you will need to define the responses of requests in your Django file's views. On the other hand, if you're using Flask, you will need to define the responses to requests in the routes.
Creating Views in Django
Besides rendering your template, views in Django are also responsible for processing data and interacting with the database (if your site is connected to one). Here's how you must define the desired responses in the views.py file:
# appname/views.py from django.shortcuts import render def home(request): context = { 'title': 'Welcome to Our Website!', } return render(request, 'home.html', context) def about(request): context = { 'title': 'About Us', } return render(request, 'about.html', context)
As you can see, the view home() renders the home.html template, and the view about() renders the about.html template. Also, note that the context dictionary is used to pass user-generated data to the templates.
Creating Routes in Flask
So far, we've learned that every route in Flask corresponds to specific URLs. But the routes also define the logic involved in processing a request the user makes, and subsequently returning a response.
Here's how you can define the processing logic in your primary Python file with Flask code in it:
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): title = 'Welcome to Our Website!' return render_template('home.html', title=title) @app.route('/about/') def about(): title = 'About Us' return render_template('about.html', title=title)
In the above example, the views home() and about() return the rendered templates home.html and about.html, respectively. The title variable is passed as an argument to the render_template() function to provide dynamic data to the templates.
Now, you have a website that is ready to go live – as long as you don't want features that require a database to function. But note that adding a database to your website can enable features such as user authentication, content management, and personalization.
In Django, you can use the built-in ORM (Object-Relational Mapping) to interact with databases easily. In Flask, you can choose from various database libraries like SQLAlchemy to handle database operations. However, the instructions for adding a database to your website are outside of the scope of this guide.
Best Practices to Follow When Building a Website with Python
When delving into Python web development, it's essential to follow some best practices to ensure code that is tidy, efficient, and easy to maintain. Here are some vital points to keep in mind:
#1 Use a Virtual Environment
Virtual environments create isolated Python environments for your projects. Tools like virtualenv or Python's built-in venv module enable you to create virtual environments.
These isolated environments allow you to manage dependencies and prevent conflicts between packages. Using virtual environments guarantees project-specific dependencies and prevents cluttering your global Python installation.
#2 Use the MVC Pattern
The Model-View-Controller pattern is a software architectural pattern commonly employed in web development. It segregates your application into three components: models (representing data and business logic), views (handling user interface), and controllers (managing the flow between models and views). Following this pattern enhances code modularity and maintainability.
#3 Utilize Database Abstraction Layers
Using an ORM (Object-Relational Mapping) library like SQLAlchemy is one of the best ways to interact with a database. Such libraries facilitate database interactions with Python objects and queries rather than giving direct access to the database layer.
In addition to supplying a layer of abstraction, using such libraries makes interacting with databases easier. They also make switching to other database systems simpler.
#4 Write Unit Tests
Unit testing is crucial for detecting potential bugs early into development. It is also essential to maintaining code quality. You can use Python's built-in testing framework, unittest, for this purpose. You can also utilize third-party libraries like pytest to make writing unit tests easier.
Every component of your web app must have a unit test, including your site's models, views, and controllers. Most development teams choose to automate tests. This helps the devs to remain certain that later changes to the code don't introduce problems.
Conclusion
Python is one of the most powerful languages you can build websites with. Though the language is relatively easy to learn, making a website with it demands several steps and a lot of setup.
But now that you've learned the basics of Python web development and are familiar with two of the most popular frameworks for the purpose, you're one step closer to getting your website live on the internet.