Как поднять сервер на python

от admin

Пишем простой сервер на Python

Ну, начнем как и везде с определений, берите тетрадь и ручку сейчас начнется нудятина. Чтобы мы cмогли написать свой сервер, нужно для начала понимать как он вообще работает, ловите определение:

Сервер – это программное обеспечение, которое ожидает запросов клиентов и обслуживает или обрабатывает их соответственно.

Если объяснять это своими словами, представьте фургон с хот-догами(сервер), проголодавшись, вы(клиент) подходите и говорите повару, что вы хотите заказать(запрос), после чего повар обрабатывает, что вы ему сказали и начинает готовить, в конечном итоге вы получаете свой хот-дог(результат) и сытый радуетесь жизни. Для наглядности посмотри схему.

Околопрактика

Для написания сервера мы будем использовать Python и модуль Socket.

Socket позволяет нам общаться с сервером с помощью сокетов. Весь код я постараюсь пояснять, дабы ты мой дорогой читатель все понял. В конце статьи будет готовый код.

Создайте два файла в одной директории:

socket_server.py

socket_client.py

Практика

Пишем код для серверной части, так что открывайте файл socket_server.py.

Начнем с импорта модуля и создания TCP-сокета:

Далее весь код будет с комментариями:

Добавим вечный цикл, который будет считывать данные с клиентской части, и отправлять их обратно.

Переходим к клиентской части, весь код теперь пишем в файле socket_client.py.

Начало у клиентской части такое-же как и у серверной.

Далее подключимся к нашему серверу и отправим сообщение «Hello. Habr!».

Слева сервер, справа клиент

Слева сервер, справа клиент

Заключение

Вот мы с вами и написали свой первый сервер, рад был стараться для вас, ниже будет готовый код.

Creating a Python3 Webserver From the Ground Up

Jumping into Python’s web code when your previous experience is mostly in web-based languages (PHP, Javascript, Ruby) can be a daunting task. Python has all of the tools available to make a strong HTTP Server or framework, as well as plenty of mature web frameworks to get started with, but the purpose of this tutorial/write-up isn’t to show you how to leverage those, but how to build one from the ground up (similarly to how you’d start learning with NodeJS) to give you a more complete understanding of how the components can fit together.

Throughout this tutorial, we’ll go through a few different steps, the first of which is included today:
1. Setting up a basic HTTP server that will respond to basic GET requests with a stock message (“Hello World”) and then expand that to have a router that allows us to request different HTML files.
2. Incorporate appropriate file responses for requests (HTML, images, CSS, Javascript)
3. Allow our routes to take parameters, respond in-kind with the appropriate data and set up API routes
4. Add a view rendering library and incorporate a database into our application

A basic understanding of Python3’s syntax and OOP components will help you through this tutorial. Components important to the server will be explained as we move through, but basic syntax will not be explained.

The full source code will be available on Git once it’s completed, and the source code for today’s tutorial will be at the end of the article.

Let’s dive right in.

Setting Up

Python3

First and foremost, let’s make sure we’re running the right version — we’ll be building this on Python3, which you’ll need to have it installed.

You can run a which python3 on a Linux box to make sure it’s available, if not, follow the appropriate steps to install the latest python3 binary.

Note — on Macs, the version that ships out of the box (i.e. what happens when you run python ) is version 2, which means you’ll need to install the latest version. Homebrew makes this easy.

Setting Up Our Editor

You can use your editor of choice for this, but I’d recommend at least the following:
— The syntax package for your editor
— A linter (pylint is a good choice)

Setting Up Our Project

main.py

Create the directory in which you want the webserver to live.

Once you have a new directory, create two files in the root — the initial will be main.py to house our execution script, and server.py which will contain the class that will be running our server.

First, let’s fill out our `main.py`. Where needed, I’ll fill out comments about the code after the presented code blocks.

First, we’re importing the necessary packages that we’ll be using in this file:

The time package simply writes timestamps for when our server goes up or down.

The `http.server` package contains the HTTP server boilerplate from the Python3 standard library. We’re importing a single module from this — HTTPServer .

The server module is the other file we’ll be filling out here in a moment, as of now, it’s going to show an error for the improper import. We’re importing a single class, Server from our module.

Next, we define two constants we’ll be using when we launch the server: HOST_NAME=localhost which will launch our server on our localhost and PORT_NUMBER=8000 which is the port we want it to run on (feel free to change this port if your 8000 is occupied).

Next up, we have the boilerplate for running our server. The first line if __name__ == ‘__main__’: is assuring that we ran this file specifically. If that’s the case, we’ll execute the rest of the code.

Next, we create the HTTP object:
httpd = HTTPServer((HOST_NAME, PORT_NUMBER), Server)

We pass the following parameters to the HTTPServer object that we imported earlier:

  • We pass a tuple containing the HOST_NAME and PORT_NUMBER
  • As a second argument, we pass the server handling class Server , imported from our own file, that we’ll fill out in a moment

The next line simply prints our “Server UP” with the timestamp to the console. We’re using the Python string formatting operator to pass in the constants as well:
print(time.asctime(), ‘Server Starts — %s:%s’ % (HOST_NAME, PORT_NUMBER))

This next block actually starts up the server and runs it:

This tells our created httpd object to serve until it receives a keyboard interrupt. Once that happens, it closes out the server connection with httpd.server_close .

Our last print line simply outputs a message when the server is closed.
print(time.asctime(), ‘Server Stops — %s:%s’ % (HOST_NAME, PORT_NUMBER))

Next, let’s set up our server handler.

server.py

Let’s go ahead and stub out the file with the following class:

We’ll be using these methods to handle the responses. On our first line, we import the BaseHTTPRequestHandler from the http.server package. This is going to be the class that ours will subclass. There are some important things to note:

— When a request comes in, the BaseHTTPRequestHandler will automatically route the request to the appropriate request method (either do_GET, do_HEAD or do_POST ) which we’ve defined on our subclass

— We’ll use handle_http to send our basic http handlers and then return the content.

— respond will be in charge of sending the actual response out

In order to first respond, our class will need to be able to send, at minimum, three things:

— the response’s Content-type ,
— the response’s status code ,
— and finally the actual content of the site

Let’s add this to our class now so that it can send a basic “Hello World” response to a GET request in plain text to make sure our server is working as intended:

Let’s look at the changes, starting at our handle_http method.

As stated before, this method is going to take care of sending our header and generally putting the response in a format where it’s ready to be sent. All arguments in our handle_http method will be passed in from the respond method. The flow of data will look like this when a request is received:

do_* receives request > respond invoked > handle_http bootstraps request, returns content > respond sends the response

In the first line, we’re sending the status code through the send_response method inherited from the BaseHTTPRequestHandler .

In the next line, we’re sending the Content-type header with send_headers , also passed in from our respond method. We end the headers we’re sending (for now!) with the self.end_headers method.

Next, we return the content we want to send (“Hello World” for now), converted into a bytes object with UTF-8 encoding. Anything you send back in your response will need to be in this format. We’ll add additional handling later to take care of objects that are already in this byte format (for example, images).

Next, let’s look at the respond method.

For now, it’s passing through a 200 success code and the content type (‘text/html’) to the handle_http method. Finally we run the self.wfile.write method to send the finalized content out as the response.

Our do_GET method simply kicks off this process as it will be the one the BaseHTTPRequestHandler triggers when a GET request is received.

At this point, our server is ready to run. Navigate to the directory your project is housed in and run python3 main.py to start up the server. Navigate to your chosen port (8000) in the above instructions, and you should see a “Hello World” response.

We now have a webserver!

Adding a Router

Obviously, right now, this is not much of a webserver — we’re just passing “Hello World” out to the user.

One of the most important facets of a websever is being able to respond to requests at different URLs — it’s not really useful without it. So next, we’re going to go ahead and create a router.

A router, at its core, just allows us to map a given request to a given resource on our webserver. This sounds very similar to a given structure in Python (the dictionary) which allows us to map keys to their specific values.

Let’s create a new folder (routes) and create a file inside that directory ( main.py ).

Since we’re currently working with text, we’re going to set up our router to just respond with text data when a given route is hit.

Let’s fill this out:

This is very simple at the moment, but we’ll be filling it out further in our examples.

Next, let’s import the routes file into our server.py :

Next, let’s adjust our handle_http to grab content from the routes file dependent on the current path:

All we need to do is pull the self.path member from the class and then pass it into the routes[] dictionary that we pulled from our routes file. It’s pretty straightforward — we’re just looking it up by key at the moment. We then pass the route_content into our return in order to pass it on to the respond method.

If you visit the URLs you specified in your routes.py file, you should now be able to see the intended text response at each URL (after a server restart).

Sending HTML

Next we’re going to make the routes file respond with HTML rather than just text — far more useful.

Let’s create a few more files. Start by creating a “templates” folder which will house our HTML (for now, index.html and goodbye.html ):

You can put whatever you want in these files for now, but leave out any references to CSS or JS because our server will not be able to handle those right now (though we’ll be getting to that).

Here’s our (very simple) index.html file:

We also need to change our routes file — we’re going to go ahead and nest another dictionary within our current keys:

The template key within our nested dictionary is going to handle pointing to our specific template file for a given route.

Next, we’ll adjust our server.py file to pull those specific files:

We’ll cover the changes starting with our new import:
from pathlib import Path

We’re importing the Path module from pathlib to make sure that our HTML files exist before we attempt to read their contents.

Next, we’ll go down to our handle_http method:

We’re doing a few things differently now:

  • The method no longer takes any arguments, instead we’ll be building out the response type and status code within our function so that we can respond with a 404 or other status code if necessary
  • We’re doing a check to ensure that our path exists within our routes to ensure that the path actually exists. If it doesn’t, we’ll send a 404 with a text/plain response
  • Within this check, we’re pulling the given route’s template into the route_content variable and then passing it to open
  • Once this is pulled, we use .read to get the HTML file’s content. If the file doesn’t exist, we throw a 404.
  • After this, the only changes are that the content_type is now dynamic, and the response_content is equivalent to what we set it to earlier.

Go ahead and fire up the server and check your index page — you should now we be able to see the content you put in your index.html file. Next, go to /goodbye and you’ll be able to see the content in the goodbye.html file.

Some Refactoring, and Error Handling for Non-HTML Requests

Okay, so, we’ve created a server that is capable of returning HTML files for a specific URL, but we haven’t yet built something that can handle everything else an HTML file needs to do, namely, being able to include CSS, Javascript and Image files from the server.

We’re going to be building that out (in the next article), but the first thing we want to do is some refactoring. In the current files, we’re handling everything on a case-by-case basis which will very quickly balloon into a massive handle_http function, and isn’t a particularly clean way to handle it.

Go ahead and create a new folder, named “response”. This response folder is going to house a few classes that will allow us to tailor the response for specific types of files (e.g. templates vs static assets vs errors) in a much cleaner way.

Within this folder, let’s create the base RequestHandler class and name it requestHandler.py :

Within this file, we’re going to do two things:

  • Create a MockFile class — this is a placeholder object that will take care of requests where we won’t have a .read function on the self.contents member.
  • If we don’t have this, Python will yell at us, despite the fact that we’ll be supplying the results of open calls later that have a read function.
  • We’re also declaring our RequestHandler here that will be the class we extend to handle each type of request. There are a number of different methods we’re declaring on this object which are mostly getters and setters for the various attributes that each request type will have. Also important to note is what we’re not declaring here: We have no mechanism to actually retrieve the file — this is because we’re going to delegate that to the child classes so that they can each individually handle where the files should be imported from, as well as any specific handling that needs to happen to those files (and some response types won’t even have files to open).

Next, let’s go ahead and define a child class that will extend this to handle our templates and get our server back up and running:

Within our TemplateHandler class, the first thing we’re doing is importing our RequestHandler from the previous file. We pass it into the constructor for the class so that it inherits from that class:

Next up, we define two methods — within our __init__ we set the content-type for our HTML templates (which will always be text/html ).

We define the find method which will allow the template to find the specific file and set the contents so that we can pull them out within our server file.

We now have a class that will handle our templates, but in our server.py we currently have two different types of requests that need handled — the templates, and “bad” requests, such as a 404 if the file is not found. Let’s go ahead and implement a BadRequestHandler as well.

Simple enough — this one doesn’t need a find method because there’s nothing to find, it’s just a 404 so the content-type can be simple, and the status will be a 404.

Let’s change up our server.py to reflect the changes we made — for now we’ll only be handling HTML requests and sending 404s for everything else:

We’ve changed some of the logic around — our do_GET will now be handling the actual request with our RequestHandler objects.

First, let’s look at the new imports:

Here we’re importing the os package that will allow us to split the extension from the request path so that we can match against the extension and use the appropriate handler.

Let’s look at our do_GET method:

First, we split the path into its parts using os.path.splitext . We then pull the file extension from the array we just created.

We then have a conditional to check if our extension is either “” or “.html” . This will handle requests for both .html files directly, and for simple URL requests (e.g. localhost:8000/, localhost:8000/goodbye).

Next, we have the same logic we previously did to see if the path exists in our routes file. If the path is valid, we create a new `TemplateHandler()` and then use the handler’s `.find` method, passing in the routes object which looks like this:

In our else we use a BadRequestHandler to signal the 404 on the file.

In our next else (if the route isn’t found) we create another BadRequestHandler to handle the 404.

Finally, we use self.respond and send the created handler through to the respond method which will then be passed into our handle_http method.

Let’s look at respond next:

The only change here is that we’re passing through an opts argument that contains the handler , and then passing that through to the handle_http method call.

Finally, let’s check out the new handle_http :

First, we pull the status_code from the handler. If a BadRequestHandler made its way through, it’ll be a 404, otherwise a 200 in the TemplateHandler unless the handler was unable to find the file, in which case it will also respond with a 404 (check out the TemplateHandler ’s logic to see this in action).

We go ahead and send the status code, and then if the status code is 200 (OK) we go ahead and pull the contents of the file with handler.getContents . This does an internal call to .read on the file that we opened.

Next, we send a header with the content type, again pulled from our handler .

Читать:
Как включить компьютер без клавиатуры

We end the headers, and then go ahead and send our result.

We’re now reading files using our RequestHandler class, and we’ve cleaned up our server.py quite a bit (or at least made it more understandable and extensible). You should now be able to restart your server and take a look at the HTML pages for the specific routes, and routes that are not included should send a 404 message.

That’s it for today’s tutorial — when the second part of this is published, we’ll take a look at how we can add other resources (CSS, Javascript, etc) when the HTML pages automatically requests them (like, how, you know, the web actually works).

You can find the repository with the code up to this point at this Github link.

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, . The shortmessage is usually used as the message key in an error response, and longmessage as the explain key. It is used by send_response_only() and send_error() methods.

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.

9001 способ создать веб-сервер на Python

Подпишись на обновления блогa, чтобы не пропустить следующий пост!

Дополняемый список способов запустить веб-сервер на Python:

Модуль socket и прямые руки

Берем модуль socket из стандартной библиотеки, создаем серверный сокет, принимаем входящие подключения, вычитываем и обрабатываем запросы и отправляем ответы. Все своими руками. Подробнее можно почитать тут.

Синхронный TCP сервер

Возможна обработка только одного клиента в один момент времени, весь код выполяется в одном процессе и одном (главном) потоке.

Многопоточный TCP сервер

Очевидный недостаток синхронного подхода — отсутствие какой бы то ни было конкурентной обработки запросов. Берем модуль threading и начинаем обрабатывать каждый запрос в отдельном потоке.

Пул потоков-обработчиков

Недостаток подхода с потоком на каждый входящий запрос — накладные расходы на запуск новых потоков. Вводим пул потоков-обработчиков, минимум N из которых не должны завершаться после завершения обработки запроса, получаем сокращение накладных расходов на запуск.

Многопроцессный TCP сервер

Альтернативный (и исторически более ранний) взгляд на обработку — каждый запрос в отдельном процессе. Берем низкоуровневый os.fork() и клонируем главный процесс сервера на каждый входящий запрос.

Модуль socketserver

Модуль стандартной библиотеки socketserver предназначен для сокращения рутинных действий при написании серверов на Python. Фактически, он предоставляет те же возможности, что и сервера в разделе Модуль socket и прямые руки, но. Просто сравните количество кода.

Класс TCPServer

Базовый, но не абстрактный класс для создания TCP сервера. Аналогичен синхронному TCP серверу. Только один клиент в один момент времени. Предоставляет функциональность для запуска сервера, приема входящих соединений и минимальной обработки ошибок. Обработка же запросов вынесена в класс BaseRequestHandler. Для создания обработчика необходимо отнаследоваться от BaseRequestHandler и определить как минимум метод handle().

ThreadingMixIn + TCPServer

С синхронным TCPServer мы опять не можем обрабатывать входящие запросы конкурентно. Берем ThreadingMixIn и получаем многопоточный TCP сервер:

ForkingMixIn + TCPServer

Аналогично многопоточному серверу можно создать многопроцессный сервер, используя ForkingMixIn.

Поточная обработка

Когда запрос или ответ слишком большой, держать его целиком в памяти неэффективно, требуется вычитывать или записывать запрос по частям. Еще одна ситуация, когда может пригодиться поточная обработка — пошаговое формирование ответа, когда даже небольшие части ответа имеют ценность для клиента сами по себе и могут быть отправлены клиенту немедленно. Для этих целей идеально подходит класс StreamRequestHandler:

Модуль asyncio

Синхронная обработка запросов — непозволительная роскошь неэффективная неэффективность. Процессы и потоки — ограниченная конкурентная обработка, подходящая для десятков или сотен одновременных (и быстрых) запросов. Но что делать, если запросов тысячи? Или если каждое соединение может длиться минуты или даже часы (привет, WebSocket-ы)? Всех спасет asyncio — модуль стандартной библиотеки для написания высокопроизводительных сетевых приложений на основе асинхронного ввода-вывода. В частности, asyncio предоставляет реализацию асинхронного TCP сервера:

Модуль http.server

Когда сетевого и транспортного уровня не достаточно и хочется работать на 7 небе уровне модели ISO OSI, поможет модуль стандартной библиотеки http.server. Модуль определяет классы для реализации HTTP серверов. В их числе HTTPServer, являющийся наследником socketserver.TCPServer, и ThreadingHTTPServer на основе ThreadingMixIn.

Этот модуль не для боевого применения! Его использование может привести к вызову произвольного кода на сервере!

В то же время, это удобная и полезная штука, позволяющая с помощью Python и ничего более, запускать HTTP сервер на локальной машине, например, чтобы раздавать статику.

Пример кастомизации HTTP сервера: отдаем специальный Content-Type заголовок для *.wasm файлов:

Похожие статьи