# Python HTTP Server
Running this command serves the files of the current directory at port 9000 .
If no argument is provided as port number then server will run on default port 8000 .
The -m flag will search sys.path for the corresponding .py file to run as a module.
If you want to only serve on localhost you’ll need to write a custom Python program such as:
# Serving files
Assuming you have the following directory of files:

You can setup a web server to serve these files as follows:
The SocketServer module provides the classes and functionalities to setup a network server.
SocketServer ‘s TCPServer class sets up a server using the TCP protocol. The constructor accepts a tuple representing the address of the server (i.e. the IP address and port) and the class that handles the server requests.
The SimpleHTTPRequestHandler class of the SimpleHTTPServer module allows the files at the current directory to be served.
Save the script at the same directory and run it.
Run the HTTP Server :
python -m SimpleHTTPServer 8000
python -m http.server 8000
The ‘-m’ flag will search ‘sys.path’ for the corresponding ‘.py’ file to run as a module.
(opens new window) in the browser, it will give you the following:

# Programmatic API of SimpleHTTPServer
What happens when we execute python -m SimpleHTTPServer 9000 ?
To answer this question we should understand the construct of SimpleHTTPServer (https://hg.python.org/cpython/file/2.7/Lib/SimpleHTTPServer.py)
Firstly, Python invokes the SimpleHTTPServer module with 9000 as an argument. Now observing the SimpleHTTPServer code,
The test function is invoked following request handlers and ServerClass. Now BaseHTTPServer.test is invoked
Hence here the port number, which the user passed as argument is parsed and is bound to the host address. Further basic steps of socket programming with given port and protocol is carried out. Finally socket server is initiated.
This is a basic overview of inheritance from SocketServer class to other classes:
http.server — HTTP servers¶
This module defines classes for implementing HTTP servers.
http.server is not recommended for production. It only implements basic security checks .
Availability : not Emscripten, not WASI.
This module does not work or is not available on WebAssembly platforms wasm32-emscripten and wasm32-wasi . See WebAssembly platforms for more information.
One class, HTTPServer , is a socketserver.TCPServer subclass. It creates and listens at the HTTP socket, dispatching the requests to a handler. Code to create and run the server looks like this:
This class builds on the TCPServer class by storing the server address as instance variables named server_name and server_port . The server is accessible by the handler, typically through the handler’s server instance variable.
class http.server. ThreadingHTTPServer ( server_address , RequestHandlerClass ) ¶
This class is identical to HTTPServer but uses threads to handle requests by using the ThreadingMixIn . This is useful to handle web browsers pre-opening sockets, on which HTTPServer would wait indefinitely.
New in version 3.7.
The HTTPServer and ThreadingHTTPServer must be given a RequestHandlerClass on instantiation, of which this module provides three different variants:
class http.server. BaseHTTPRequestHandler ( request , client_address , server ) ¶
This class is used to handle the HTTP requests that arrive at the server. By itself, it cannot respond to any actual HTTP requests; it must be subclassed to handle each request method (e.g. GET or POST). BaseHTTPRequestHandler provides a number of class and instance variables, and methods for use by subclasses.
The handler will parse the request and the headers, then call a method specific to the request type. The method name is constructed from the request. For example, for the request method SPAM , the do_SPAM() method will be called with no arguments. All of the relevant information is stored in instance variables of the handler. Subclasses should not need to override or extend the __init__() method.
BaseHTTPRequestHandler has the following instance variables:
Contains a tuple of the form (host, port) referring to the client’s address.
Contains the server instance.
Boolean that should be set before handle_one_request() returns, indicating if another request may be expected, or if the connection should be shut down.
Contains the string representation of the HTTP request line. The terminating CRLF is stripped. This attribute should be set by handle_one_request() . If no valid request line was processed, it should be set to the empty string.
Contains the command (request type). For example, ‘GET’ .
Contains the request path. If query component of the URL is present, then path includes the query. Using the terminology of RFC 3986, path here includes hier-part and the query .
Contains the version string from the request. For example, ‘HTTP/1.0’ .
Holds an instance of the class specified by the MessageClass class variable. This instance parses and manages the headers in the HTTP request. The parse_headers() function from http.client is used to parse the headers and it requires that the HTTP request provide a valid RFC 2822 style header.
An io.BufferedIOBase input stream, ready to read from the start of the optional input data.
Contains the output stream for writing a response back to the client. Proper adherence to the HTTP protocol must be used when writing to this stream in order to achieve successful interoperation with HTTP clients.
Changed in version 3.6: This is an io.BufferedIOBase stream.
BaseHTTPRequestHandler has the following attributes:
Specifies the server software version. You may want to override this. The format is multiple whitespace-separated strings, where each string is of the form name[/version]. For example, ‘BaseHTTP/0.2’ .
Contains the Python system version, in a form usable by the version_string method and the server_version class variable. For example, ‘Python/1.4’ .
Specifies a format string that should be used by send_error() method for building an error response to the client. The string is filled by default with variables from responses based on the status code that passed to send_error() .
Specifies the Content-Type HTTP header of error responses sent to the client. The default value is ‘text/html’ .
Specifies the HTTP version to which the server is conformant. It is sent in responses to let the client know the server’s communication capabilities for future requests. If set to ‘HTTP/1.1’ , the server will permit HTTP persistent connections; however, your server must then include an accurate Content-Length header (using send_header() ) in all of its responses to clients. For backwards compatibility, the setting defaults to ‘HTTP/1.0’ .
Specifies an email.message.Message -like class to parse HTTP headers. Typically, this is not overridden, and it defaults to http.client.HTTPMessage .
This attribute contains a mapping of error code integers to two-element tuples containing a short and long message. For example,
A BaseHTTPRequestHandler instance has the following methods:
Calls handle_one_request() once (or, if persistent connections are enabled, multiple times) to handle incoming HTTP requests. You should never need to override it; instead, implement appropriate do_*() methods.
This method will parse and dispatch the request to the appropriate do_*() method. You should never need to override it.
When an HTTP/1.1 conformant server receives an Expect: 100-continue request header it responds back with a 100 Continue followed by 200 OK headers. This method can be overridden to raise an error if the server does not want the client to continue. For e.g. server can choose to send 417 Expectation Failed as a response header and return False .
New in version 3.2.
Sends and logs a complete error reply to the client. The numeric code specifies the HTTP error code, with message as an optional, short, human readable description of the error. The explain argument can be used to provide more detailed information about the error; it will be formatted using the error_message_format attribute and emitted, after a complete set of headers, as the response body. The responses attribute holds the default values for message and explain that will be used if no value is provided; for unknown codes the default value for both is the string . . The body will be empty if the method is HEAD or the response code is one of the following: 1xx , 204 No Content , 205 Reset Content , 304 Not Modified .
Changed in version 3.4: The error response includes a Content-Length header. Added the explain argument.
Adds a response header to the headers buffer and logs the accepted request. The HTTP response line is written to the internal buffer, followed by Server and Date headers. The values for these two headers are picked up from the version_string() and date_time_string() methods, respectively. If the server does not intend to send any other headers using the send_header() method, then send_response() should be followed by an end_headers() call.
Changed in version 3.3: Headers are stored to an internal buffer and end_headers() needs to be called explicitly.
Adds the HTTP header to an internal buffer which will be written to the output stream when either end_headers() or flush_headers() is invoked. keyword should specify the header keyword, with value specifying its value. Note that, after the send_header calls are done, end_headers() MUST BE called in order to complete the operation.
Changed in version 3.2: Headers are stored in an internal buffer.
Sends the response header only, used for the purposes when 100 Continue response is sent by the server to the client. The headers not buffered and sent directly the output stream.If the message is not specified, the HTTP message corresponding the response code is sent.
New in version 3.2.
Adds a blank line (indicating the end of the HTTP headers in the response) to the headers buffer and calls flush_headers() .
Changed in version 3.2: The buffered headers are written to the output stream.
Finally send the headers to the output stream and flush the internal headers buffer.
New in version 3.3.
Logs an accepted (successful) request. code should specify the numeric HTTP code associated with the response. If a size of the response is available, then it should be passed as the size parameter.
Logs an error when a request cannot be fulfilled. By default, it passes the message to log_message() , so it takes the same arguments (format and additional values).
Logs an arbitrary message to sys.stderr . This is typically overridden to create custom error logging mechanisms. The format argument is a standard printf-style format string, where the additional arguments to log_message() are applied as inputs to the formatting. The client ip address and current date and time are prefixed to every message logged.
Returns the server software’s version string. This is a combination of the server_version and sys_version attributes.
date_time_string ( timestamp = None ) ¶
Returns the date and time given by timestamp (which must be None or in the format returned by time.time() ), formatted for a message header. If timestamp is omitted, it uses the current date and time.
The result looks like ‘Sun, 06 Nov 1994 08:49:37 GMT’ .
Returns the current date and time, formatted for logging.
Returns the client address.
Changed in version 3.3: Previously, a name lookup was performed. To avoid name resolution delays, it now always returns the IP address.
This class serves files from the directory directory and below, or the current directory if directory is not provided, directly mapping the directory structure to HTTP requests.
New in version 3.7: The directory parameter.
Changed in version 3.9: The directory parameter accepts a path-like object .
A lot of the work, such as parsing the request, is done by the base class BaseHTTPRequestHandler . This class implements the do_GET() and do_HEAD() functions.
The following are defined as class-level attributes of SimpleHTTPRequestHandler :
This will be "SimpleHTTP/" + __version__ , where __version__ is defined at the module level.
A dictionary mapping suffixes into MIME types, contains custom overrides for the default system mappings. The mapping is used case-insensitively, and so should contain only lower-cased keys.
Changed in version 3.9: This dictionary is no longer filled with the default system mappings, but only contains overrides.
The SimpleHTTPRequestHandler class defines the following methods:
This method serves the ‘HEAD’ request type: it sends the headers it would send for the equivalent GET request. See the do_GET() method for a more complete explanation of the possible headers.
The request is mapped to a local file by interpreting the request as a path relative to the current working directory.
If the request was mapped to a directory, the directory is checked for a file named index.html or index.htm (in that order). If found, the file’s contents are returned; otherwise a directory listing is generated by calling the list_directory() method. This method uses os.listdir() to scan the directory, and returns a 404 error response if the listdir() fails.
If the request was mapped to a file, it is opened. Any OSError exception in opening the requested file is mapped to a 404 , ‘File not found’ error. If there was a ‘If-Modified-Since’ header in the request, and the file was not modified after this time, a 304 , ‘Not Modified’ response is sent. Otherwise, the content type is guessed by calling the guess_type() method, which in turn uses the extensions_map variable, and the file contents are returned.
A ‘Content-type:’ header with the guessed content type is output, followed by a ‘Content-Length:’ header with the file’s size and a ‘Last-Modified:’ header with the file’s modification time.
Then follows a blank line signifying the end of the headers, and then the contents of the file are output. If the file’s MIME type starts with text/ the file is opened in text mode; otherwise binary mode is used.
For example usage, see the implementation of the test function in Lib/http/server.py.
Changed in version 3.7: Support of the ‘If-Modified-Since’ header.
The SimpleHTTPRequestHandler class can be used in the following manner in order to create a very basic webserver serving files relative to the current directory:
http.server can also be invoked directly using the -m switch of the interpreter. Similar to the previous example, this serves files relative to the current directory:
The server listens to port 8000 by default. The default can be overridden by passing the desired port number as an argument:
By default, the server binds itself to all interfaces. The option -b/—bind specifies a specific address to which it should bind. Both IPv4 and IPv6 addresses are supported. For example, the following command causes the server to bind to localhost only:
New in version 3.4: —bind argument was introduced.
New in version 3.8: —bind argument enhanced to support IPv6
By default, the server uses the current directory. The option -d/—directory specifies a directory to which it should serve the files. For example, the following command uses a specific directory:
New in version 3.7: —directory argument was introduced.
By default, the server is conformant to HTTP/1.0. The option -p/—protocol specifies the HTTP version to which the server is conformant. For example, the following command runs an HTTP/1.1 conformant server:
New in version 3.11: —protocol argument was introduced.
This class is used to serve either files or output of CGI scripts from the current directory and below. Note that mapping HTTP hierarchic structure to local directory structure is exactly as in SimpleHTTPRequestHandler .
CGI scripts run by the CGIHTTPRequestHandler class cannot execute redirects (HTTP code 302), because code 200 (script output follows) is sent prior to execution of the CGI script. This pre-empts the status code.
The class will however, run the CGI script, instead of serving it as a file, if it guesses it to be a CGI script. Only directory-based CGI are used — the other common server configuration is to treat special extensions as denoting CGI scripts.
The do_GET() and do_HEAD() functions are modified to run CGI scripts and serve the output, instead of serving files, if the request leads to somewhere below the cgi_directories path.
The CGIHTTPRequestHandler defines the following data member:
This defaults to [‘/cgi-bin’, ‘/htbin’] and describes directories to treat as containing CGI scripts.
The CGIHTTPRequestHandler defines the following method:
This method serves the ‘POST’ request type, only allowed for CGI scripts. Error 501, “Can only POST to CGI scripts”, is output when trying to POST to a non-CGI url.
Note that CGI scripts will be run with UID of user nobody, for security reasons. Problems with the CGI script will be translated to error 403.
CGIHTTPRequestHandler can be enabled in the command line by passing the —cgi option:
Security Considerations¶
SimpleHTTPRequestHandler will follow symbolic links when handling requests, this makes it possible for files outside of the specified directory to be served.
Build Web Server From Scratch With Python.
![]()
If you are reading an article with this kind of title so maybe your are involved in the world of Web Development and have at least an idea of how web works, if not you can get an overview of it in this article .
The first thing that might come to your head is “Why to create a Web Server from scratch? What inventing the wheel again for?”
A famous thinker used to say: I hear and I forget; I see and I remember; I do and I understand.
I believe to become a better developer you must get a better understanding of the underlying software systems you use on a daily basis and that includes programming languages, compilers and interpreters, databases and operating systems, web servers and web frameworks. And, to get a better and deeper understanding of those systems you must re-build them from scratch, brick by brick, wall by wall.
I hope at this point you’re convinced that it’s a good idea to start re-building different software systems to learn how they work.
But, What is a Web Server then?
It is basically a networking server that sits on a physical server (yeah, a server on a server lol) and waits for a client to send a request. When it receives a request, it generates a response and sends it back to the client. The communication between a client and a server happens using HTTP protocol. A client can be your browser or any other software that speaks HTTP.
Before the client can send a HTTP request though, it first needs to establish a TCP connection with the Web server. Then it sends an HTTP request over the TCP connection to the server and waits for the server to send an HTTP response back.
To establish the TCP connection we will so-called sockets:
Here we made a socket instance and passed it two parameters. The first parameter is AF_INET and the second one is SOCK_STREAM. AF_INET refers to the address family ipv4. The SOCK_STREAM means connection oriented TCP protocol.
Then we set the socket option to SOL_SOCKET to manipulate options at the sockets API level. With this done now we can bind the host and port before start to listen from them.
The socket must be bound to an address and listening for connections. For that we use the socket.accept() property, The return value is a pair (conn, address) where conn is a new socket object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of the connection.
To receive the data from the socket we use the socket.recv() method, The return value is a bytes object representing the data received. The maximum amount of data to be received at once is specified by its argument. Decode to utf-8 can help us to avoid problems with the data received.
Then we set the response and send it using the sendall method and close the connection.
Now let’s try it…
The entire code would be:
If you execute this program and check in your browser you should get something like this:
You can also simulate a web browser running the Web server fire up a telnet session on the command line specifying a host to connect to localhost and the port to connect to 8888 and then press Enter:
At this point you’ve established a TCP connection with the server running on your local host and ready to send and receive HTTP messages. In the picture below you can see a standard procedure a server has to go through to be able to accept new TCP connections.
Conclusion
And that’s the basic model of how a Web server works. To sum it up: The Web server creates a listening socket and starts accepting new connections in a loop. The client initiates a TCP connection and, after successfully establishing it, the client sends an HTTP request to the server and the server responds with an HTTP response that gets displayed to the user. To establish a TCP connection both clients and servers use sockets.
Пишем свой веб-сервер на Python: протокол HTTP
Подпишись на обновления блогa, чтобы не пропустить следующий пост!
Оглавление
Введение
На данный момент мы умеем отправлять и принимать данные по сети и организовывать обработку запросов на сервере. Настало время перейти на более высокий уровень — реализовать свой HTTP сервер.
Для начала определимся, что же такое HTTP. Hypertext Transfer Protocol (HTTP) — это протокол прикладного уровня, предназначенный для передачи гипертекстовых данных в распределенных информационных системах. Ух, сложнааа. А на самом деле нет. Давайте разбираться!
Протокол — это не более, чем соглашение между двумя или более участниками некоторого взаимодействия. Когда речь идет о сетевом взаимодействии, протоколы принято условно разделять на уровни. В самом низу находятся протоколы физического уровня, определяющие как данные передаются в физических средах, т.е. по проводам, оптоволокну, и т.п. Знакомые нам из первой части протоколы IP и TCP — это протоколы сетевого и транспортного уровня, соответственно. Они определяют более высокоуровневые детали взаимодействия, в частности, IP отвечает за адресацию компьютеров/узлов в сети, а TCP — за надежную передачу данных произвольной (т.е. в общем случае превышающей размер одного IP-пакета) длины между узлами. HTTP же располагается на самом высоком уровне — прикладном. От нижележащих протоколов HTTP ожидает гарантий надежности доставки данных, а сам концентрируется на определении понятий запросов и ответов (сообщений) и их семантике. Фактически, HTTP является основным протоколом передачи данных в вебе, а сами данные являются гипертекстом, зачастую представленным в формате HTML-страниц.

До версии HTTP/2, появившейся в 2015 году, HTTP был простым текстовым протоколом. Во второй версии протокол претерпел значительные доработки, стал эффективнее и приобрел новые возможности, но в то же время реализация клиентов и серверов усложнилась. На декабрь 2021 только 46.8% сайтов Интернет используют HTTP/2, но наблюдается устойчивый восходящий тренд.
В этой статье мы рассмотрим, как можно реализовать простейший HTTP-сервер на Python. Ради простоты, мы будем работать с версией протокола HTTP/1.1, а код сервера будет скорее служить образовательным целям, нежели являться полнофункциональным веб-сервером.
Задача HTTP-сервера
HTTP-сервер — это (в большинстве случаев) развитие идеи уже хорошо нам известного TCP-сервера. Задача HTTP-сервера — принимать входящие HTTP-запросы от клиентов, обрабатывать их и отправлять HTTP-ответы.
Простейший HTTP-запрос выглядит следующим образом:
То, что мы видим выше — это так называемое сообщение HTTP message. Опуская вопрос кодировки данных, сообщение HTTP/1.1 — это обычный текст, который состоит из строк, разделенных символами CRLF, т.е. \r\n . Первая строка запроса называется request line. Она определяет метод method, цель target и версию протокола. Далее идут заголовки запроса. В ранних версиях протокола секция заголовков могла отсутствовать полностью, но в HTTP/1.1 заголовок Host является обязательным.
Назначение вышеописанных элементов мы рассмотрим чуть позже, а сейчас перейдем к примеру HTTP-ответа:
HTTP-ответы также представлены сообщениями. Первая строка ответа называется status line. Она состоит из версии, трехзначного кода статуса status-code и опционального текста причины.
Как и в случае с TCP-сервером, для того, чтобы начать обрабатывать HTTP-запросы, наш сервер должен создать слушающий (listening) сокет. На каждое входящее соединение, сервер должен прочитывать текст HTTP-запроса, вызывать соответствующий обработчик, и, получив от него ответ, отсылать данные клиенту. TCP-соединение может быть как завершено непосредственно после отправки ответа, так и сохранено для повторного использования клиентом.
Структура HTTP-сервера
Реализация полнофункционального HTTP/1.1-сервера требует учета всех требований протокола, определенных группой RFC (RFC7230 "Message Syntax and Routing", RFC7231 "Semantics and Content", RFC7232 "Conditional Requests", RFC7233 "Range Requests", RFC7234 "Caching", RFC7235 "Authentication"). Мы же скорее хотим сфокусироваться на самом подходе к реализации. Исходный код в этой статье не готов для боевого использования, и не гарантируется, что его логика строго следует спецификации протокола.
В качестве основы будущего HTTP-сервера мы будем использовать следующий класс:
Код сервера максимально упрощен, чтобы иметь возможность сфокусироваться именно на работе с протоколом HTTP. Обработка запросов происходит синхронно, т.е. возможно обслуживать не более одного клиента в один момент времени. Сервер в бесконечном цикле осуществляет прием входящих соединений, выполняя serv_sock.accept() . Каждое соединение conn является клиентским сокетом. Прием очередного соединения инициирует обработку HTTP-запроса serve_client(conn) . Обработка же заключается в чтении и разборе aka синтаксическом анализе HTTP-запроса parse_request(conn) , непосредственно обработке handle_request(req) и отправке ответа send_response(conn, resp) . В случае же ошибки на любом из этапов, обработка заканчивается отправкой сообщения об ошибке send_error(conn, err) .
Запустить сервер можно, сохранив код в файле server.py и выполнив команду:
Для отправки тестовых HTTP-запросов удобно пользоваться консольной утилитой netcat:
Пару слов о кодировке
В соответствии со спецификацией, одно сообщение HTTP может одновременно содержать данные, представленные в различных кодировках. В то же время, служебные данные, такие как request line, status line и заголовки должны быть преставлены некоторым надмножеством однобайтовой ASCII кодировки, определенном в стандарте ISO/IEC 8859-1. Почему существует такое требование становится очевидно при попытке реализации собственного HTTP-сервера. Как мы уже видели выше, HTTP-запрос — это обычный текст, а текст в компьютерном мире — это последовательность байт плюс дополнительное знание, в какой кодировке эти байты должны быть интерпретированы. Без знания кодировки в общем случае невозможно (и зачастую небезопасно) каким-либо образом интерпретировать текстовые данные, представленные последовательностью байт. Так как никакой предварительной фазы обмена информацией о кодировке в протоколе не предусмотрено, логичным решением является заранее договориться, что все данные по умолчанию передаются в одной и той же кодировке, и такой кодировкой была выбрана ASCII. В таком случае, у сервера всегда существует возможность произвести разбор запроса на составляющие, т.е. отделить request line от блока заголовков, а заголовки друг от друга.
Ограничение ASCII к счастью не распространяется на тело запроса. Имея возможность прочитать заголовки, из них возможно получить информацию о наличии, размере и кодировке тела запроса. Далее сервер должен прочитать заданное количество "сырых" байт из сокета и лишь потом декодировать их в строку с использованием договоренной кодировки (или кодировки по умолчанию).
Если же существует очень большое желании использовать не-ASCII символы в значениях заголовков, то проткол предлагает кодировать данные в MIME, хотя поддержка и использование этой возможности не является широко распространенной практикой.
Стратегия разбора запроса
Разбор запроса состоит из следующих шагов:
Читаем первую строку, т.е. request line, разбираем ее на метод, цель и версию и сохраняем их в некоторую структуру данных.
Читаем построчно заголовки, разбираем их на имя и значение и сохраняем в словаре (aka ассоциативном массиве) с именем заголовка в качестве ключа. Индикатором конца секции заголовков служит пустая строка.
На основе метода и заголовков определяем, содержит ли запрос тело. Если да, поточно читаем байты из соединения до тех пор, пока прочитанное количество не равно ожидаемому размеру тела запроса. Техника чтения может отличаться в зависимости от типа запроса, подробнее см. секцию Чтение тела запроса.
Как было отмечено ранее, чтение строк должно осуществляться с использованием кодировки ISO/IEC 8859-1. Применение других кодировок возможно только к значениям элементов сообщения (т.е. к значениям заголовков или телу запроса).
Разбор request line
В качестве разминки выполним разбор request line, самой первой строки HTTP-запроса. Прежде всего, из соединения необходимо прочитать строку, т.е. последовательность байт, заканчивающуюся комбинацией \r\n . Простейший способ — это читать данные байт за байтом, сохраняя их в некотором буфере, пока не будет найдена необходимая комбинация:
Однако, такой подход достаточно неэффективен, так как каждый вызов conn.recv() приводит к системному вызову, а значит имеет высокие накладные расходы. К счастью, благодаря широчайшим возможностям стандартной библиотеки Python, сокет предоставляет возможность создать вокруг него некоторую обертку, которая предоставляет file object интерфейс:
Так как мы фокусируемся только на версии HTTP/1.1, код разбора получился достаточно коротким и простым. Все, что мы сделали — это прочитали строку из соединения и разбили ее по пробелу на составляющие — метод, цель и версию, сохранив их в структуре Request.
Разбор заголовков запроса
Перейдем к следующему шагу — разбору HTTP-заголовков. Запрос с заголовками выглядит следующим образом:
Таким образом, необходимо читать строку за строкой, до тех пор, пока не будет встречена первая пустая строка. Выполним небольшой рефакторинг кода нашего сервера, выделив разбор request line и разбор заголовков в отдельные методы:
В результате, мы получили список отдельных заголовков headers вида:
В то же время, мы планировали сохранять заголовки HTTP-сообщений в ассоциативном массиве, где ключами бы являлись ключи заголовков (например, Host, Accept или User-Agent), а значениями — соответствующие значения полей. Одним из вариантов было бы продолжить разбор, разбивая каждый элемент списка по символу : и сохраняя левую часть в качестве ключа, а правую — в качестве значения в некотором dict:
Однако, существует достаточно большое количество частных случаев, которые подход выше не учитывает. Например, в одном сообщении может быть несколько заголовков с одинаковым именем, т.е. в общем случае по ключу в hdict должен находиться скорее список, а не одна строка; значения заголовков могут быть представлены в MIME-кодировке; и пр.
К счастью, формат HTTP-сообщений, как и email-сообщений, следует спецификации Internet Message Format. Стандартная библиотека Python предоставляет модуль email, который в частности может быть использован для разбора HTTP-заголовков. Нам понадобится внести лишь минимальное изменение в метод parse_headers() , чтобы воспользоваться стандартным парсером:
Возвращаемое значение метода Parser.parsestr() — это объект email.message.Message , который напоминает OrderedDict . Ключи в Message — это отсортированные в порядке появления ключи заголовков.
Последнее, что мы сделаем в рамках задачи разбора заголовков — это проверим наличие и соответствие заголовка Host:
Обработка запроса
Настало время заняться непосредственно обработкой HTTP-запросов, т.е. бизнес-логикой нашего сервера. Одной из традиционных задач, выполняемых HTTP-сервером, является отдача статического контента, т.е. файлов и директорий из некоторой корневой директории. Мы же опустим эту функцию и сфокусируемся на кастомной логике приложения.
Представим, что мы хотим создать сервис, который позволяет регистрировать пользователей, получать список ID зарегистрированных пользователей, а также информацию о каждом пользователе по его ID. Опишем API нашего сервиса:
Дополнительно, в зависимости от заголовка запроса Accept, сервер будет возвращать данные либо в формате HTML, либо JSON.
Прежде, чем приступать непосредственно к обработке, давайте расширим возможности класса Request, чтобы впоследствии код обработки получился чуть более высокоуровневым. Добавим полезные методы path и query , которые будут разбивать цель вида /users?name=Vasya&age=42 на /users и <'name': ['Vasya'], 'age': ['42']>, соответственно:
Обработка запросов начинается в методе handle_request() . Сам метод занимается скорее диспетчеризацией запросов на основе метода и цели, чем непосредственно обработкой:
Давайте посмотрим на метод создания пользователя handle_post_users() :
Все очень просто — на основании данных из запроса создаем новый объект пользователя и сохраняем его на сервере. Ответом на такой запрос является лишь строка статуса HTTP/1.1 204 Created\r\n . Класс Response можно определить следующим образом:
Следующий функция нашего приложения — это возвращение списка зарегистрированных пользователей handle_get_users() . В данном случае нам понадобится полноценный ответ, содержащий в себе перечисление всех пользователей на сервере. А в качестве дополнительной возможности, наш сервер будет поддерживать два формата данных — text/html и application/json:
Важно обратить внимание на способ представления body . Так как наш ответ содержит символы кириллицы, ASCII кодировка нам не подходит. Мы работаем с body как со строкой в кодировке UTF-8. Однако, прежде чем создать объект ответа, мы кодируем строку в последовательность байт, а заголовок Content-Length, представляющий собой размер ответа, принимает значение длины уже в байтах. Заголовок Content-Type при этом содержит секцию ; charset=utf-8 , по которой клиенты нашего сервера могут определить кодировку тела ответа.
Реализацию последнего метода нашего приложения handle_get_user(user_id) можно посмотреть в полном исходном коде сервера в конце статьи.
Отправка ответа
Последний шаг, отделяющий нас от минимальной рабочей версии — это отправка HTTP-ответов. Код отправки достаточно прост. Прежде всего записываем в соединение status line вида HTTP/1.1 <status_code> <reason> . Затем, построчно записываем заголовки и не забываем пустую строку, обозначающую конец секции заголовков. Все вышеперечисленные данные должны быть представлены в кодировке ISO/IEC 8859-1. При наличии тела ответа, ожидаем, что оно уже представлено последовательностью байт и просто отправляем его в сокет:
В случае возникновения ошибки на сервере, нам также необходимо отправить ответ. Для этого реализуем метод send_error() , фактически являющийся оберткой вокруг метода send_response() :
Теперь мы можем ввести класс HTTPError(Exception) и заменить в коде сервера вхождения вида raise Exception('Not found') на raise HTTPError(404, 'Not found') .
Запустим наш сервер:
И протестируем его, создав двух пользователей:
Теперь попробуем получить информацию о зарегистрированных пользователях — в формате HTML и в формате JSON:
Также попробуем протестировать сообщения об ошибке:
Чтение тела запроса
До настоящего момента, наш сервер не умел работал с телом запроса. Расширим класс Request, добавив тривиальную реализацию метода body() :
Если абстрактно представить себе проблему передачи сообщений по сети, то задача чтения одного сообщения может быть непротиворечиво решена только если: сообщения всегда имеют фиксированную длину, сообщения имеют метаинформацию о размере, сообщения разделены некоторым набором символов. В случае протокола HTTP используется подход с передачей метаинформации в заголовоке Content-Length, определяющем длину тела сообщения.
Необходимо заметить, что не все типы запросов могут иметь тело. Например, запросы GET не должны иметь тела сообщения.
Протокол HTTP также предоставляет возможность передачи больших объемов данных, разбивая их на части (т.н. chunk-и). В таком случае добавляется специалльный заголовок Transfer-Encoding: chunked , а тело запроса (или ответа) представляется блоками байт, каждый из которых имеет префикс в виде длины блока. Подробнее тут Chunked transfer encoding.
Повторное использование TCP-соединений
Протокол HTTP поддерживает отправку нескольких последовательных (в версии HTTP2 поддерживается также мультиплексирование) HTTP-запросов в рамках одного TCP-соединения. Несмотря на то, что наш сервер мгновенно закрывает соединение после отправки ответа, поведением по умолчанию для протокола HTTP/1.1 является сохранение соединения открытым для повторного его использования клиентом. Это так называемый механизм HTTP keep-alive. В случае же, если клиент или сервер по каким-либо причинам не хотят реиспользовать соединение, необходимо добавить заголовок Connection: close .
Заключение
Реализованный нами HTTP-сервер объединяет в себе как непосредственно работу с протоколом, так и более высокоуровневую обработку HTTP-запросов, суть — бизнес-логику приложения. Очевидным развитием архитектуры веб-сервера является отделение редко меняющейся протокольной части от специфичной и волатильной бизнес-логики приложения. Более того, формализация программного интерфейса HTTP-сервера в виде некоторого стандарта позволила бы создавать переносимые между серверами приложения, избегая дублирования кода. Не удивительно, что Python-сообщество уже решило эту проблему, введя стандарт взаимодействия сервера и приложения WSGI. В следующей статье мы рассмотрим, что из себя представляет эта спецификация и как на уровне кода можно научить приложение взаимодействовать с любым WSGI-совместимым HTTP-сервером.