Bottle Source reading notes (a): WSGI

Source: Internet
Author: User

Objective

Bottle is a Python web framework. The entire framework has only one file, less than 4k lines of code, and no dependencies outside of the Python standard library, but contains common features of web frameworks such as routing, templates, and plug-ins. It would be appropriate to read the bottle source code to understand what web frameworks and web frameworks work. Since bottle is a framework for supporting WSGI, before reading the source code, let us first understand what is WSGI.

Note: The bottle version used in this article is 0.12.13.

WSGI

A typical Web server can only handle static pages. If dynamic content is involved, the server needs to interact with the server languages such as Java/python/ruby and give the content to them. Since most Web servers are written in C, they cannot execute the server language directly, so a bridge is needed between the two (in practice, an application server is typically added to the Web server and WSGI application to support Wsgi). And in Python, Wsgi is such a bridge. The implementation of WSGI is divided into two parts, one is the server, the other is the application. Let's take a look at what they look like and how they work together.

 1 class Server:2 3 def __init__ (self, server_address): 4 self.server_address = server_address 5 6 def             Set_app (self, application): 7 Self.app = Application 8 9 def serve_forever (self): ten while True:11 # socket.accept () if Request_comein (): Self.handle_request () + def Handle_ Request (self): Request_data = Self.get_request () self.parse_request (request_data) environ = Self.get_environ () result = Self.application (environ, self.start_response) self.send_response (Result) 2 1 def start_response (self, status, headers, Exc_info): Pass24 def Get_environ (self): pas S27 def get_request (self): PASS30-def parse_request (self, text): Pass33 + def Send_ Response (self, message): Pass36 Notoginseng def make_server (host, port, app, Server=server): The Server ((ho St, Port)).Set_app (APP) return SERVER42-def simple_app (environ, start_response): status = ' OK ' Response_head ers = [(' Content-type ', ' Text/plain ')]46 start_response (status, Response_headers) "Hello world! ' if __name__ = = ' __main__ ': "Server = make_server" (' localhost ', 8080, Simple_app) server.serve_forever ()

Limited to space, this server model omits a lot of detail, if you want a simple and can run Wsgi server, you can refer here let's Build a Web server.part 2.

After the server receives the request, the information of the request message is parsed and the result is saved in a dictionary named Environ. The application application (environ, start_response) is then invoked with Environ and the start_response function that handles the header information as a parameter. Finally, the result of the application is composed of a new response, which is sent back to the client.

On the application side, the WSGI application is a callable object. It can be a function, a method, a class, or an __call__ instance with a method. The above application is a function.

When various servers and applications/frameworks are developed in accordance with WSGI standards, we can freely combine different servers and frameworks as needed.

Bottle The simplest application

After a brief look at Wsgi, we go back to bottle to see what a bottle application looks like, how it works, and how it differs from our model.

1 from bottle import bottle, run2 3 app = Bottle () 4 5 @app. Route ('/hello ') 6 def hello (): 7     return ' Hello world! ' 8 9 Run (app, host= ' localhost ', port=8080, server= ' Wsgiref ')

Now run this program and use the browser to access the address ' Localhost:8080/hello ' and you will see ' Hello world! '.

1. Unlike the above application, the bottle application is an example. According to Wsgi, the bottle object is to implement the __call__ method:

1 def __call__ (self, Environ, start_response): 2     "Each instance of:class: ' Bottle ' is a WSGI application. "' 3     return Self.wsgi (environ, start_response)

So this bottle.wsgi method is the server call bottle application of the portal, but also we read the source of the entrance.

2. @app. Route () This adorner binds a function to a URL. When we access ' Localhost:8080/hello ', the Hello function is called.

3. Bottle default server is Wsgiref (a wsgi simple implementation in the Python standard library). Of course bottle also wrote adapters (Adapter) for many servers, just to change the server's value, the run () function looks for the appropriate adapter based on the name of the server. There is no need to write extra code.

The run function and the adapter section code:

1 def run (app=none, server= ' wsgiref ', host= ' 127.0.0.1 ', port=8080, 2         interval=1, Reloader=false, Quiet=false, Plugins=none, 3         debug=none, **kargs): 4     if server in server_names:5         server = server_names.get (server) 6     if Isinstance (server, basestring): 7         Server = Load (server) 8     if isinstance (server, type): 9         Server = Ser Ver (host=host, Port=port, **kargs)     if not isinstance (server, Serveradapter): Raise ValueError         ("Unknown or Unsupported server:%r "% server" ...     Server.run (APP) Meinheldserver (serveradapter):     def run (self, handler): + from         Meinheld Import server18         server.listen ((Self.host, Self.port))         Server.run (handler)

At last

In this article, we briefly describe how servers and applications interact under the WSGI standard. Next, we continue around this simplest application, speaking about the routing features associated with @app.route ().

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.