Web framework essence, web Framework

Source: Internet
Author: User

Web framework essence, web Framework
Web framework nature

As we all know, all Web applications are essentially a socket server, and your browser is actually a socket Client.

#!/usr/bin/env python#coding:utf-8  import socket  def handle_request(client):    buf = client.recv(1024)    client.send("HTTP/1.1 200 OK\r\n\r\n")    client.send("Hello, Seven")  def main():    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)    sock.bind(('localhost',8000))    sock.listen(5)      while True:        connection, address = sock.accept()        handle_request(connection)        connection.close()  if __name__ == '__main__':    main()

 

The above uses socket to realize its essence. For python web programs in real development, it is generally divided into two parts: server programs and applications. The server program encapsulates the socket server and sorts the request data when the request arrives. The application is responsible for specific logic processing. To facilitate application development, many Web frameworks have emerged, such as Django, Flask, and web. py. Different frameworks have different development methods, but in any case, developed applications must work with server programs to provide services for users. In this way, the server program needs to provide different support for different frameworks. This chaotic situation is not good for servers or frameworks. For servers, different frameworks must be supported. For the framework, only the servers that support it can be used by applications. At this time, standardization becomes particularly important. We can set up a standard. As long as the server program supports this standard and the framework also supports this standard, they can work together. Once the standards are determined, both parties shall implement each other. In this way, the server can support more standard frameworks, and more standard servers can be used in the framework.

WSGI (Web Server Gateway Interface) is a specification that defines the Interface formats between web apps and web servers written in python to achieve decoupling between web apps and web servers.

The independent WSGI server provided by the python standard library is called wsgiref.

#!/usr/bin/env python#coding:utf-8 from wsgiref.simple_server import make_server def RunServer(environ, start_response):    start_response('200 OK', [('Content-Type', 'text/html')])    return '

  

Custom Web Framework

I. Framework

Develop your own Web framework through the wsgiref module provided by the python standard library

#!/usr/bin/env python#coding:utf-8from wsgiref.simple_server import make_server def index():    return 'index' def login():    return 'login' def routers():         urlpatterns = (        ('/index/',index),        ('/login/',login),    )         return urlpatterns def RunServer(environ, start_response):    start_response('200 OK', [('Content-Type', 'text/html')])    url = environ['PATH_INFO']    urlpatterns = routers()    func = None    for item in urlpatterns:        if item[0] == url:            func = item[1]            break    if func:        return func()    else:        return '404 not found'     if __name__ == '__main__':    httpd = make_server('', 8000, RunServer)    print "Serving HTTP on port 8000..."    httpd.serve_forever()

  

2. template engine

In the previous step, all login and index are returned to the user's browser with a simple string. In actual Web requests, a complex string that complies with HTML rules is generally returned, therefore, we generally write the HTML that will be returned to the user in the specified file and then return it. For example:

<! DOCTYPE html> #!/usr/bin/env python# -*- coding:utf-8 -*- from wsgiref.simple_server import make_server def index(): # return 'index' f = open('index.html') data = f.read() return data def login(): # return 'login' f = open('login.html') data = f.read() return data def routers(): urlpatterns = ( ('/index/', index), ('/login/', login), ) return urlpatterns def run_server(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) url = environ['PATH_INFO'] urlpatterns = routers() func = None for item in urlpatterns: if item[0] == url: func = item[1] break if func: return func() else: return '404 not found' if __name__ == '__main__': httpd = make_server('', 8000, run_server) print "Serving HTTP on port 8000..." httpd.serve_forever()

  

Although the above Code can return HTML content to users for complex pages, there is still a problem: how to return dynamic content to users?

  • Customize a set of special syntaxes and replace them
  • Use the open-source tool jinja2 and follow its specified syntax
<! DOCTYPE html> #!/usr/bin/env python# -*- coding:utf-8 -*- from wsgiref.simple_server import make_serverfrom jinja2 import Template def index(): # return 'index' # template = Template('Hello {{ name }}!') # result = template.render(name='John Doe') f = open('index.html') result = f.read() template = Template(result) data = template.render(name='John Doe', user_list=['alex', 'eric']) return data.encode('utf-8') def login(): # return 'login' f = open('login.html') data = f.read() return data def routers(): urlpatterns = ( ('/index/', index), ('/login/', login), ) return urlpatterns def run_server(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) url = environ['PATH_INFO'] urlpatterns = routers() func = None for item in urlpatterns: if item[0] == url: func = item[1] break if func: return func() else: return '404 not found' if __name__ == '__main__': httpd = make_server('', 8000, run_server) print "Serving HTTP on port 8000..." httpd.serve_forever()

  

 

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.