The connection between Web server and Python application in layman's

Source: Internet
Author: User

Simply put, a Web server is a program that runs on a physical server, and it waits forever for the client (primarily a browser, such as Chrome,firefox, etc.) to send a request. The WEB server accepts Http Request, returns Response, and many times Response is not a static file, so an application is required to generate the corresponding Response based on the request. The application is mainly used to process the related business logic, read or update the database, and return the corresponding Response according to different Request. The bridge between the two is Wsgi.

Always like to study the underlying technology, before the Python web framework web.py operating mechanism is confused, probably learned the next flask framework and the Django framework is based on the Python WSGI protocol, Python provides a simple Wsgi server implementation--wsgiref, on the site to find two examples run a bit, really, the first time to run a bit more confused, although know the bottom is dependent on the socket, but in-depth no further research, also do not understand. So spent a few days, a solid look at the source, while Baidu side understand, and finally learned a lot. Sometimes feel that they let the "spoiled", because of the Microsoft closed-source relationship, the basic knowledge of their own not all, in a lot of the framework of the use, only will, the principle of a 3344, or a lot of bad, really open source is good, a word against the source, it is indeed learned a lot, Python is also a very powerful language, which is the biggest feeling I have to read the source code.

For the basics that you need for this article, you can find it in the following links:
Build a forum from scratch (1): Web server vs. Web framework
Build a forum from scratch (2): Web Server Gateway Interface
Honestly, before I read these two articles, although I have a good understanding of the Web server, Web framework, but still relatively vague, these two articles are very well written. Bole Online is also a good technology site!

After reading these two articles, there is a certain foundation. First on the code:

# main.py
1 #Coding:utf-82 Import Time3 fromRestyImportPathdispatcher4 fromWsgiref.simple_serverImportMake_server5 6 7_hello_resp =" "8 9 Ten <title>hello {name}</title> One A <body> - - </body> the " " - - - defHello_world (environ, start_response): + #handing response status and response headers to WSGI server - #From wsgiref.handlers import Simplehandler +Start_response ('OK', [('Content-type','text/html')]) Aparams = environ['params'] atRESP = _hello_resp.format (Name=params.get ('name')) - yieldResp.encode ('Utf-8') - - -_localtime_resp =" " - <?xml version= "1.0"?> in <time> - <year>{t.tm_year}</year> to <month>{t.tm_mon}</month> + <day>{t.tm_mday}</day> - the <minute>{t.tm_min}</minute> * <second>{t.tm_sec}</second> $ </time>" "Panax Notoginseng - the deflocaltime (environ, start_response): + #handing response status and response headers to WSGI server AStart_response ('OK', [('Content-type','Application/xml')]) theRESP = _localtime_resp.format (t=time.localtime) + yieldResp.encode ('Utf-8') - $ $ #Impersonate a client - if __name__=='__main__': -Dispatcher =Pathdispatcher () theDispatcher.register ('GET','/hello', Hello_world) -Dispatcher.register ('GET','/localtime', localtime)Wuyi the #start a simple server -httpd = Make_server ("', 8080, Dispatcher) Wu Print "serving on port 8080 ..." -Httpd.serve_forever ()#turn on the loop mechanism
# resty.py
1 #Coding:utf-82 ImportCGI3 4 5 defnotfound_404 (environ, start_response):6Start_response ('404 Not Found', [('Content-type','Text/plain')])7 return['Not Found']8 9 Ten #use of middleware One classPathdispatcher: A def __init__(self): -Self.pathmap = {} - the #The ability of an object of this class to have a function, the object can accept the argument, just like a function call, this function is called in handlers.py - def __call__(self, Environ, start_response): -Path = environ['Path_info'] -params = CGI. Fieldstorage (environ['Wsgi.input'], environ=environ) + -method = environ['Request_method'].lower () +environ['params'] = {Key:params.getvalue (key) forKeyinchParams#Dictionary Derivation type AHandler =Self.pathmap.get (method, Path), notfound_404) at returnhandler (environ, start_response) - - defregister (self, method, path, function): -Self.pathmap[method.lower (), Path] =function - returnfunction

Then I analyze the role of Python's own WSGI server main file:

simple_server.py simulates a simple Web server, handlers.py is the WSGI protocol wrapper handler for the HTTP protocol. Look at it:

As shown above, I've probably summed up the role of different py files. I previously had a vague effect on WSGI, even though I knew Wsgi was the bridge between the Web server and the Web application, but honestly! After the client browser has typed in a newline, the Python application performs exactly what is important and the order in which it is called. And looking at the code above, I ask you a question:
When was the __call__ function called? Did you see the __call__ call in the program? Although the __CALL__ function is a built-in function (I commented on it), I already have the definition, and now I have the implementation code, what about the calling program? Forgive as an engineering student horn tip, see the program inside there is a dubious call really suppressed-.-
After reading the following, you should understand


Build << start from scratch Forum (2): Web Server Gateway Interface >> read it and understand __call
Functions of the __ function. However, let me explain, the whole debug to you to see:


Programming Environment: Win7//////////Ide:vs code///////python version:2.7.13
I separately in main.py, handlers, resty.py down point, start Debug put ....


When the debug console appears "serving on port 8080 ..." means that the client browser is now waiting for access, below, we write in the browser Http://127.0.0.1:8080/hello?name=Ryan


Figure 15 Note the value of the Envron variable, which is a variable of type dict, and you can see the "?" in our browser. All the key-value in the back were saved. Passed to the Python application.

Of course, to complete a full URL access is certainly more than the call of these function modules, this is the main call, and this has been a good explanation of my previous problems, well, according to the figure to understand it

The connection between Web server and Python application in layman's

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.