Robin.te.Hofstee

How to Set Up a Python Web Server

Robin te Hofstee6 min readViews7
How to Set Up a Python Web Server

A detailed tutorial on setting up a Python web server using Flask and deploying it locally.

Introduction to Python Web Servers

A Python web server allows you to run web applications written in Python. One of the most popular frameworks for this purpose is Flask, which is lightweight and easy to use. In this tutorial, we will set up a basic Python web server using Flask, deploy it locally, and explore some of its advanced features.

Setting Up Flask

Before you can start writing your web server application, you need to set up Flask. Flask is a micro web framework for Python, and it is very easy to install and use.

Installing Flask

First, you need to install Flask. Open your terminal or command prompt and run the following command:

pip install Flask

Flask will be installed along with its dependencies.

Creating a Flask Application

Now that Flask is installed, you can create your first Flask application. Create a new Python file called app.py and add the following code:

from flask import Flask
 
app = Flask(__name__)
 
@app.route('/')
def home():
    return "Hello, World!"
 
if __name__ == '__main__':
    app.run(debug=True)

This code sets up a basic Flask application. The app.route('/') decorator defines the URL endpoint where the home function will be executed. The app.run(debug=True) line starts the server and enables debug mode, which is useful for development.

Running the Flask Application

To run your Flask application, open a terminal or command prompt, navigate to the directory where app.py is located, and run the following command:

python app.py

If everything is set up correctly, the server will start, and you will see a message indicating that the server is running on http://127.0.0.1:5000/. Open your web browser and go to http://127.0.0.1:5000/, and you should see the message "Hello, World!" displayed.

Customizing the Home Page

You can customize the home page by changing the home function. For example, you can return a more detailed HTML response:

from flask import Flask
 
app = Flask(__name__)
 
@app.route('/')
def home():
    return '''
    <html>
        <head>
            <title>My Flask App</title>
        </head>
        <body>
            <h1>Welcome to My Flask App</h1>
            <p>This is a simple Flask web server.</p>
        </body>
    </html>
    '''
 
if __name__ == '__main__':
    app.run(debug=True)

Now, when you refresh your browser, you should see a more structured HTML page.

Adding Routes and Handling Requests

Flask allows you to define multiple routes and handle different types of HTTP requests. Let's add a new route that responds to GET requests for /about.

@app.route('/about')
def about():
    return "This is the about page."

This route will respond to GET requests to the /about URL with the string "This is the about page." You can test this by navigating to http://127.0.0.1:5000/about in your browser.

Handling POST Requests

To handle POST requests, you can use the request object provided by Flask. Here’s an example of how to handle a POST request to the /login endpoint:

from flask import Flask, request
 
app = Flask(__name__)
 
@app.route('/login', methods=['POST'])
def login():
    username = request.form['username']
    password = request.form['password']
    return f"Welcome, {username}!"
 
if __name__ == '__main__':
    app.run(debug=True)

In this example, the /login endpoint will accept POST requests with username and password fields in the request body. When you send a POST request to /login with these fields, the server will return a welcome message with the username.

Deploying the Flask Application

Once you have your Flask application running locally, you might want to deploy it to a public server. There are several ways to do this, but one of the most common is to use a WSGI server like Gunicorn and a web server like Nginx.

Using Gunicorn

Gunicorn is a Python WSGI HTTP server for UNIX. It can be installed using pip:

pip install gunicorn

To run your Flask application with Gunicorn, use the following command:

gunicorn app:app

This will start the Gunicorn server and your Flask application will be available on http://127.0.0.1:8000/.

Using Nginx

To serve your Flask application publicly, you can use Nginx as a reverse proxy. First, install Nginx:

sudo apt-get install nginx

Create a new configuration file for your Flask application in /etc/nginx/sites-available/yourapp:

server {
    listen 80;
    server_name yourdomain.com;
 
    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Enable the configuration by creating a symbolic link to the sites-enabled directory:

sudo ln -s /etc/nginx/sites-available/yourapp /etc/nginx/sites-enabled

Test your Nginx configuration:

sudo nginx -t

If there are no errors, restart Nginx:

sudo systemctl restart nginx

Now your Flask application should be accessible via your domain name.

Conclusion

In this tutorial, we covered setting up a basic Flask application, customizing the home page, adding routes and handling different HTTP methods, and deploying the application using Gunicorn and Nginx. Flask is a powerful yet simple framework for building web applications in Python, and this tutorial should give you a solid foundation to start building your own web applications.

Share this post
Robin te Hofstee

Written by Robin te Hofstee

Technology enthusiast with a deep love for programming. Sharing practical guides on React, Next.js, Linux and self-hosting.

Next.js App Router Deep Dive

2

A practical deep dive into the Next.js App Router: layouts, dynamic routes, Server and Client Components, data fetching, caching, Server Actions, route handlers, and the pitfalls to avoid.

Linux File Permissions Explained

2

A comprehensive guide to Linux file permissions — what they are, how the rwx model works, how to read and change permissions with chmod, chown and umask, plus special permissions like setuid, setgid and sticky bits.

Nmap: The Complete Linux Network Scanner Tutorial

3

A comprehensive Nmap tutorial for Linux, covering installation, target specification, host discovery, port scanning techniques, service and OS detection, the Nmap Scripting Engine, timing and performance, output formats, and practical examples from the official reference guide.