Python--eventlet.wsgi

Source: Internet
Author: User
Tags deprecated

Eventlet's WSGI module provides a simple way to start an event-driven WSGI server that can be used as an embedded Web server for an application, or as a mature Web server, such as an example of a Web server such as spawning.

Directory

First, the Eventlet WSGI server

1. Eventlet.wsgi.server ()

2. Eventlet.wsgi.format_data_time ()

Second, SSL

Third, Post hooks

Iv. "Continue" response head

First, Eventlet's WSGI server

To start a WSGI server, simply create a socket and use it to call Eventlet.wsgi.server ().

For example:

 fromEventletImportWsgiImportEventletdefHello_world (env, Start_response): Start_response ('OK', [('Content-type','Text/plain')])    return['Hello, world!\r\n.']wsgi.server (Eventlet.listen ("', 8090)), Hello_world)

This simple server uses Eventlet.listen () to create a socket, wsgi.server () listens for the corresponding address, port, etc., and passes the request to the WSGI application Hello_world processing.

A slightly more vivid example is as follows:

ImportEventlet fromEventletImportWsgidefHello_world (env, start_response):ifenv['Path_info'] !='/': Start_response ('404 Not Found', [('Content-type','Text/plain')])        return['Not found\r\n'] Start_response ('OK', [('Content-type','Text/plain')])    return['Hello, world!\r\n.']wsgi.server (Eventlet.listen ("', 8090)), Hello_world)

This example is a very concise interpretation of the WSGI application interface specification, and also covers the use of server in the Eventlet.wsgi module.

1.

Eventlet.wsgi.server ()

eventlet.wsgi.server (socket, Site,log=None, environ=None, Max_size=None, Max_http_version='http/1.1', Protocol=<classEventlet.wsgi.HttpProtocol at 0x7f4f68192f58>, server_event=None, Minimum_chunk_size=None, Log_x_forwarded_for=True, Custom_pool=None, KeepAlive=True, Log_output=True, Log_format='% (CLIENT_IP) s--[% (Date_time) s] "% (request_line) S"% (Status_code) s% (body_length) s% (wall_seconds). 6f', Url_length_limit=8192, Debug=True, Socket_timeout=None, Capitalize_response_headers=true)

This call encapsulates a number of features that create a WSGI server to handle requests that are generated in a specified socket, and this function loops through the request at all times. When the server exits, the corresponding socket object socket will be closed but the underlying file descriptor will be retained, so if you invoke the DUP () with this socket, you will still be able to use it.

Parameters:

Socket Server socket, already bound to a port and listening in
Site Functions to implement WSGI applications

Log

The location of the log output should be a class file (File-like) object with the default of Sys.stderr
Environ Additional parameters added to the Environ dictionary for each request
Max_size Maximum number of client connections allowed at this server time
Max_http_version Set to "http/1.0" will only support HTTP 1.0. Can support applications that do not work properly under HTTP 1.1
Protocol Deprecated, Protocol class
Server_event Deprecated, used to collect Server objects
Minimum_chunk_size The minimum size of the HTTP block in bytes. Can be used to improve the performance of applications that produce many small strings. Although using it technically violates the WSGI specification, it is possible to override the extent of each request by setting environ[' Eventlet.minimum_write_chunk_size ')
Log_x_forwarded_for If True (the default), the contents of the X-forwarded-for in the HTTP header are recorded in addition to the actual client IP address recorded in the ' Client_ip ' segment of the log
Custom_pool A custom Greenpool instance that is used to incubate the client's greenthreads. If the item is set, ignore the parameter max_size
KeepAlive Set to False disables server keepalives, and all connections are closed after the service has completed a request
Log_output A Boolean value that indicates whether the server logs the log
Log_format A python format string is used as the template to generate log lines. The following values can be formatted into IT:CLIENT_IP, Date_time, Request_line, Status_code, Body_length, Wall_seconds. The default is a good example by
Url_length_limit Maximum length of the request URL, if long, returns a 414 error
Debug This is set to TRUE if you want the server to send the exception trace back to the client in error 500. If this is set to false,server it will respond with a null value
Socket_timeout Socket operation timeout limit for client connections, default is None, meaning permanent wait
Capitalize_response_headers The field name of the uppercase response header, which is true by default

2.

eventlet.wsgi.format_date_time (timestamp)

Formats the UNIX timestamp as an HTTP standard string.

Second, SSL

To create a secure server, you only need to pass in a socket for an SSL package:

Wsgi.server (Eventlet.wrap_ssl (                              eventlet.listen (('), 8090),                              certfile='  cert.crt',                              keyfile='private.key',                              server_side=True),            Hello_world)

Applications can determine whether they are in an SSL server by using the environment variable env['wsgi.url_scheme' .

Third, support the non-standard extension of Post hooks

Eventlet's WSGI server supports non-standard extensions for WSGI specifications--with env[' eventlet.posthooks '] containing an array of several post hooks . These post hooks are called after the response is completely sent. Each post hook is a tuple in the format (func, args, kwargs) , with WSGI environment dictionary plus args and Kwargs for parameters called Func.

For example:

 fromEventletImportWsgiImportEventletdefHook (env, arg1, arg2, Kwarg3=none, kwarg4=None):Print('Hook called:%s %s%s%s%s'%(env, arg1, arg2, Kwarg3, KWARG4))defHello_world (env, start_response): env['Eventlet.posthooks'].append (Hook, ('arg1','arg2'), {'Kwarg3': 3,'Kwarg4': 4})) Start_response ('OK', [('Content-type','Text/plain')])    return['Hello, world!\r\n.']wsgi.server (Eventlet.listen ("', 8090)), Hello_world)

The code above prints the WSGI environment and other function parameters for each requested processing.

Post hooks are useful when you need to execute a piece of code after a client request has been fully responded to (or after the client disconnects prematurely). An example is the accurate recording of bandwidth usage, because the bandwidth consumed by the user when disconnecting is less than the value content-length.

Iv. "Continue" response head

Eventlet's WSGI server supports sending (optional) headers and HTTP "Continue" temporary responses. This is useful in such cases where a WSGI server expects to complete a PUT request as a single HTTP request/response pair, And also wants to communicate back to client as part of the same HTTP transaction. An example are where the HTTP server wants to pass hints back to the client about characteristics of data payload it can AC Cept. As an example, an HTTP server could pass a hint in a header the accompanying "Continue" response to the client Indicatin G It can or cannot accept encrypted data payloads, and thus client can make the encrypted vs unencrypted decision before s tarting to send the data).

This works well for WSGI servers as the WSGI specification mandates HTTP expect/continue mechanism (PEP333).

To define the "Continue" response header, you need to call Set_hundred_continue_response_header () in env[' Wsgi.input ') as follows:

 fromEventletImportWsgiImportEventletdefWsgi_app (env, start_response):#Define "Continue" Response headersenv['Wsgi.input'].set_hundred_continue_response_headers ([('hundred-continue-header-1','H1'),         ('hundred-continue-header-k','Hk')])    #the following read () causes "Continue" response to    #The client. Headers ' Hundred-continue-header-1 ' and    #' hundred-continue-header-k ' is sent with the response    #following the "http/1.1 continue\r\n" status lineText = env['Wsgi.input'].read () start_response ('OK', [('Content-length', str (len (text)))]) return[Text]

Python--eventlet.wsgi

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.