Python learning, python

Source: Internet
Author: User

Python learning, python

Write a web framework by yourself. Because I am a newbie and I am not clear about some python built-in functions, I need some python and WSGI preparations before writing this article. This is a series of articles. This article only implements how to process URLs.

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

Prerequisites

The web framework mainly implements interaction between web servers and web applications. The underlying network protocols are mainly completed by web servers. For example, listening port and filling packet.

Python built-in functions _ iter _ and _ call _ and WSGI iterator

The iterator provides the class sequence interface for the class sequence object. That is to say, the class sequence object can be iterated like a series through the iterator. Simply put, it is to traverse objects. If you want the class to be iterated, you must implement _ iter _ and next ().

_ Call __

As long as the _ call _ method is implemented during class definition, the object of this class is callable, which can be used as a function. Here we only need to understand what is the _ call _ function, because it is required in the WSGI specification.

WSGI

About WSGI introduction can click http://webpython.codepoint.net, has a very detailed introduction. Here, I will only explain it. The WSGI interface is implemented with callable objects: a function, a method, or an callable instance. The following is an example with detailed Annotations:

# This is our application object. It could have any name,# except when using mod_wsgi where it must be "application"def application( # It accepts two arguments:      # environ points to a dictionary containing CGI like environment variables      # which is filled by the server for each received request from the client      environ,      # start_response is a callback function supplied by the server      # which will 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 = '200 OK'   # These are 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 be any iterable.   return [response_body]

Simply put, the results are returned Based on the received parameters.

Design web Framework

I have previously used django to write a very simple blog, which is currently on SAES and has not been updated for a long time. URL: http://3.mrzysv5.sinaapp.com. The most basic requirement of a web framework is to simplify the amount of user code. Therefore, in django, I only need to write the view, model, and url configuration files. The following is a function for processing views written when I use django:

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 need to do is to operate the database and return the corresponding resources. Therefore, the web framework I want to compile should encapsulate some underlying operations as much as possible and leave some available interfaces to users. According to my observations, the web Framework process is roughly as follows:

A wsgi base class mainly has the following functions:

  • Process the environ Parameter
  • Obtain the method or class name based on the url, and return
import reclass WSGIapp:    headers = []    def __init__(self,urls=()):        self.urls = urls        self.status = '200 OK'    def __call__(self,environ,start_response):        x = self.mapping_urls(environ)        print x        start_response(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_index'),    ('/hello/(.*)','GET_hello')    ]wsgiapp = WSGIapp(urls)if __name__ == '__main__':    from wsgiref.simple_server import 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.

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.