Skip to main content
Taught by Tech Leads

Master pipelines, cloud & AI to become an operational Data Engineer.

DataScientist.fr
Image de Start an HTTP server in one line of code in Python - Practical tutorial
Python
Web Development

Start an HTTP server in one line of code in Python - Practical tutorial

Photo de Romain DE LA SOUCHÈRE

Tech Lead, CTO AXI Technologies

Published on 2 janvier 2025 · 11 min of reading

In a world where technology is constantly evolving, mastering the basic tools for managing web servers becomes essential. Whether you are a novice developer or a seasoned professional, understanding how to start an HTTP server directly from the command line can open up new perspectives for you. This article guides you through the essential steps to serve static and dynamic content, while ensuring the security of your connections through the use of HTTPS and self-signed certificates. Dive into this fascinating universe where simplicity meets power.

How to start http.server from the command line

To start an HTTP server using Python, the standard library offers a very handy module: http.server. This module allows you to launch a minimalist web server with a single command line, which is ideal for quick tests or temporarily sharing files on a local network. Here’s how to proceed:

Verifying Python installation

Before getting started, ensure that Python is installed on your machine. You can check this by opening your terminal and executing the following command:
textile
If Python is installed, this command will display the Python version. If not, you need to install Python from the official site python.org.

Launching the HTTP server

Once you have confirmed that Python is installed, navigate in the terminal to the location of the directory you want to share on the network. Use the cd command to change directories, as follows:
textile
Once in the correct directory, execute the following command to start the HTTP server:
textile
This command launches an HTTP server on the default port 8000. You will then see a message indicating that the server is running:
python

Accessing the server

To access the server from a web browser, open your preferred browser and enter the following address in the address bar:
python
This URL allows you to access the files and subdirectories of the directory you chose to share.

Changing the port

If you wish to use a port other than 8000, you can specify the port directly in the command. For example, to use port 8080, type:
textile

Security and limitations

Note that http.server is designed for development or local network use. It is not secure for production use, as it does not handle secure connections (HTTPS) and does not provide protection against malicious attacks.
By following these instructions, you can quickly set up a simple HTTP server with Python for testing or file sharing.

Running a script remotely via the Common Gateway Interface (CGI)

Using the Common Gateway Interface (CGI) with Python's http.server module allows you to execute scripts remotely. This can be useful for testing scripts or simple applications. Here’s how to set up and run CGI scripts.

Enabling CGI mode

To enable CGI mode with http.server, you need to start the server using the --cgi option. Make sure you are in the directory where your CGI scripts are located, then execute the following command in your terminal:
textile
This command initializes the HTTP server with the capability to process CGI scripts. By default, CGI scripts must be placed in a subdirectory named cgi-bin in the current directory.

Example of a CGI script

A typical CGI script in Python starts with a shebang line to indicate which Python interpreter to use. Here’s a simple example of a CGI script:
python
Save this script with a .py extension in the cgi-bin directory.

Script permissions

Ensure that your script has the appropriate execution permissions. You can modify the permissions using the chmod command:
textile

Accessing and executing the script

To execute the script from your browser, type the following URL:
python
This triggers the execution of the script on the server, and the result will display in the browser.

Security considerations

Although executing CGI scripts is convenient for testing or demonstrations, it is important to note that this mechanism may present security vulnerabilities. Ensure that the server is accessible only by trusted users and that scripts are properly validated to prevent any injection of malicious code.
By using the CGI mode of http.server, you can easily test and run Python scripts remotely, with minimal configuration.

Serving static and dynamic content programmatically

Serving static or dynamic content with Python can be efficiently achieved by extending the http.server module. This allows you to create simple web applications without relying on heavy frameworks. Here’s how you can serve both types of content programmatically.

Serving static content

Static content, such as HTML, CSS, or JavaScript files, can be served directly using the SimpleHTTPRequestHandler class. Here’s how to set up a server to serve static files:
python
This script sets up an HTTP server that serves content from the current directory. Run it and access http://localhost:8000 to see your static files.

Serving dynamic content

To serve dynamic content, you can create a custom class that inherits from BaseHTTPRequestHandler and implements the do_GET or do_POST method, depending on your needs.
Here’s a simple example to serve dynamic content:
python
This server sends a simple dynamic HTML page in response to each GET request.
Serving static and dynamic content with Python is a simple and straightforward task thanks to the http.server module. This is particularly useful for small-scale projects or demonstrations. However, for more complex applications requiring advanced request handling, it is recommended to use specialized web frameworks like Flask or Django.

Encrypting the connection with https

To secure the exchanges between the server and clients, it is essential to encrypt the connection using HTTPS. Python allows you to set up a simple HTTPS server by leveraging the ssl library to wrap the HTTP server socket. Here’s how to proceed.

Generating an SSL certificate

Before getting started, you need to have an SSL certificate. For a development environment, you can generate a self-signed certificate using openssl. Execute the following command in your terminal:
textile
This creates two files: key.pem (private key) and cert.pem (certificate).

Configuring the HTTPS server

With the generated certificate files, you can now configure the HTTP server to use HTTPS. Here’s an example configuration:
python
This script configures an HTTPS server using the previously generated certificate and private key. The server listens for secure connections on port 4443.

Accessing the secure server

To access the secure server, open your browser and enter the following URL:
python
Note that browsers may display a warning regarding the self-signed certificate. This is normal for certificates that are not issued by a recognized certification authority.

Final considerations

Using HTTPS greatly enhances security by encrypting the exchanged data. However, for production deployment, it is crucial to use a certificate issued by a recognized certification authority to avoid security warnings in users' browsers.

Generating a self-signed certificate with python

Generating a self-signed certificate is an essential step for testing HTTPS in development. While OpenSSL is often used for this task, it is also possible to do it directly in Python using the cryptography library. Here’s how to create a self-signed certificate without leaving the Python environment.

Installing the cryptography library

Before getting started, ensure that the cryptography library is installed. You can add it to your Python environment with the following command:
textile

Generating the certificate

With cryptography, you can create a self-signed certificate using the following script:
python
This script generates an RSA key and a self-signed certificate, then saves them in key.pem and cert.pem files. These files can then be used to configure an HTTPS server, as described earlier. This method provides a convenient way to manage certificates directly in your Python code, thereby simplifying the development process.

Considering security and performance limitations

When using Python's http.server module to serve content, it is crucial to understand its limitations in terms of security and performance. While it is useful for development and testing, it has weaknesses for production use.

Security limitations

Python’s simple HTTP server is not designed to handle secure connections by default. While it is possible to configure it to use HTTPS with an SSL certificate, as we have seen, this configuration does not replace the security measures provided by full web servers like Apache or Nginx. Here are some points to consider:
  • Lack of advanced protections: The server does not include features such as denial-of-service (DoS) attack prevention or protection against SQL injections.
  • Self-signed certificates: Using self-signed certificates can lead to security warnings in browsers, which may be acceptable for development but not for a production site.
  • Lack of logging: Logging capabilities are limited, making it difficult to monitor suspicious activities.

Performance limitations

The http.server module is designed to be simple and lightweight, meaning it cannot effectively handle a large number of concurrent requests. Here are some limitations to consider:
  • Limited concurrency: The server uses a single-threaded request processing model, which can become a bottleneck under heavy load.
  • No caching: It offers no caching functionality, which can affect performance if the same content is frequently requested.
  • Basic request handling: Request processing is basic and does not benefit from the optimizations present in more advanced web servers.

Recommendations

For production projects, it is recommended to switch to more robust solutions that offer improved performance and advanced security features. Servers like Nginx or Apache, or frameworks like Flask or Django, are better suited to handle the complex needs of a production web application. Additionally, using a reverse proxy to manage connections and SSL certificates can enhance security and improve the ability to handle heavy loads.

Conclusion

In conclusion, Python’s http.server module provides a quick and convenient solution for launching a simple HTTP server, ideal for testing or local development. It allows you to easily serve static or dynamic content, execute scripts remotely via CGI, and even secure connections with HTTPS using self-signed certificates. However, it is important to keep in mind the inherent limitations of this solution in terms of security and performance.

Use for development

For developers, http.server is a valuable tool that facilitates the rapid setup of a testing environment. It allows you to visualize code changes in real-time, test script integration, and share files locally without complex configuration. This ease of use is one of the main advantages of this module.

Considerations for production

Although http.server can be used for demonstrations or small-scale applications, it is not suitable for production deployment due to its weaknesses in security and performance. Developers should consider transitioning to more robust solutions, such as full web servers or frameworks that offer advanced request handling, caching capabilities, and enhanced protections against cyber attacks.

Future perspectives

For those looking to explore further, learning web frameworks like Flask or Django can open up new possibilities for developing secure and performant web applications. These tools offer built-in features for database management, advanced routing, and security, simplifying the development of complex projects.
In summary, http.server is an excellent starting point for understanding the basics of how a web server works and for performing simple tasks. However, to meet the demands of a production application, it is necessary to turn to more suitable solutions that ensure data security and user satisfaction.

Want to go further?

This topic is part of our Become a Data Analyst course. Browse the full programme, or get it by email.

Share with

Photo de Romain DE LA SOUCHÈRE

Romain DE LA SOUCHÈRE

Tech Lead, CTO AXI Technologies

Expert Data Engineering et Cloud, Romain affiche plus de 11 ans d'expérience, dont plusieurs années comme Lead Developer sur des solutions Smart Building haute performance. Il y a conçu et mis en production des moteurs de traitement capables d'absorber des centaines de milliers de données de capteurs par minute, ainsi que des bases clusterisées gérant plus de 10 millions de données dynamiques. Certifié Microsoft Azure DevOps Engineer Expert, il maîtrise aussi bien le développement back-end (Python, C#) que le DevOps (Docker, Kubernetes, Terraform) et les agents LLM. Formateur en Python, cloud, DevOps et IA générative appliquée, il forme avec une obsession : Amener chaque apprenant à concevoir et déployer des architectures réellement scalables en production.

» Learn More

Associated trainings

All our trainings
Image de la formation Become a Data Analyst
Become a Data Analyst
6 months
Intermediate
Guarantee
Image de la formation Become a Data Engineer
Become a Data Engineer
9 months
Advanced
Guarantee