[Python Web Development] using the WSGI Development Class Flask Framework (II)

Source: Internet
Author: User
Tags webp

WSGI Web Server Gateway Interface

Wsgi primarily specifies how Web servers communicate with Web applications and how Web applications are linked together to process a request.

Wsgiref WSGI reference module in Python

One, WSGI application side:

1, according to WSGI definition, the application should be callable object

2, the callable object must have two fixed parameters: one is a dictionary containing server environment variables, and the other is a callable object that initializes the response using HTTP status codes and HTTP headers returned to the client

The Environ variable contains some familiar environment variables, such as Http_host,http_user_agent,remote_addr,request_method,server_port, as in the following sections:

Hello world! Gateway_interface = ' cgi/1.1 ' http_accept = ' text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image /apng,*/*;q=0.8 ' http_accept_encoding = ' gzip, deflate, br ' http_accept_language = ' zh-cn,zh;q=0.9,en;q=0.8 ' HTTP_ CONNECTION = ' keep-alive ' http_host = ' 127.0.0.1:9999 ' http_user_agent = ' mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) applewebkit/537.36 (khtml, like Gecko) chrome/63.0.3239.84 safari/537.36 ' query_string = ' remote_a DDR = ' 127.0.0.1 ' request_method = ' GET ' server_port = ' 9999 ' server_protocol = ' http/1.1 ' server_software = ' wsgiserver/0.2 ‘

3. This callable object must return an iterative object to be used to compose the response

There are several submodules in the Wsgiref Reference library:

* Util--some useful functions and packaging

* Headers--Management response header

* Handlers--the base class for how to deal with Server/gateway

* Simple_server--Implement a simple WSGI HTTP server

* Validate--check wrapper between application and server for error detection

Second, the use of WSGI HTTP server side

1. Start a simple wsgi HTTP Server:

# Simple Web 1from wsgiref.simple_server import make_serverdef demo_app (environ, start_response): #copy自simple_server模块 From    io import stringio    stdout = Stringio ()    print ("Hello world!", file=stdout)    print (file=stdout)    h = sorted (Environ.items ())    for K, V in H:        print (k, ' = ', repr (v), file=stdout)    start_response ("OK", [(' Content-type ', ' text/plain; Charset=utf-8 ')])    return [Stdout.getvalue (). Encode ("Utf-8")]ip = ' 127.0.0.1 ' port = 9999server = Make_server (IP, port, Demo_app) Server.serve_forever () Server.server_close ()
Wsgiref.simple_server.make_server (host, port, app, Server_class=wsgiserver, Handler_class=wsgirequesthandler)
To start a WSGI server, you must pass in host, port, app three parameters.

After running this program, we have implemented a webserver that listens on port 9999, the following is the server running status and the results of the browser access:

Visit http://127.0.0.1:9999/#server端运行状态: 127.0.0.1--[26/dec/2017 15:01:13] "get/http/1.1"-2128127.0.0.1--[26/dec/ 15:01:13] "Get/favicon.ico http/1.1" 200 2096# browser access result: Hello world! Apple_pubsub_socket_render = '/private/tmp/com.apple.launchd.gx10g4snot/render ' clicolor = ' 1 ' CONTENT_LENGTH = ' Content_Type = ' text/plain ' gateway_interface = ' cgi/1.1 ' grep_options = '--color=auto ' HOME = '/users/ihoney ' HTTP_ACCEPT = ' text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 ' HTTP_ACCEPT_ENCODING = ' gzip, deflate, br ' http_accept_language = ' zh-cn,zh;q=0.9,en;q=0.8 ' http_connection = ' keep-alive ' http_host = ' 127.0.0.1:9999 ' http_upgrade_insecure_requests = ' 1 ' http_user_agent = ' mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) applewebkit/537.36 (khtml, like Gecko) chrome/63.0.3239.84 safari/537.36 ' lc_ctype = ' zh_cn. UTF-8 ' ...

  

2. Customize the response page content:

# Simple Web 2from wsgiref.simple_server import make_serverdef Application (environ:dict,start_response):    # print (Type ( Environ), environ)    html = "

Browser Access results:

Simple_server is only a reference and cannot be used in production environments.

Parsing of query_string query string

1. Use the CGI module:

# Simple Web 3 uses CGI module parsing query_stringimport cgifrom wsgiref.simple_server import make_serverdef application (Environ:dict, Start_response):    qstr = Environ.get ("query_string")    print (QSTR)    #? id=5&name=ihoney&age=18,19    Print (Cgi.parse_qs (QSTR)) #字典, value is the list type    print (CGI.PARSE_QSL (qstr)) #二元组列表    html = "

When writing, the IDE tool will prompt that the CGI module has expired, it is recommended to use the Urllib library.

2. Using the Urllib Library

# Simple Web 4 uses Urllib module parsing query_stringfrom urllib import parsefrom wsgiref.simple_server import make_serverdef Application ( Environ:dict,start_response):    qstr = Environ.get ("query_string")    print (QSTR)    #? Id=5&name=ihoney &age=18,19    Print (Parse.parse_qs (QSTR)) #字典, value is the list type    print (PARSE.PARSE_QSL (qstr)) #二元组列表    html = " 

  

3. Using a third-party library Webob

PIP3 Install Webob

Third-party library Webob can encapsulate the parsing of the environment data into objects, which are called directly when used.

3.1 Webob. Request

#简单web 5, use third-party library Webob to resolve from Wsgiref.simple_server import make_serverfrom webob import Request, Responsedef application ( Environ:dict, start_response): request = Request (environ) print (request.method) print (Request.path) print (req Uest. GET) print (Request. POST) print (request.params) print (request.query_string) HTML = "

  

3.2 Webob. Resphone

#from wsgiref.simple_server Import make_serverfrom webob import Request, responsedef application (environ:dict, Start_ Response):    res = response ("

  

3.3 Multidict

Request.get and Request.post are multidict dictionaries.

# multidictfrom webob.multidict Import MULTIDICTMD = Multidict () md[1] = ' B ' md.add (1, ' a ') print (Md.get (1)) #只返回一个值print ( Md.getall (1)) # Print (Md.getone (1)) #要求key的value只能有一个, otherwise throw Keyerror exception print (Md.get (' C ')) #不存在返回默认值None # Run Result: a[' B ', ' a ' ]none

 

3.4 Webob.dec.wsgify Decorator

Turn a function into a WSGI application

# wsgifyfrom wsgiref.simple_server Import make_serverfrom webob import Request, response,decdef application (environ: Dict, Start_response):    res = response ("

  

Improved:

From wsgiref.simple_server import make_serverfrom webob import Request, response,dec@dec.wsgifydef app (request:request )-Response:return Response ("

  

Summarize:

This article briefly introduces some usages of WSGI, WSGI HTTP Server, query string processing, third-party library Webob.

  

[Python Web Development] using the WSGI Development Class Flask Framework (II)

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.