Pythonweb framework learning notes

Source: Internet
Author: User
This article mainly shares pythonweb framework learning notes. For more information, see I. Nature of web Framework

1. handle requests by yourself based on socket

#! /Usr/bin/env python3 # coding: utf8import socketdef handle_request (client): # receive request buf = client. recv (1024) print (buf) # return information client. send (bytes ('Welcome liuyao webserver', 'utf8') def main (): # create sock object sock = socket. socket () # Listen to port 80 sock. bind ('localhost', 8000) # maximum number of connections sock. listen (5) print ('Welcome nginx') # loop while True: # Wait for the user's connection. By default, accept is blocked. When a request is sent, the connection, address = sock is executed. accept () # hand over the connection to handle_request function handle_request (connection) # Close the connection. close () if _ name _ = '_ main _': main ()

2. wsgi-based

WSGI, short for Web Server Gateway Interface or Python Web Server Gateway Interface, is a simple and common Interface between the Web Server and Web application or framework defined for the Python language. Since WSGI was developed, similar interfaces have also appeared in many other languages.

The official definition of WSGI is the Python Web Server Gateway Interface. It can be seen from the name that this is a Gateway, that is, a Gateway. The gateway is used to convert between protocols.

WSGI is a low-level interface between a Web server and a Web application or application framework, to improve the commonality of Web application development that can be transplanted. WSGI is designed based on the existing CGI standards.

Many frameworks have built-in WSGI servers, such as Flask, webpy, Django, and CherryPy. Of course, the performance is not good. The built-in web server is mostly for testing purposes. During the release, the WSGI server in the production environment or the uwsgi with nginx is used.

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

#! /Usr/bin/env python # coding: UTF-8 # import wsgi module from wsgiref. simple_server import make_serverdef RunServer (environ, start_response): start_response ('2014, 200 OK ', [('content-type', 'text/html')]) return [bytes ("welcome webserver ". encode ('utf8')] if _ name _ = '_ main _': httpd = make_server ('', 8000, RunServer) print ("Serving HTTP on port 8000... ") httpd. serve_forever () # receiving requests # preprocessing requests (encapsulated with many http requests)

After the request comes, run the RunServer function.

Schematic:

When a user sends a request, the socket sends the request to the function for processing, and then returns it to the user.

Ii. custom web framework

Develop a Web framework based on the wsgiref module provided by the python standard library

Previously, only one url can be accessed using wsgiref.
The following url requests can be processed and returned to the user

#! /Usr/bin/env python # coding: utf-8from wsgiref. simple_server import make_serverdef RunServer (environ, start_response): start_response ('000000', [('content-type', 'text/html ')]) # depending on the url, returns a different string #1 get the URL [where to get the URL? When the request comes, run RunServer. # wsgi encapsulates these requests to us. These requests are encapsulated. environ & start_response] request_url = environ ['path _ info'] print (request_url) #2 depending on the URL # print environ # Here we can use breakpoints to check what data it encapsulates if request_url = '/login ': return [bytes ("welcome login", 'utf8')] elif request_url = '/reg': return [bytes ("welcome reg", 'utf8')] else: return [bytes ('2017! No found ', 'utf8')] if _ name _ =' _ main _ ': httpd = make_server ('', 8000, RunServer) print ("Serving HTTP on port 8000... ") httpd. serve_forever ()

Of course, although the above process is based on different URLs, if there are a large number of URLs, the code will be cumbersome to write.
So use the following method for processing

#! /Usr/bin/env python # coding: utf-8from wsgiref. simple_server import make_serverdef index (): return [bytes ('index', 'utf8')] def login (): return [bytes ('login', 'utf8')] def reg (): return [bytes ('reg ', 'utf8')] def layout (): return [bytes ('layout', 'utf8')] # define a list to make the url and the above function correspond to urllist = [('/Index', index), ('/login', login), ('/reg ', reg), ('/layout', layout),] def RunServer (environ, start_response): start_res Ponse ('200 OK ', [('content-type', 'text/html')]) # depending on the url, returns a different string #1 get the URL [where to get the URL? When the request comes over and runs RunServer, wsgi encapsulates these requests to us. All these requests are encapsulated. environ & start_response] request_url = environ ['path _ info'] print (request_url) #2 depending on the URL # print environ # Here we can use the breakpoint to view what data it encapsulates # loop through this list to find the function for the url you opened and return the url in urllist: if request_url = url [0]: return url [1] () else: # No 404 return [bytes ('2017 not found ', 'utf8')] if _ name _ = '_ main _': httpd = make_server ('', 8000, RunServer) print ("Serving HTTP on port 8000... ") httpd. serve_forever ()

Iii. template engine
The preceding operations return a string to the user based on the url accessed by the user, for example, return xxx.

Case:

First write an index.html page

Content:

 indexwelcome index

Login.html page

Content:

 
  login welcome login 

Python code:

#! /Usr/bin/env python # coding: utf-8from wsgiref. simple_server import make_serverdef index (): # Read the index page and return it to indexfile = open('index.html ', 'r + '). read () return [bytes (indexfile, 'utf8')] def login (): loginfile = open('login.html ', 'r + '). read () return [bytes (loginfile, 'utf8')] urllist = [('/login', login), ('/Index', index),] def RunServer (environ, start_response): start_response ('2017 OK ', [('content-type' , 'Text/html')]) # Return different strings based on different URLs #1. Obtain the url [where to obtain the URL? When the request comes over and runs RunServer, wsgi encapsulates these requests to us. All these requests are encapsulated. environ & start_response] request_url = environ ['path _ info'] print (request_url) #2 depending on the URL # print environ # Here we can use breakpoints to check what data it encapsulates for url in urllist: # if the url requested by the user matches the defined rul, if request_url = url [0]: # execute return url [1] () else: #404 return [bytes ('1970 not found', 'utf8')] if _ name _ = '_ main _' is not returned in the url_list __': httpd = make_server ('', 8000, RunServer) print (" Serving HTTP on port 8000... ") httpd. serve_forever ()

But the above content can only be returned to static content, not dynamic content
So how to return dynamic content?

Customize a set of special syntaxes and replace them

Use the open-source tool jinja2 and follow its specified syntax

Index.html follows the jinja syntax for replacement, loop, and judgment.

First, display the approximate effect. The specific jinja2 will be described in detail in chapter django notes.

Index.html page

Content:

 
  Title 
  {{ name }} {{ age }} {{ time }} 
  
 
    {% for item in user_list %}
  • {{ item }}
  • {% endfor %}
{% if num == 1 %} num == 1 {% else %} num == 2 {% endif %}

Python code:

#! /Usr/bin/env python #-*-coding: UTF-8-*-import time # import the wsgi module from wsgiref. simple_server import make_server # import the jinja module from jinja2 import Templatedef index (): Unlock to open index.html data = open('index.html '). read () # Use jinja2 to render template = Template (data) result = template. render (name = 'yunaoyunao', age = '18', time = str (time. time (), user_list = ['linux ', 'python', 'bootstarp'], num = 1) # Why is jinja used for replacement, because it is not just text It also supports the if judgment & for loop operation # note that the default unicode encoding is set to UTF-8 return [bytes (result, 'utf8')] urllist = [('/Index', index),] def RunServer (environ, start_response): start_response ('2014, 200 OK', [('content-type ', 'text/html')]) # Return different strings based on different URLs #1. Obtain the url [Where can I obtain the URL? When the request comes, run RunServer. # wsgi encapsulates these requests to us. These requests are encapsulated. environ & start_response] request_url = environ ['path _ info'] print (request_url) #2 perform different operations based on the URL # loop this list for url in urllist: # if the url requested by the user matches the rul defined by us if request_url = url [0]: print (url) return url [1] () else: #404 return [bytes ('2017 not found', 'utf8')] is not returned in the urllist list. if _ name _ = '_ main _': httpd = make_server ('', 8000, RunServer) print (" Serving HTTP on port 8000... ") httpd. serve_forever ()

Iv. MVC and MTV

1. MVC

The full name is Model View Controller, short for model-view-controller. It is a Model of software design, organize Code by means of separation of business logic, data, and interface display, and integrate the business logic into a component to improve and personalize the custom interface and user interaction, you do not need to rewrite the business logic. MVC is uniquely developed to map traditional input, processing, and output functions in a logical graphical user interface structure.

Add the routing rule to urls. py

Operate the func function in the controller of urls.

Operate the database in db. py in the model.

Add html pages to views

Schematic:

2. MTV

Models handles DB operations

Templates html Template

Views process function requests

Schematic:

The above is all the content of this article, hoping to help you learn.

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.