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)¶
This class builds on the
TCPServerclass by storing the server address as instance variables namedserver_nameandserver_port. The server is accessible by the handler, typically through the handler’sserverinstance variable.- server_name¶
The HTTP server’s fully qualified domain name.
- server_port¶
The HTTP server’s port number obtained from server_address.
- class http.server.ThreadingHTTPServer(server_address, RequestHandlerClass)¶
Цей клас ідентичний HTTPServer, але використовує потоки для обробки запитів за допомогою
ThreadingMixIn. Це корисно для роботи з веб-браузерами, які попередньо відкривають сокети, на якихHTTPServerчекатиме нескінченно довго.Added in version 3.7.
HTTPServer і ThreadingHTTPServer повинні отримати RequestHandlerClass під час створення екземпляра, для якого цей модуль надає три різні варіанти:
- 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 (for example,
'GET'or'POST').BaseHTTPRequestHandlerprovides 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, thedo_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¶
Contains the request path. If the query component of the URL is present, then
pathincludes the query. Using the terminology of RFC 3986,pathhere includeshier-partand thequery.
- request_version¶
Містить рядок версії із запиту. Наприклад,
'HTTP/1.0'.
- headers¶
Holds an instance of the class specified by the
MessageClassclass variable. This instance parses and manages the headers in the HTTP request. Theparse_headers()function fromhttp.clientis used to parse the headers and it requires that the HTTP request provide a valid RFC 5322 style header.
- 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¶
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 fromresponsesbased on the status code passed tosend_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 accurateContent-Lengthheader (usingsend_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 appropriatedo_*()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-continuerequest header it responds with a100 Continuefollowed by200 OKheaders. This method can be overridden to raise an error if the server does not want the client to continue. For example, the server can choose to send417 Expectation Failedas a response header andreturn 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_formatattribute and emitted, after a complete set of headers, as the response body. Theresponsesattribute 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_headerend_headers()ПОТРІБНО викликати, щоб завершити операцію.This method does not reject input containing CRLF sequences.
Змінено в версії 3.2: Заголовки зберігаються у внутрішньому буфері.
- send_response_only(code, message=None)¶
Sends the response header only, used for the purposes when
100 Continueresponse is sent by the server to the client. The headers are not buffered and sent directly the output stream. If the message is not specified, the HTTP message corresponding the response code is sent.This method does not reject message containing CRLF sequences.
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, ...)¶
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 tolog_message()are applied as inputs to the formatting. The client IP address and current date and time are prefixed to every message logged.
- 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__визначено на рівні модуля.
- index_pages¶
Specifies the filenames that are treated as directory index pages.
Defaults to
("index.html", "index.htm").Added in version 3.12.
- extensions_map¶
Суфікси словника, що відображають типи MIME, містять користувацькі заміни для стандартних системних відображень. Відображення використовується без урахування регістру, тому має містити лише ключі в нижньому регістрі.
Змінено в версії 3.9: Цей словник більше не заповнюється типовими системними відображеннями, а містить лише перевизначення.
Клас
SimpleHTTPRequestHandlerвизначає такі методи:- do_HEAD()¶
Цей метод обслуговує тип запиту
'HEAD: він надсилає заголовки, які б надіслав для еквівалентного запитуGET. Перегляньте методdo_GET()для більш повного пояснення можливих заголовків.
- do_GET()¶
Запит відображається в локальному файлі шляхом інтерпретації запиту як шляху відносно поточного робочого каталогу.
If the request was mapped to a directory, the directory is checked for an index page as specified by
index_pages. If found, the file’s contents are returned; otherwise a directory listing is generated by calling thelist_directory()method. This method usesos.listdir()to scan the directory, and returns a404error response if thelistdir()fails.If the request was mapped to a file, it is opened. Any
OSErrorexception in opening the requested file is mapped to a404,'File not found'error. If there was an'If-Modified-Since'header in the request, and the file was not modified after this time, a304,'Not Modified'response is sent. Otherwise, the content type is guessed by calling theguess_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
testfunction in Lib/http/server.py.Змінено в версії 3.7: Підтримка заголовка
'If-Modified-Since.
- list_directory(path)¶
Helper to list the contents of path when no index page is present.
This returns either a file-like object (which must be closed by the caller) or
Noneto indicate an error, in which case the caller has nothing further to do. In either case, the headers are sent.
- guess_type(path)¶
Guess the type of the file at the given path.
This returns a string of the form
type/subtype, usable for a MIME Content-type header.The default implementation looks the file’s extension up in
extensions_map, falling back tomimetypes.guess_file_type()and then to'application/octet-stream'.Змінено в версії 3.13: Add
mimetypes.guess_file_type()as a fallback.
The SimpleHTTPRequestHandler class can be used to create a very basic
webserver serving files relative to the current directory as follows:
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.
- class http.server.CGIHTTPRequestHandler(request, client_address, server)¶
Цей клас використовується для обслуговування файлів або виведення сценаріїв CGI з поточного каталогу та нижче. Зауважте, що зіставлення ієрархічної структури HTTP зі структурою локального каталогу відбувається точно так само, як у
SimpleHTTPRequestHandler.Примітка
Сценарії CGI, що виконуються класом
CGIHTTPRequestHandler, не можуть виконувати перенаправлення (код HTTP 302), тому що код 200 (вивід сценарію йде далі) надсилається перед виконанням сценарію CGI. Це випереджає код стану.Однак клас запустить сценарій CGI замість того, щоб подавати його як файл, якщо він здогадається, що це сценарій CGI. Використовується лише CGI на основі каталогу — іншою загальною конфігурацією сервера є розгляд спеціальних розширень як позначення сценаріїв CGI.
The
do_GET()anddo_HEAD()functions are modified to run CGI scripts and serve the output, instead of serving files, if the request leads to somewhere below thecgi_directoriespath.CGIHTTPRequestHandlerвизначає такий елемент даних:- cgi_directories¶
За замовчуванням це
['/cgi-bin', '/htbin']і описує каталоги, які слід вважати такими, що містять сценарії CGI.
CGIHTTPRequestHandlerвизначає такий метод:- do_POST()¶
Цей метод обслуговує тип запиту
'POST', дозволений лише для сценаріїв CGI. Помилка 501 «Можна публікувати лише сценарії CGI» виводиться під час спроби ПУБЛІКАЦІЇ за URL-адресою, яка не є CGI.
Зауважте, що сценарії CGI виконуватимуться з UID користувача nobody з міркувань безпеки. Проблеми зі сценарієм CGI будуть переведені на помилку 403.
Deprecated since version 3.13, will be removed in version 3.15:
CGIHTTPRequestHandleris being removed in 3.15. CGI has not been considered a good way to do things for well over a decade. This code has been unmaintained for a while now and sees very little practical use. Retaining it could lead to further security considerations.
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¶
The server listens to port 8000 by default. The default can be overridden by passing the desired port number as an argument:
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
--bindoption.
- -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.
- --cgi¶
CGIHTTPRequestHandlercan be enabled in the command line by passing the--cgioption:python -m http.server --cgi
Deprecated since version 3.13, will be removed in version 3.15:
http.servercommand line--cgisupport is being removed becauseCGIHTTPRequestHandleris being removed.
Попередження
CGIHTTPRequestHandler and the --cgi command-line option
are not intended for use by untrusted clients and may be vulnerable
to exploitation. Always use within a secure environment.
Міркування безпеки¶
SimpleHTTPRequestHandler will follow symbolic links when handling
requests which makes it possible for files outside of the specified directory
to be served.
Methods BaseHTTPRequestHandler.send_header() and
BaseHTTPRequestHandler.send_response_only() assume sanitized input
and do not perform input validation such as checking for the presence of CRLF
sequences. Untrusted input may result in HTTP header injection attacks.
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.