http.server — HTTP servers

Вихідний код: Lib/http/server.py


Цей модуль визначає класи для реалізації HTTP-серверів.

Попередження

http.server is not recommended for production. It only implements basic security checks.

Availability: not WASI.

This module does not work or is not available on WebAssembly. See WebAssembly platforms for more information.

Один клас, HTTPServer, є підкласом socketserver.TCPServer. Він створює та прослуховує HTTP-сокет, надсилаючи запити обробнику. Код для створення та запуску сервера виглядає так:

def run(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler):
    server_address = ('', 8000)
    httpd = server_class(server_address, handler_class)
    httpd.serve_forever()
class http.server.HTTPServer(server_address, RequestHandlerClass)

Цей клас будується на основі класу TCPServer, зберігаючи адресу сервера як змінні екземпляра з іменами server_name і server_port. Сервер доступний обробнику, як правило, через змінну екземпляра обробника server.

class http.server.ThreadingHTTPServer(server_address, RequestHandlerClass)

Цей клас ідентичний HTTPServer, але використовує потоки для обробки запитів за допомогою ThreadingMixIn. Це корисно для роботи з веб-браузерами, які попередньо відкривають сокети, на яких HTTPServer чекатиме нескінченно довго.

Added in version 3.7.

class http.server.HTTPSServer(server_address, RequestHandlerClass, bind_and_activate=True, *, certfile, keyfile=None, password=None, alpn_protocols=None)

Subclass of HTTPServer with a wrapped socket using the ssl module. If the ssl module is not available, instantiating a HTTPSServer object fails with a RuntimeError.

The certfile argument is the path to the SSL certificate chain file, and the keyfile is the path to file containing the private key.

A password can be specified for files protected and wrapped with PKCS#8, but beware that this could possibly expose hardcoded passwords in clear.

Дивись також

See ssl.SSLContext.load_cert_chain() for additional information on the accepted values for certfile, keyfile and password.

When specified, the alpn_protocols argument must be a sequence of strings specifying the «Application-Layer Protocol Negotiation» (ALPN) protocols supported by the server. ALPN allows the server and the client to negotiate the application protocol during the TLS handshake.

By default, it is set to ["http/1.1"], meaning the server supports HTTP/1.1.

Added in version 3.14.

class http.server.ThreadingHTTPSServer(server_address, RequestHandlerClass, bind_and_activate=True, *, certfile, keyfile=None, password=None, alpn_protocols=None)

This class is identical to HTTPSServer but uses threads to handle requests by inheriting from ThreadingMixIn. This is analogous to ThreadingHTTPServer only using HTTPSServer.

Added in version 3.14.

The HTTPServer, ThreadingHTTPServer, HTTPSServer and ThreadingHTTPSServer must be given a RequestHandlerClass on instantiation, of which this module provides three different variants:

class http.server.BaseHTTPRequestHandler(request, client_address, server)

Цей клас використовується для обробки HTTP-запитів, які надходять на сервер. Сам по собі він не може відповідати на жодні фактичні запити HTTP; він повинен бути підкласом для обробки кожного методу запиту (наприклад, GET або POST). BaseHTTPRequestHandler надає ряд змінних класу та екземпляра, а також методів для використання підкласами.

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 має такі змінні екземпляра:

client_address

Містить кортеж у формі (хост, порт), який посилається на адресу клієнта.

server

Містить екземпляр сервера.

close_connection

Логічне значення, яке має бути встановлено перед поверненням handle_one_request(), вказуючи, чи можна очікувати ще один запит, чи з’єднання має бути закрито.

requestline

Містить рядкове представлення рядка запиту HTTP. Кінцевий CRLF видаляється. Цей атрибут має бути встановлено handle_one_request(). Якщо дійсний рядок запиту не оброблено, його слід встановити на порожній рядок.

command

Містить команду (тип запиту). Наприклад, 'GET'.

path

Містить шлях запиту. Якщо компонент запиту URL-адреси присутній, тоді path включає запит. Використовуючи термінологію RFC 3986, path тут включає hier-part і query.

request_version

Містить рядок версії із запиту. Наприклад, 'HTTP/1.0'.

headers

Містить екземпляр класу, визначеного змінною класу MessageClass. Цей екземпляр аналізує та керує заголовками в запиті HTTP. Функція parse_headers() з http.client використовується для аналізу заголовків і вимагає, щоб HTTP-запит надав дійсний заголовок стилю RFC 2822.

rfile

Вхідний потік io.BufferedIOBase, готовий для читання з початку додаткових вхідних даних.

wfile

Містить вихідний потік для запису відповіді клієнту. Щоб досягти успішної взаємодії з HTTP-клієнтами, під час запису в цей потік необхідно належним чином дотримуватися протоколу HTTP.

Змінено в версії 3.6: Це потік io.BufferedIOBase.

BaseHTTPRequestHandler має такі атрибути:

server_version

Визначає версію програмного забезпечення сервера. Ви можете змінити це. Формат — кілька рядків, розділених пробілами, де кожен рядок має назву форми[/version]. Наприклад, «BaseHTTP/0.2».

sys_version

Містить версію системи Python у формі, придатній для використання методом version_string і змінною класу server_version. Наприклад, 'Python/1.4'.

error_message_format

Визначає рядок формату, який має використовуватися методом send_error() для створення відповіді про помилку клієнту. Рядок за замовчуванням заповнюється змінними з responses на основі коду стану, переданого в send_error().

error_content_type

Визначає HTTP-заголовок Content-Type відповідей про помилки, надісланих клієнту. Значення за замовчуванням - 'text/html'.

protocol_version

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'.

MessageClass

Визначає email.message.Message-подібний клас для аналізу заголовків HTTP. Як правило, це не перевизначається, і за замовчуванням має значення http.client.HTTPMessage.

responses

Цей атрибут містить відображення цілих чисел коду помилки в двоелементні кортежі, що містять коротке та довге повідомлення. Наприклад, {code: (shortmessage, longmessage)}. shortmessage зазвичай використовується як ключ message у відповіді про помилку, а longmessage як ключ explain. Він використовується методами send_response_only() і send_error().

Екземпляр BaseHTTPRequestHandler має такі методи:

handle()

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.

handle_one_request()

This method will parse and dispatch the request to the appropriate do_*() method. You should never need to override it.

handle_expect_100()

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.

Added in version 3.2.

send_error(code, message=None, explain=None)

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.

Змінено в версії 3.4: Відповідь про помилку містить заголовок Content-Length. Додано аргумент explain.

send_response(code, message=None)

Додає заголовок відповіді до буфера заголовків і реєструє прийнятий запит. Рядок відповіді HTTP записується у внутрішній буфер, а потім ідуть заголовки Server і Date. Значення для цих двох заголовків беруться з методів version_string() і date_time_string() відповідно. Якщо сервер не має наміру надсилати будь-які інші заголовки за допомогою методу send_header(), тоді за send_response() має слідувати виклик end_headers().

Змінено в версії 3.3: Заголовки зберігаються у внутрішньому буфері, і end_headers() потрібно викликати явно.

send_header(keyword, value)

Додає HTTP-заголовок до внутрішнього буфера, який буде записаний у вихідний потік під час виклику end_headers() або flush_headers(). keyword має вказувати ключове слово заголовка, а value — його значення. Зауважте, що після завершення викликів send_header end_headers() ПОТРІБНО викликати, щоб завершити операцію.

Змінено в версії 3.2: Заголовки зберігаються у внутрішньому буфері.

send_response_only(code, message=None)

Надсилає лише заголовок відповіді, який використовується для цілей, коли відповідь 100 Continue надсилається сервером клієнту. Заголовки не буферизуються та надсилаються безпосередньо в вихідний потік. Якщо повідомлення не вказано, надсилається HTTP-повідомлення, що відповідає коду відповіді.

Added in version 3.2.

end_headers()

Adds a blank line (indicating the end of the HTTP headers in the response) to the headers buffer and calls flush_headers().

Змінено в версії 3.2: Буферизовані заголовки записуються у вихідний потік.

flush_headers()

Нарешті надішліть заголовки у вихідний потік і очистіть внутрішній буфер заголовків.

Added in version 3.3.

log_request(code='-', size='-')

Реєструє прийнятий (успішний) запит. code має вказувати числовий код HTTP, пов’язаний із відповіддю. Якщо доступний розмір відповіді, його слід передати як параметр size.

log_error(...)

Записує помилку, коли запит не може бути виконано. За замовчуванням він передає повідомлення в log_message(), тому приймає ті самі аргументи (формат і додаткові значення).

log_message(format, ...)

Записує довільне повідомлення до sys.stderr. Зазвичай це замінюється, щоб створити спеціальні механізми реєстрації помилок. Аргумент format — це стандартний рядок форматування у стилі printf, де додаткові аргументи log_message() застосовуються як вхідні дані для форматування. IP-адреса клієнта, поточна дата й час додаються до кожного зареєстрованого повідомлення.

version_string()

Повертає рядок версії програмного забезпечення сервера. Це комбінація атрибутів server_version і sys_version.

date_time_string(timestamp=None)

Повертає дату й час, задані timestamp (які мають бути None або у форматі, що повертається time.time()), відформатовані для заголовка повідомлення. Якщо timestamp пропущено, використовуються поточні дата й час.

Результат виглядає так: 'Sun, 06 Nov 1994 08:49:37 GMT''.

log_date_time_string()

Повертає поточну дату й час у форматі для журналювання.

address_string()

Повертає адресу клієнта.

Змінено в версії 3.3: Раніше було виконано пошук імені. Щоб уникнути затримок розпізнавання імен, тепер завжди повертається IP-адреса.

class http.server.SimpleHTTPRequestHandler(request, client_address, server, directory=None)

Цей клас обслуговує файли з каталогу directory і нижче, або з поточного каталогу, якщо directory не надано, безпосередньо відображаючи структуру каталогу на HTTP-запити.

Змінено в версії 3.7: Added the directory parameter.

Змінено в версії 3.9: Параметр directory приймає path-like object.

Велику частину роботи, наприклад розбір запиту, виконує базовий клас BaseHTTPRequestHandler. Цей клас реалізує функції do_GET() і do_HEAD().

Наступне визначено як атрибути рівня класу SimpleHTTPRequestHandler:

server_version

Це буде "SimpleHTTP/" + __version__, де __version__ визначено на рівні модуля.

extensions_map

Суфікси словника, що відображають типи MIME, містять користувацькі заміни для стандартних системних відображень. Відображення використовується без урахування регістру, тому має містити лише ключі в нижньому регістрі.

Змінено в версії 3.9: Цей словник більше не заповнюється типовими системними відображеннями, а містить лише перевизначення.

Клас SimpleHTTPRequestHandler визначає такі методи:

do_HEAD()

Цей метод обслуговує тип запиту 'HEAD: він надсилає заголовки, які б надіслав для еквівалентного запиту GET. Перегляньте метод do_GET() для більш повного пояснення можливих заголовків.

do_GET()

Запит відображається в локальному файлі шляхом інтерпретації запиту як шляху відносно поточного робочого каталогу.

Якщо запит було зіставлено з каталогом, каталог перевіряється на наявність файлу з назвою index.html або index.htm (у такому порядку). Якщо знайдено, повертається вміст файлу; інакше список каталогу створюється шляхом виклику методу list_directory(). Цей метод використовує os.listdir() для сканування каталогу та повертає відповідь про помилку 404, якщо listdir() не вдається.

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 an '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.

Виводиться заголовок 'Content-type:'' з припущеним типом вмісту, а потім заголовок 'Content-Length:'' із заголовком 'Content-Length:'' із заголовком розміру файлу та 'Last-Modified:''. заголовок із часом модифікації файлу.

Then follows a blank line signifying the end of the headers, and then the contents of the file are output.

For example usage, see the implementation of the test function in Lib/http/server.py.

Змінено в версії 3.7: Підтримка заголовка 'If-Modified-Since.

Клас SimpleHTTPRequestHandler можна використовувати таким чином, щоб створити простий веб-сервер, який обслуговує файли відносно поточного каталогу:

import http.server
import socketserver

PORT = 8000

Handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print("serving at port", PORT)
    httpd.serve_forever()

SimpleHTTPRequestHandler can also be subclassed to enhance behavior, such as using different index file names by overriding the class attribute index_pages.

Command-line interface

http.server can also be invoked directly using the -m switch of the interpreter. The following example illustrates how to serve files relative to the current directory:

python -m http.server [OPTIONS] [port]

Приймаються такі варіанти:

port

За замовчуванням сервер слухає порт 8000. Значення за замовчуванням можна змінити, передавши потрібний номер порту як аргумент:

python -m http.server 9000
-b, --bind <address>

Specifies a specific address to which it should bind. Both IPv4 and IPv6 addresses are supported. By default, the server binds itself to all interfaces. For example, the following command causes the server to bind to localhost only:

python -m http.server --bind 127.0.0.1

Added in version 3.4.

Змінено в версії 3.8: Support IPv6 in the --bind option.

-d, --directory <dir>

Specifies a directory to which it should serve the files. By default, the server uses the current directory. For example, the following command uses a specific directory:

python -m http.server --directory /tmp/

Added in version 3.7.

-p, --protocol <version>

Specifies the HTTP version to which the server is conformant. By default, the server is conformant to HTTP/1.0. For example, the following command runs an HTTP/1.1 conformant server:

python -m http.server --protocol HTTP/1.1

Added in version 3.11.

--tls-cert

Specifies a TLS certificate chain for HTTPS connections:

python -m http.server --tls-cert fullchain.pem

Added in version 3.14.

--tls-key

Specifies a private key file for HTTPS connections.

This option requires --tls-cert to be specified.

Added in version 3.14.

--tls-password-file

Specifies the password file for password-protected private keys:

python -m http.server \
       --tls-cert cert.pem \
       --tls-key key.pem \
       --tls-password-file password.txt

This option requires –tls-cert` to be specified.

Added in version 3.14.

Міркування безпеки

SimpleHTTPRequestHandler will follow symbolic links when handling requests, this makes it possible for files outside of the specified directory to be served.

Earlier versions of Python did not scrub control characters from the log messages emitted to stderr from python -m http.server or the default BaseHTTPRequestHandler .log_message implementation. This could allow remote clients connecting to your server to send nefarious control codes to your terminal.

Змінено в версії 3.12: Control characters are scrubbed in stderr logs.