☆ --- understand before learning Django ☆ Django wsgiref jinja2

 

 Introduced

Pure hand-line and web framework

Review software development framework: c / sb / s   

  cs client server client ------- server

  bs Browser Browser ------- server server

HTTP protocol: Hypertext Transfer Protocol provides for data transfer format between the browser and the server 

HTTP four characteristics 

   Based on a request-response 

   2 based on tcp / ip protocol operated on the application layer

   3 Stateless (after the user's browser can not save the state and had a session cookie)

   No connection 4 (immediately after the first request in response to a disconnection, no connection between the two links)

   Long connection websocket 

http request data format: 

    request the first line (the HTTP protocol version identification and request mode) 

    request header (a bunch of k, v key-value pairs)

     / r / the n-(which is also the focus of one line) 

    request body (carrying some sensitive identification information such as a password) 

format http response data: 

    response the first line (identified protocol version HTTP response status codes) 

    in response header (lot k, v key-value pairs)

     / R & lt / n-(which is also a line focus) 

    in response to the body ( returned to the browser page data are usually the response body html interface)
http protocol data format
Supplemental response status code: 
    a string of simple numbers to represent some complex state or message 
    1XX: the server has successfully received your data is being processed you can continue to submit additional data 
    2XX: the server you want a successful response data (the request was successful 200) 
    3XX: redirection (when the page you need to log in after a visit to visit you will find that the window will be automatically transferred to the login page 301  302 ) 
    4XX: request error (there is no resource request 404, the request is not legitimate does not comply with internal regulations will not permissions 403) 
    5XX: internal server error ( 500 ) 

  supplementary request method 
    1 .get request 
       towards the service side to resources (such as the browser window, enter www.baidu.com) 
    2 .post request 
       submitted data service towards the end (such as user login to submit your username and password) 

the URL of: a uniform resource locator (URL is vernacular)
And mode request response status codes http protocol

HTTP GET request format

HTTP response format:

 

Pure line and hand version of web frameworks

'' ' 
Request header row manner http requests version information 
b'GET / HTTP / 1.1 \ r \ n 
request key value kv body of 
the Host: 127.0.0.1:9527\r\n 
Connection: Keep-Alive \ R & lt \ n- 
Cache- Control: max-Age = 0 \ R & lt \ n- 
....... 

\ R & lt \ n-' 

request body   
....... 
' '' 
Import Socket 

our sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM ) 
sock.bind (( ' 127.0.0.1 ' , 8000 )) 
sock.listen () 

the while True: 
    Conn, addr = sock.accept () 
    Data = conn.recv (8096 )
     # a reply message in response to status line plus 
    conn.send (b "HTTP/1.1 200 OK\r\n\r\n")
    conn.send(b"OK")
    conn.close()

Type Conversion Tips

data = b'hello world'

data = str(data,encoding='utf-8')
print(data)

data = bytes(data,encoding='utf-8')
print(data)

By dividing the last user input path suffix

    = conn.recv Data (1024 ) 
    Data = STR (Data, encoding = ' UTF-. 8 ' )
     # Get suffix get committed data 
    # Print (Data) 
    current_path = data.split ( ' \ R & lt \ n- ' ) [0] .split ( '  ' ) [. 1 ]
     Print (current_path)

 Because too much trouble so some write socket module to help us encapsulate wsgiref module

# Import module simple simple 
from wsgiref.simple_server Import make_server 

DEF RUN (the env, Response):
     # the env is the envelope associated with the request 
    # Response response being associated with 

    Print (the env) # He is a large dictionary 

    Response ( ' 200 is the OK ' , []) 

    current_path = env.get ( ' the PATH_INFO ' ) # Get suffix 
    IF current_path == ' Login ' :
         return [B ' Login ' ]
     return [B' Of He LLO Baby ' ]   # when a client is connected to the run method is triggered 

IF  the __name__ == ' __main__ ' : 
    Server = make_server ( ' 127.0.0.1 ' , 8080 , run)
     # real-time monitoring, once a customer address 127.0.0.1 8080 terminal is connected automatically bracketed calling run 
    # Flask Flask hint automatic run is a class instance object brackets! 
    #   Host, Port, App, server_class = WSGIServer, handler_class = WSGIRequestHandler

 

 Different suffixes should have different functions but the function if too much we need a time to judge a lot of trouble we could write a dictionary set of tuples Ganso which put functions suffix and function uses a for loop to determine and execute the function in not there

    = FUNC None
     for url in URLs:
         # judged that the current is not within the tuple url 
        IF url [0] == current_path:
             # if it matches url suffix put on the name assigned to the corresponding function FUNC 
            FUNC = url [. 1 ]
             # Once the match should quit immediately for recycling to save resources 
            BREAK 
    # variable func afraid to make a judgment on him not match! 
    IF func: 
        RES = func ( env ) 
      
the else : RES = errors ( env ) return [res.encode ( ' UTF-8 ' )] after processing each function you do not need to encode

After wsgiref based modules and split into different files
add a feature to modify the code to just two places in

  1 correspondence relationship with the view of the routing function .urls.py URLs = >>> [( '/ index', index),]
  2 .views.py view function

Static and dynamic pages

    Static pages 
        data is written dead, the same years 
    of dynamic web page 
        data is not written death is dynamic access to 
        , such as:
             1. Real-time back-end to get the current time " delivery " to show the front page
             2. obtain data from the back-end database " pass " to show the front page 

    
    is passed to the front page    >>>     page rendering

templates written inside the html file

  Derivation: read the file and using the replace replacement symbols stored therein and returned to the client

  But now I want a dictionary can be placed inside html value through the dictionary we need jinja2 module

 

jinja2 
    PIP3 install jinja2 
    due flask is dependent on the framework of jinja2 so download flask frame module also comes with jinja2
     
    rendering template contains the template syntax 
    template --- html file template syntax (close to the python syntax) 
    front-end can also use the back end of some of the syntax operation of the rear end of the incoming data {} {} {} %%


<P> {{}} data </ P> <P> {{data [ ' username ' ]}} </ P> <P> {{data }} .password </ P> <P> {{data.get ( ' Hobby ' )}} </ P> { % for user_dict in user_list% } <TR> <TD> user_dict.id {{}} </ TD> <TD>{{user_dict.name}}</td> <TD>{{user_dict.password}}</td> </tr> {%endfor%}
from jinja2 import Template
def get_user(env):
    user_dict = {'username':'jason','password':'123','hobby':['read','game','running']}
    with open(r'templates/03 get_user.html','r',encoding='. 8-UTF ' ) AS F: 
        data = reached, f.read ()
     TEMP = Template (data) 
    RES = temp.render (data = user_dict)   # The user_dict front page is transmitted to the front page by the variable name can be acquired to the data dictionary 
    return RES

to sum up


1. homochiral line and web frame
1. The manually written code that socket
2. Manual data processing http

2. Based on the wsgiref module to help us deal scoket and http data
wsgiref module
when parsing 1. http request data dictionary to help you pack into a transmission give you easy operation of your data
2. Take the time response data and then automatically help you packaged as a way consistent with http protocol format and then returned to the front

3. package routing and view functions as well as all correspondence between the html file view function files used by all site templates in the folder
1.urls.py routing and view function a correspondence relationship
2.views.py view function (not only refers to the view function may be a function class)
3.templates template folders

4. Based on jinja2 achieve rendering template
rendering template
to generate good back-end data transfer in some way to use the front page (front page based on template syntax faster and easier to use back-end data transmission over)

Guess you like

Origin www.cnblogs.com/lddragon/p/11529577.html