Python Learning-writing a simple web framework (i)

Source: Internet
Author: User
Tags response code

Write yourself a web framework, because I am a rookie, some of Python's built-in functions are not clear, so before writing this article requires some pre-knowledge of Python and Wsgi, this is a series of articles. This article only implements how URLs are handled.

Refer to this article: http://www.cnblogs.com/russellluo/p/3338616.html

Pre-knowledge

The web framework primarily implements the interaction between Web servers and Web applications. The underlying network protocol is mainly done by the Web server. such as listening ports, filling messages and so on.

Python built-in functions __iter__ and __call__ and Wsgi iterators iterator

Iterators provide an interface to a class sequence object for a sequence of classes, meaning that a class sequence object can iterate like a sequence through an iterator. The simple thing to say is to traverse the object. If you want your class to be iterative, you must implement __ITER__ and next ().

__call__

As long as the __call__ method is implemented when the class is defined, the object of the class is adjustable, that is, the object can be used as a function. This is only used to understand what the __call__ function is, as required in the WSGI specification.

WSGI

About WSGI the introduction can click Http://webpython.codepoint.net, have a very detailed introduction. Here's just a little bit about. The WSGI interface is implemented with callable objects: a function, a method, or a callable instance. Here is an example of a comment written in detail:

# This is our Application object. It could has any name,# except if using MOD_WSGI where it must be "application" DEF application (# It accepts the Argume NTS: # environ points to a dictionary containing CGI like environment variables # which are filled by the server For each received request from the client environ, # Start_response are a callback function supplied by the serve  R # which'll be used to send the HTTP status and headers to the server Start_response): # Build the response Body possibly using the environ dictionary response_body = ' The request method was%s '% environ[' Request_method '] #   HTTP response code and Message status = ' $ OK ' # These is HTTP headers expected by the client.   # They must be wrapped as a list of tupled pairs: # [(header name, header value)].  Response_headers = [(' Content-type ', ' Text/plain '), (' Content-length ', str (len (response_body)))] # Send them to the server using the supplied function Start_response (status, Response_headers) # Return the response body.   # Notice It is wrapped in a list although it could being any iterable. return [Response_body]

In simple terms, the corresponding result is returned based on the parameters received.

Designing a Web Framework

I used Django to write a very simple blog, currently on the SAE, long time no update. Website: http://3.mrzysv5.sinaapp.com. The basic requirement of a web framework is to simplify the user's code volume. So in Django, I just need to write the view, model, and URL configuration files. Here's a function that I wrote with Django when I was working with a view:

def blog_list (Request):    blogs = Article.objects.all (). order_by ('-publish_date ')    blog_num = Article.objects.count ()    return render_to_response (' index.html ', {"Blogs": Blogs, "Blog_num": Blog_num}, Context_ Instance=requestcontext (Request)) def blog_detail (request):    bid = Request. Get.get (' id ', ')    blog = Article.objects.get (id=bid)    return render_to_response (' blog.html ', {' blog ': blog})

All I have to do is manipulate the database and return the appropriate resources. So the web framework I'm writing is going to encapsulate some of the underlying operations as much as possible, leaving the user with some usable interfaces. According to my observations, the web framework is processed roughly as follows:

    1. A WSGI applied base class is initialized when the configured URL file is passed in
    2. User-written processing method, base class call method according to URL
    3. Return to Client View

A WSGI base class that has the following functions:

    • handles the environ parameter
    • to get the method or class name based on the URL, and then returns
Import Reclass wsgiapp:headers = [] def __init__ (self,urls= ()): Self.urls = urls self.status = ' $ O K ' Def __call__ (self,environ,start_response): x = Self.mapping_urls (environ) print x start_respons E (self.status,self.headers) if Isinstance (X,STR): Return iter ([x]) Else:return iter (x  ) def mapping_urls (self,environ): Path = environ[' Path_info '] for pattern,name in self.urls:m                = Re.match (' ^ ' +pattern+ ' $ ', path) if M:args = M.groups () func = Globals () [name] return func (*args) return Self.notfound () def notfound (self): Self.status = ' 404 Not Found ' Self.headers = [(' Content-type ', ' Text/plain ')] return ' 404 Not found\n ' @classmethod def header (CLS,    Name,value): Cls.headers.append ((Name,value)) def get_index (*args): Wsgiapp.header (' Content-type ', ' Text/plain ') Return ' welcome!\n ' def Get_hello (*args): Wsgiapp.header (' Content-type ', ' Text/plain ') return ' Hello%s!\n '% argsurls = [('/', ' Get_inde X '), ('/hello/(. *) ', ' Get_hello ')]wsgiapp = Wsgiapp (urls) if __name__ = = ' __main__ ': from Wsgiref.simple_server im Port Make_server httpd = Make_server (", 8000,wsgiapp) print ' Server starting ... ' Httpd.serve_forever ()

The above code is not very brief, just need to define the function.

Python Learning-writing a simple web framework (i)

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.