A brief introduction to some of the main points of Python's own authoring web framework

Source: Internet
Author: User
Tags set cookie
Before we formally start web development, we need to write a web framework.

Why not choose an out-of-the-box web framework and develop it from scratch? Let's take a look at the existing popular web framework:

    • Django: One-stop development framework, but not conducive to customization;
    • web.py: Use classes instead of simpler functions to process URLs, and URL mappings are configured separately;
    • Flask: URL routing with @decorator is good, but the framework is too strong for code intrusion from the application;
    • Bottle: The lack of interception based on URL mode is not conducive to permission checking.

Therefore, we combine the advantages of several frameworks to design a simple, flexible, and highly invasive web framework.
Designing a Web Framework

A simple URL framework should allow the URL to be mapped directly to the function in a @decorator way:

# Home: @get ('/') def index ():  return '

Index page

' # URL with parameters: @get ('/user/:id ') def show_user (ID): user = User.get (ID) return ' Hello,%s '% User.Name

There is no @decorator does not change the function behavior, that is, the Web Framework API intrusion is very small, you can directly test the function Show_user (ID) without the need to start the Web server.

Functions can return STR, Unicode, and iterator, which can be returned directly to the browser as a string.

Second, the Web framework supports URL interceptors so that we can do permission checks based on the URL:

@interceptor ('/manage/') def check_manage_url (next):  if Current_user.isadmin ():    return Next ()  else:    Raise Seeother ('/signin ')

The interceptor accepts a next function so that an interceptor can decide whether to call next () to continue processing the request or to return directly.

Support templates are required to support the Mvc,web framework, but we do not qualify which template to use, you can choose JINJA2, or you can choose Mako, Cheetah, and so on.

To unify the interface of a template, the function can return dict and match @view to render the template:

@view (' index.html ') @get ('/') def index ():  return Dict (Blogs=get_recent_blogs (), User=get_current_user ())

If you need to get user input data from form form or URL querystring, you need to access the request object, and if you want to set a specific content-type, set a cookie, etc., you need to access the response object. The request and response objects should be obtained from a unique threadlocal:

@get ('/test ') def test ():  input_data = Ctx.request.input ()  ctx.response.content_type = ' Text/plain '  Ctx.response.set_cookie (' name ', ' value ', expires=3600)  return ' result '

Finally, if you need to redirect, or return an HTTP error code, the best way is to throw the exception directly, for example, redirect to the landing page:

Raise Seeother ('/signin ')

Return 404 Error:

Raise NotFound ()

Based on the above interface, we can implement the web framework.
Implementing the Web Framework

Some of the most basic objects are as follows:

# transwarp/web.py# Global Threadlocal object: CTX = threading.local () # HTTP Error class: Class Httperror (Exception): pass# Request object: Class Request (object): # returns VALUE:DEF get (self, key, default=none) according to key: Pass # returns Key-value Dict:def input (self): pas S # return URL path: @property def path_info (self): Pass # returns HTTP Headers: @property def Headers (self): Pass # according to K EY returns cookie Value:def cookie (self, Name, Default=none): pass# Response Object: Class Response (object): # setting Header:def Set    _header (self, Key, value): Pass # Set Cookie:def Set_cookie (self, name, value, Max_age=none, Expires=none, path= '/'): Pass # Set Status: @property def status: Pass @status. Setter def status (self, value): pass# definition get:def ge T (path): pass# definition Post:def post (path): pass# definition Template: Def view (path): pass# definition Interceptor: Def interceptor (pattern): pass# definition template engine: CL Templateengine (object): Def __call__ (self, Path, model): Pass# uses Jinja2:class jinja2templateengine by default (templateengin E): Def __init__ (self, TEMpl_dir, **kw): From JINJA2 import environment, Filesystemloader self._env = Environment (Loader=filesystemloader (TEM Pl_dir), **kw) def __call__ (self, Path, model): Return self._env.get_template (Path). Render (**model). Encode (' Utf-8 ')

Filling out the above definition, we have only one thing left: Define the global Wsgiapplication class, implement the Wsgi interface, and then, with the configuration started, complete the work of the entire web framework.

The design wsgiapplication should fully consider the distinction between the development mode (development mode) and the product model (Production mode). In the product mode, Wsgiapplication needs to provide the Wsgi interface directly to the server, let the server call the interface, and in the development mode, we would like to be able to directly start the server through the App.run () development debugging:

Wsgi = Wsgiapplication () if __name__ = = ' __main__ ':  wsgi.run () Else:  application = Wsgi.get_wsgi_application () Therefore, wsgiapplication is defined as follows: Class Wsgiapplication (object):  def __init__ (self, Document_root=none, **kw):    Pass  # Add a URL definition:  def add_url (Self, func):    pass  # Add a Interceptor definition:  def add_interceptor (self, func) :    Pass  # set Templateengine:  @property  def template_engine (self):    pass  @template_ Engine.setter  def template_engine (self, Engine):    pass  # returns WSGI handler:  def get_wsgi_application ( Self):    def wsgi (env, start_response):      pass    return wsgi  # Direct Start Server in development mode:  def run (self, port= 9000, host= ' 127.0.0.1 '): From    wsgiref.simple_server import make_server    server = Make_server (host, Port, Self.get_wsgi_application ())    server.serve_forever () Try

By filling out the Wsgiapplication class, we get a complete web framework.

  • 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.