- How to Create a Python Web Server
- What is a Web Server? [Definition]
- How Do You Create a Simple Python Web Server?
- Recommend Python Course
- Creating a Custom Web Server Using Python
- Conclusion
- Пишем простой сервер на Python
- Околопрактика
- Практика
- Заключение
- Create a Python Web Server
- Example
- Builtin webserver
- Web server
How to Create a Python Web Server
Python remains one of the best programming languages to learn in 2022 , with applications in back-end web development, machine learning, scientific modelling, system operations, and several enterprise-specific software. It is generally considered one of the more approachable programming languages, with dynamically typed, English-like syntax and many libraries.
That accessibility extends to creating a Python web server, which you can do in only a few lines of code. Like our other Python tutorials , you’ll find that some of the most fundamental operations are carried out in a matter of minutes.
We’ll show you how to create your own Python web server for local testing. The whole process takes only a few minutes and a few lines of code.
But first, let’s go over what a web server is.
What is a Web Server? [Definition]
In the infrastructure of the internet, the server is one part of the client-server model. When a client browser visits a web page, it makes an HTTP request to the server containing the files needed to operate a website. The server listens to the client’s request, processes it, and responds with the required files to present the web page. This content could be HTML (the text and media you see on a website) and JSON (applications).
You might have encountered a few server error codes in your time browsing the internet — “file not found” or 404 being a more popular one. In these cases, the server has trouble accessing certain files. With a 404 error, the particular file is missing.
There are more nuances to web servers, including classification into static and dynamic web servers. For example, static web servers only return files as they are, with no extra processing. Dynamic web servers introduce databases and application servers, which you can proceed to once you’ve got the hang of static servers.
Having said all that, we should get into how you create a web server. We’ll assume you’re running the latest version of Python. There are resources for you to learn how to run a python script , among other useful lessons.
How Do You Create a Simple Python Web Server?
Launching a Python web server is quick and straightforward, and it’ll only take a few minutes for you to get up and to run. All it takes is one line of code to get the simplest of local servers running on your computer.
By local testing, your system becomes the server to the client that is your browser, and the files are stored locally on your system. The module you’ll be using to create a web server is Python’s http server. There is one caveat to this: it can only be used as a static file server. You’ll need a Python web framework, like Django, to run dynamic web servers.
Let’s get to the code, which looks like this follows:
Type this into the terminal or command prompt, depending on your system, and you should see a “server started” message and a “server stopped” when you close the server.
And there you have it — your first Python webserver! Admittedly, it’s a simple one, doing nothing more than opening up a web server on your system’s default port of 8000. The port can also be changed by specifying the port number at the end of the line, like this:
A simple web server like the one you’ve just created is all well and good. It’s far more interesting and educational, however, to create a custom web server. After all, the best way to learn python is through a hands-on approach — code, debug, fix, rinse and repeat.
Recommend Python Course
Creating a Custom Web Server Using Python
A custom web server allows you to do more than a built-in web server. The code you’re about to see will teach you a lot about some important functions and processes. Don’t be put off by the length of the code — there are only a handful of key concepts at play here. You don’t have to manually type all of this out to test it yourself — but note the significance of those concepts.
from http.server import HTTPServer, BaseHTTPRequestHandler #Python’s built-in library
import time
hostName = "localhost"
serverPort = 8080 #You can choose any available port; by default, it is 8000
Class MyServer(BaseHTTPRequestHandler):
def do_GET(self): //the do_GET method is inherited from BaseHTTPRequestHandler
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes("", "utf-8"))
self.wfile.write(bytes("Request: %s
" % self.path, "utf-8"))
self.wfile.write(bytes("", "utf-8"))
self.wfile.write(bytes("This is an example web server.
", "utf-8"))
self.wfile.write(bytes("", "utf-8"))
if __name__ == "__main__":
webServer = HTTPServer((hostName, serverPort), MyServer)
print("Server started http://%s:%s" % (hostName, serverPort)) #Server starts
try:
webServer.serve_forever()
except KeyboardInterrupt:
pass
webServer.server_close() #Executes when you hit a keyboard interrupt, closing the server
print("Server stopped.")
Before we jump into the critical parts, let’s quickly go over a few things. If you’ve done your HTML homework, then you’ll see some familiar terms in the code. The class MyServer writes to the output stream (wfile) that’s sent as a response to the client using “self.wfile.write()”. What we’re doing here is writing an elementary HTML page on the fly.
We’ll address some of the more important executions going on here, namely:
- The module http.server
- The classes HTTPServer and BaseHTTPRequestHandler, derived from the library http.server
- The do_GET method
The HTTP server is a standard module in the Python library that has the classes used in client-server communication. Those two classes are HTTPServer and BaseHTTPRequestHandler. The latter accesses the server through the former. HTTPServer stores the server address as instance variables, while BaseHTTPRequestHandler calls methods to handle the requests.
To sum up, the code starts at the main function. Next, the class MyServer is called, and the BaseHTTPRequestHandler calls the do_GET() method to meet requests. When you interrupt the program, the server closes.
If you did this correctly, you should see messages like this:
Why would you want to use a custom web server? It lets you use more methods, like do_HEAD() and do_POST(), offering additional functionality. In any case, you can see that creating a custom web server is also fairly straightforward.
Conclusion
It doesn’t take much to get your web server going using Python. It’s the fundamental idea that you should absorb. Creating your server is a small but significant step forward on your path to creating full-stack applications.
Try the code yourself, and perhaps even search for Python projects incorporating server implementation. There are many projects available that make use of this concept, so it’s good to know how to implement it in a larger context.
If you’re looking for more such lessons, head over to our Python tutorials page, there’s a lot of information on everything from the best resources to lessons that focus on a specific concept.
And if you’re looking to build your own website, we found some great discounts on NameCheap for domain names and web hosting.
People are also reading:
Пишем простой сервер на Python
Ну, начнем как и везде с определений, берите тетрадь и ручку сейчас начнется нудятина. Чтобы мы cмогли написать свой сервер, нужно для начала понимать как он вообще работает, ловите определение:
Сервер – это программное обеспечение, которое ожидает запросов клиентов и обслуживает или обрабатывает их соответственно.
Если объяснять это своими словами, представьте фургон с хот-догами(сервер), проголодавшись, вы(клиент) подходите и говорите повару, что вы хотите заказать(запрос), после чего повар обрабатывает, что вы ему сказали и начинает готовить, в конечном итоге вы получаете свой хот-дог(результат) и сытый радуетесь жизни. Для наглядности посмотри схему.
Околопрактика
Для написания сервера мы будем использовать Python и модуль Socket.
Socket позволяет нам общаться с сервером с помощью сокетов. Весь код я постараюсь пояснять, дабы ты мой дорогой читатель все понял. В конце статьи будет готовый код.
Создайте два файла в одной директории:
Практика
Пишем код для серверной части, так что открывайте файл socket_server.py.
Начнем с импорта модуля и создания TCP-сокета:
Далее весь код будет с комментариями:
s.bind(('localhost', 3030)) # Привязываем серверный сокет к localhost и 3030 порту. s.listen(1) # Начинаем прослушивать входящие соединения conn, addr = s.accept() # Метод который принимает входящее соединение.
Добавим вечный цикл, который будет считывать данные с клиентской части, и отправлять их обратно.
while True: # Создаем вечный цикл. data = conn.recv(1024) # Получаем данные из сокета. if not data: break conn.sendall(data) # Отправляем данные в сокет. print(data.decode('utf-8')) # Выводим информацию на печать. conn.close()
Переходим к клиентской части, весь код теперь пишем в файле socket_client.py.
Начало у клиентской части такое-же как и у серверной.
import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Далее подключимся к нашему серверу и отправим сообщение «Hello. Habr!».
s.connect(('localhost', 3030)) # Подключаемся к нашему серверу. s.sendall('Hello, Habr!'.encode('utf-8')) # Отправляем фразу. data = s.recv(1024) #Получаем данные из сокета. s.close()
Заключение
Вот мы с вами и написали свой первый сервер, рад был стараться для вас, ниже будет готовый код.
socket_server.py:
import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('localhost', 3030)) # Привязываем серверный сокет к localhost и 3030 порту. s.listen(1) # Начинаем прослушивать входящие соединения. conn, addr = s.accept() # Метод который принимает входящее соединение. while True: data = conn.recv(1024) # Получаем данные из сокета. if not data: break conn.sendall(data) # Отправляем данные в сокет. print(data.decode('utf-8')) conn.close()
socket_client.py:
import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('localhost', 3030)) # Подключаемся к нашему серверу. s.sendall('Hello, Habr!'.encode('utf-8')) # Отправляем фразу. data = s.recv(1024) #Получаем данные из сокета. s.close()
Create a Python Web Server
A webserver in Python can be setup in two ways. Python supports a webserver out of the box. You can start a web server with a one liner.
But you can also create a custom web server which has unique functionality. In this article you’ll learn how to do that.
The web server in this example can be accessed on your local network only. This can either be localhost or another network host. You could serve it cross location with a vpn.
Example
Builtin webserver
That will open a webserver on port 8080. You can then open your browser at http://127.0.0.1:8080/
The webserver is also accessible over the network using your 192.168.-.- address.
This is a default server that you can use to download files from the machine.
Web server
Run the code below to start a custom web server. To create a custom web server, we need to use the HTTP protocol.
By design the http protocol has a “get” request which returns a file on the server. If the file is found it will return 200.
The server will start at port 8080 and accept default web browser requests.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Python 3 server example
from http.server import BaseHTTPRequestHandler, HTTPServer
import time
hostName = «localhost»
serverPort = 8080
class MyServer(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header(«Content-type», «text/html»)
self.end_headers()
self.wfile.write(bytes(««, «utf-8»))
self.wfile.write(bytes(«
Request: %s
« % self.path, «utf-8»))
self.wfile.write(bytes(««, «utf-8»))
self.wfile.write(bytes(«
This is an example web server.
«, «utf-8»))
self.wfile.write(bytes(««, «utf-8»))
if __name__ == «__main__»:
webServer = HTTPServer((hostName, serverPort), MyServer)
print(«Server started http://%s:%s» % (hostName, serverPort))
try:
webServer.serve_forever()
except KeyboardInterrupt:
pass
webServer.server_close()
print(«Server stopped.»)
If you open an url like http://127.0.0.1/example the method do_GET() is called. We send the webpage manually in this method.
The variable self.path returns the web browser url requested. In this case it would be /example
Python Decorators Introduction