python ---- basis functions

--- --- restore content begins

 All languages Web框架nature is actually from a socketserver, listening on a port, and then run up

Web框架Comprising two parts, one socket, the other part of the business logic processing, processed differently depending on the request

Python is Web框架divided into two categories,

  1. I.e. comprising socket also contains the business logic processing (Tornado)

  2. Does not contain a socket (socket frame itself achieved through third-party modules) includes only business logic (django, Flask)

WSGIStands Web Server Gateway Interface, translates to is the Web Server Gateway Interface. Specifically speaking, WSGI is a specification that defines how a Web server to interact with Python applications that use Python to write Web applications and Web servers can butt up. WSGI start is defined in PEP-0333, the latest version of the Python PEP-3333 definition.

The code examples below RunServer()is a HTTP handler WSGI-compatible function, which accepts two parameters:

  1. environ: A HTTP request contains all the information dict objects;

  2. start_response: Transmitting a HTTP response function;

By wsgirefimplementing a custom moduleweb框架

Probably logic code is: defines two functions index()and manage(), if the user accesses the URL is 127.0.0.1:8000/indexreturned <h1>/index</h1>, if a user visits is 127.0.0.1:8000/managereturned /manage, if returned to visit other pages404

#!/usr/bin/python2
# _*_coding:utf-8 _*_
from wsgiref.simple_server import make_server

def index(arg):
    Html # Returns a string containing a code
    return "<h1>%s</h1>" %(arg)

def manage(arg):
    return arg

URLS = {
    "/index": index,
    "/manage": manage,
}

def RunServer(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    url = environ['PATH_INFO']
    if url in URLS.keys():
        func_name = URLS[url]
        ret = func_name(url)
    else:
        ret = "404"
    return right

if __name__ == '__main__':
    httpd = make_server('', 8000, RunServer)
    httpd.serve_forever()

By curl command of the unit to access the test

yangwen@yangwen:~$ curl 127.0.0.1:8000/index
<h1>/index</h1>ansheng@Darker:~$ curl 127.0.0.1:8000/asdasd
404yangwen@yangwen:~$ curl 127.0.0.1:8000/manage
/manage
 

 

No matter how complex Web applications, the entrance is a WSGIhandler. All input information by HTTP request can environbe obtained, the output may be HTTP response by start_response()adding the function as the return value Body, complex Web applications, alone, or a function to handle too WSGI bottom, we need on WSGI then abstracted Web framework, to further simplify Web development.

 

--- end --- restore content

Guess you like

Origin www.cnblogs.com/Autism/p/11776097.html