- Запуск простого HTTP сервера из Python
- How to Use Python SimpleHTTPServer
- Run the Web Server from the terminal
- Run the Web Server using Python script
- testHTML.html
- Example-1: Run the webserver in the specific port number
- Output
- Example-2: Run the webserver with the port number defined by command-line
- Output
- Example-3: Run the webserver with the HTML file
- Output
- Conclusion
- About the author
- Fahmida Yesmin
- An Intro to the Python HTTP Server
- Creating Python HTTP Server from the Command Line Terminal
- Accessing the Python HTTP Server Locally
- Access Python HTTP Server Over the Network
- Creating a Python HTTP Server via Script
- Customizing the Python HTTP Server with an index.html File
- Summary
- Next Steps
Запуск простого HTTP сервера из Python
В python есть встроенный модуль для быстрого запуска простого HTTP сервера. Для запуска достаточно выполнить одну команду.
№ python -m SimpleHTTPServer
По умолчанию это запустит HTTP сервер на порту 8000. Данный HTTP сервер опубликует содержимого текущего каталога.
Чаще всего я использую этот способ, чтобы быстро опубликовать файлы из произвольного каталога хоста Linux по HTTP, и скачать файлы на другое устройство. Например, мне нужно скачать определенный лог файл из каталога /var/log.
Для этого нужно перейти в указанный каталог:
И запустить HTTP сервер python:
$ python3 -m http.server 8080
Если этот порт закрыт файерволом, нужно предварительно временно открыть его:
$ sudo firewall-cmd —add-port=8080/tcp
Теперь на другом устройства откройте браузер, перейдите по адресу http://192.168.79.128:8080 и скачайте нужные файлы.
HTTP сервер пишет в консоль лог всех обращений к файлам (HTTP GET).
Затем вернитесь в консоль Linux и завершите процесс веб сервера Python, нажав Ctrl+C .
Этот трюк можно использовать в том числе для передачи файлов из WSL в Windows.
How to Use Python SimpleHTTPServer
The main task of the webserver is to handle the HTTP requests from the client. It waits for the HTTP requests coming from the particular IP address and port number, handles the request, and sends the client’s response back. Python uses the SimpleHTTPServer module to create a web server instantly and easily serve the content of the file from the server. It can be used for file sharing also. For this, you have to enable this module with the location of the shareable files. This module comes with the Python interpreter. You don’t need to install it. Since this module is merged with the http.server module in python3, so you have to run http.server to run the webserver in python3. How web server can be used to handle HTTP request and share files, have been shown in this tutorial.
Run the Web Server from the terminal
Run the following command to run the webserver from the terminal. If no port number is defined in the command, the webserver will start at 8000 port by default.
The following output will appear if the webserver is started properly. CTRL+C is pressed to stop the server.
Run the following command to start the webserver at 8080 port.
The following output will appear if the webserver is started at the 8080 port.
Run the Web Server using Python script
Run the following commands to create a folder named web and go to the folder. All the script files and HTML files of this tutorial will be created inside this folder.
Create an HTML file named testHTML.html inside the web folder with the following script. This file will be served from the webserver later.
testHTML.html
Example-1: Run the webserver in the specific port number
Create a python file with the following script to run the webserver at 8008 port. http.server module has been imported to run the webserver, and the SocketServer module has been imported to handle the HTTP request coming from the 8080 port. An object named Handler has been created to handle the HTTP requests. forever() function is called to run the webserver. No termination condition has been added to the script. So, the script will generate an error when the user tries to stop the server.
# Import server module
import http. server
# Import SocketServer module
import socketserver
# Set the port number
port = 8080
# Create object for handling HTTP requests
Handler = http. server . SimpleHTTPRequestHandler
# Run the server forever to handle the HTTP requests
with socketserver. TCPServer ( ( «» , port ) , Handler ) as httpd:
print ( «Web Server is running at http://localhost:%s» %port )
httpd. serve_forever ( )
Output
The following output will be appeared after executing the above script.
The list of the files and folder of the script location will be shown if the following URL is executed from the browser.
If the user presses CTRL+C from the terminal or presses the stop button from the PyCharm editor, the following error message will be displayed. This problem has solved in the next example of this tutorial.
Example-2: Run the webserver with the port number defined by command-line
Create a python file with the following script to run a web server at the particular port if the command-line argument gives the port number; otherwise, 5000 will be used as the default port. sys module has been imported in the script to read the command-line argument values. try-except block has been added in the script to handle the error when the user tries to stop the server. If the KeyboardInterrupt exception appears after running the server, then the close() function will be called to stop the webserver.
# Import server module
import http. server
# Import SocketServer module
import socketserver
# Import sys module
import sys
# Set the port number
if sys . argv [ 1 : ] :
port = int ( sys . argv [ 1 ] )
# Set the IP address
server_address = ( ‘127.0.0.1’ , port )
# Create object for handling HTTP requests
Handler = http. server . SimpleHTTPRequestHandler
# Run the web server forever to handle the HTTP requests
with socketserver. TCPServer ( ( «» , port ) , Handler ) as httpd:
print ( «Web Server is running at http://localhost:%s» %port )
httpd. serve_forever ( )
# Stopped the server
except KeyboardInterrupt :
httpd. server_close ( )
print ( «The server is stopped.» )
Output
The following output will be appeared after executing the above script without command-line argument value.
The following output will appear if the run the HTML file that is created in the previous step from the webserver.
Open the configuration dialog box from the Run menu of the PyCharm editor to set the command-line argument value. Parameters field is used to set the command-line argument, and 3000 is set here as the argument value.
The following output will appear if you run the script again after setting the argument value.
Example-3: Run the webserver with the HTML file
Create a python file with the following script to run the webserver by defining the HTML file for the base URL. The hostname and the port number have defined at the beginning of the script. PythonServer class has defined in the script to display the HTML file in the browser when the web server starts running.
# Import the server module
import http. server
# Set the hostname
HOST = «localhost»
# Set the port number
PORT = 4000
# Define class to display the index page of the web server
class PythonServer ( http. server . SimpleHTTPRequestHandler ) :
def do_GET ( self ) :
if self . path == ‘/’ :
self . path = ‘testHTML.html’
return http. server . SimpleHTTPRequestHandler . do_GET ( self )
# Declare object of the class
webServer = http. server . HTTPServer ( ( HOST , PORT ) , PythonServer )
# Print the URL of the webserver
print ( «Server started http://%s:%s» % ( HOST , PORT ) )
# Run the web server
webServer. serve_forever ( )
# Stop the web server
webServer. server_close ( )
print ( «The server is stopped.» )
Output
The following output will appear executing the above script.
The following page will appear in the browser if the browser’s base URL of the webserver executes.
Conclusion
The different ways of implementing web servers by using http. server module has shown in this tutorial to help python users to create a simple web server in Python.
About the author
Fahmida Yesmin
I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.
An Intro to the Python HTTP Server
Python’s standard library includes a simple web server that supports web client-server communication. Although the http.server module has limited security and should not be use in a production environment, it is useful for developmental purposes and local file sharing.
In this article, we’ll discuss how the Python http server module can be used from the terminal, and then we’ll cover how to use it within a Python script.
Creating Python HTTP Server from the Command Line Terminal
To launch a Python HTTP server from the command-line, first open the terminal and navigate to the directory that will be hosted to the server. In our example, we’ll navigate to a folder we’ve created that contains hello-world.txt and lorem-ipsum.txt :
From this directory, we can run the command python -m http.server to start a local HTTP server. By default, this will create a server at port 8000. We can also specify a port by running the command python -m http.server PORT_NUMBER .
Accessing the Python HTTP Server Locally
Now that we’ve launched the server, we can access it on our local device. To access the server, open a browsing window and enter http://localhost:PORT_NUMBER into the URL field. If a port number is not specified in the previous step, the server will be found at http://localhost:8000 .
The browser window will then show a list of files in the local directory:
From here, users can open or download any of the hosted files.
Access Python HTTP Server Over the Network
Once the server is launched, users can also access the page from other devices that are connected to the same LAN or WLAN network. To access this server, we first need to get the IP address of the host device.
To do this, we can navigate to the terminal and enter either ipconfig on a Windows device, or ifconfig on a Linux, Unix, or macOS device. Once we’ve obtained the IP address of the host machine, we can then access the server on any device on the same network by simply opening a browser window and entering, http://IP_ADDRESS:8000/ . As on the host device, this page will display the list of files in the directory.
Creating a Python HTTP Server via Script
In addition to launching a server from the terminal, Python’s http.server module can be used to start a server using the following script:
import SimpleHTTPServer import SocketServer PORT = 8000 Handler = SimpleHTTPServer.SimpleHTTPRequestHandler httpd = SocketServer.TCPServer(("", PORT), Handler) httpd.serve_forever()
By default, this will start a server in the working directory, but a directory location can also be specified. As with the previous example, this server can be accessed on the host device by typing http://localhost:8000/ into the browser window or on other network devices by entering http://IP_ADDRESS:8000/ into a browser window.
Customizing the Python HTTP Server with an index.html File
The http.server module is not limited to just hosting a list of files. We can also use this module to host a website based on a custom index.html file. With this approach, the URL will show the contents of the index.html file instead of the list of files in the host directory.
We’ll create a simple index.html file in the work directory that simply displays ‘Hello World’:
Hello World!
This is a simple paragraph.
Then, we can run the following script to launch the server:
import http.server import socketserver PORT = 8000 class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler): def do_GET(self): self.path = 'index.html' return http.server.SimpleHTTPRequestHandler.do_GET(self) Handler = MyHttpRequestHandler with socketserver.TCPServer(("", PORT), Handler) as httpd: print("Http Server Serving at port", PORT) httpd.serve_forever()
Now, when we navigate to http://localhost:8000/ , we see the custom HTML from our index.html file instead of the list of files in our working directory:
Summary
Python’s HTTP server makes it easy for developers to get started with web client-server communication either from the terminal or from a script. Although http.server isn’t secure for use in a production environment, it provides an easy way for developers to view a local web design or to share files across a private network. For people new to web development, http.server is a user-friendly way to experiment with website designs.
Next Steps
If you’re interested in learning more about the basics of coding, programming, and software development, check out our Coding Essentials Guidebook for Developers, where we cover the essential languages, concepts, and tools that you’ll need to become a professional developer.
Thanks and happy coding! We hope you enjoyed this article. If you have any questions or comments, feel free to reach out to jacob@initialcommit.io.