flask framework (five) - Support for regular wording, template usage, request response, session

If you use regular words, we use a custom route.

Werkzeug.routing introduction from Import BaseConverter 
2 I have to write a class, then inherit BaseConverter, then implement __init__, to_python (self, value) , to_url (self, value) of these three methods
 . 3 app.url_map.converters [ ' just write ' ] = RegexConverter
 . 4 we app.route route inside @ ( ' / index / <regex1 ( "\ D +"): NID> ' ), is just write regex1, regex1 ( " regular expressions " )
 . 5 regex1 ( the results "regular expression") out of the match, returns to_python, be sure to return (the parameter view can receive to_python function return value)
 6 when we do the reverse analysis of the resolution when passed as a parameter, will be passed to to_url the result is a mosaic of return to our route

Code Example:

from the Flask Import the Flask, url_for
 from werkzeug.routing Import BaseConverter
 
App = the Flask (IMPORT_NAME = __name__ ) 

class RegexConverter (BaseConverter):
     "" " 
    Custom URL match the regular expression 
    " "" 
    DEF  __init__ (Self, the Map, regex): 
        Super (RegexConverter, Self). the __init__ (Map) 
        self.regex = REGEX 

    DEF to_python (Self, value):
         "" " 
        transmitted after the routing, the matching success function to the view parameter NID
         " "" 
        # value fails to match the out The results 
        Print ( 'value' , Value, type (value))
         return  " asdasdasd "   # return value to the view function parameters

     DEF to_url (Self, value):
         "" " 
        reverse URL is generated using the url_for, parameters passed through the processing method, returns the value of the parameters for generating the URL
         "" " 
        Val = Super (RegexConverter, Self) .to_url (value)
         Print (Val)   #val value is passed nid
         return Val    # spliced into the path for the return value of
 
app. url_map.converters [ ' regex1 ' ] = RegexConverter 
@ app.route ( ' / index / <regex1 ( "\ D +"): NID> ' ,endpoint="sb")
def index(nid):
    print("nid",nid,type(nid))
    print(url_for('sb', nid='888'))  #/index/888
    return 'Index'

if __name__ == '__main__':
    app.run()

template

Template transfer parameters, loop variable, and identifies the language code is transmitted html

test1.py

 
 
= {The USERS 
. 1: { 'name': 'John Doe', 'age': 18, 'gender': ' M', 'text': "Road ten million"},
2: { 'name': 'Li four ',' age ': 28, ' gender ':' M ',' text ': "The first security"},
. 3: {' name ':' Wang Wu ',' age ': 18, ' gender ' : 'F', 'text': "irregular traffic"}
}
def func1(st,st1):
    return Markup(f"<h1>jsaon-gdx{st}{st1}</h1>")

@app.route('/list',methods=['GET'])
def list():
    info=USERS
    return render_template('list.html',info1=info,html="<h1>jsaon-gdx</h1>",html1=func1)

the list.html (Note: the parameter value is passed back info1, reception reception parameters have to write the INFO1)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
{% for k,v in info1.items() %}  #后台传递的info1参数
        <tr>
            <td>{{k}}</td>
            <td>{{v.name}}</td>
            <td>{{v['name']}}</td>
            <td>{{v.get('name')}}</td>
            <td><a href="the url_for {{( 'SB', NID = K)}} " > detail </a> </ TD> 
        </ TR> 
{ % endfor% }
 {{HTML | Safe}}   HTML statement # transferred, using | you can cancel safe escape from the string into the normal display html syntax 
{{HTML1 ( "-DSB", "- SB")}} # Markup use, html statements can be transmitted, and may pass parameters

 </ body> 
</ html>

Note: Mark equivalent to django of mark_safe

Also in html reverse analysis by url_for path, and to pass parameters (******)

 test.py

@app.route('/detail/<int:nid>',methods=['GET'],endpoint="sb")
def detail(nid):

    return "ok"

the list.html (set alias detail view function,)

<td> <a href= "{{ url_for('sb',nid=k) }}"> detail </a> </ TD>   # routing jumps, and k values to the nid

Request response

 from flask import Flask
    from flask import request
    from flask import render_template
    from flask import redirect
    from flask import make_response

    app = Flask(__name__)


    @app.route('/login.html', methods=['GET', "POST"])
    def login():

        # 请求相关信息
        # request.method  提交的方法
        #request.args get request mentioned data 
        # Request.Form POST requests submitted data 
        # data and get the sum request.values post submitted 
        # Cookie carried Request.Cookies client 
        # Request.Headers request header 
        # request.path not the domain name, the request path 
        # request.full_path no domain name, with parameters of the request path 
        # request.script_root   
        # request.url domain parameters with the request path 
        # request.base_url the domain name request path 
        # request.url_root domain 
        # request.host_url domain 
        # request.host 127.0.0.1:500 
        # request.FILES 
        # obj = request.FILES [ 'the_file_name'] 
        # obj.save('/var/www/uploads/' + secure_filename(f.filename))

        # 响应相关信息
        # return "字符串"
        # return render_template('html模板路径',**{})
        # return redirect('/index.html')
        #return jsonify({'k1':'v1'})

        # response = make_response(render_template('index.html'))
        # response是flask.wrappers.Response类型
        # response.delete_cookie('key')
        # response.set_cookie('key', 'value')
        # response.headers['X-Something'] = 'A value'
        # return response
        return "内容"

    if __name__ == '__main__':
        app.run()

session

cookie: the key is stored in the client 
session: stored in the client's key-value pair 
token: stored in the client to check through the algorithm

Before using the session key must set about

= the Flask App ( __name__ )
 app.secret_key = "askjdaksd "    # just write

In addition to the request object, there is a session object. It allows you to store user-specific information across requests. It is implemented on the basis of Cookies, Cookies and to carry out key signature, you need to set up a session to use a key. (App.session_interface Object)

This inside look at the source app.session_interface (******)
 stored session:
 . 1 calls save_session, our encrypted session val, reads the configuration file ['SESSION_COOKIE_NAME'] obtained key
2to the key 1, val stored in cookies take the session:


 . 1 makes the request inside the cookies, which acquires key, this key is ['SESSION_COOKIE_NAME'], the encrypted value is the value of
2 to decrypt the value

app.session_interface in save_session parameters (parameters set the cookie)

key, the key 
value = '' , the value of 
the max_age = None, cookie timeout continuation time required (in seconds) If the parameter is \ None``, the cookie to the browser will continue closes the 
Expires = None, timeout ( the requires the Expires IE, the SET IT SO IF hasn ' t been already). 
path = ' / ' , which entered into force Cookie path, / represents the root path, special: cookie root path can only be accessed any url of the page, the browser the cookie back to the page with the path to avoid other applications cookie will be passed to the site. 
domain domain = None, Cookie take effect You can use this parameter to construct a cross-site cookie. Such as, Domain = " .example.com " constructed cookie on these sites is readable following: www.example.com, www2.example.com and an.other.sub.domain.example.com. If this parameter is set to None, cookie can only be read by setting its sites 
Secure =False, the browser will be passed back and forth over HTTPS cookie 
HttpOnly = False only http protocol transmission, JavaScript can not be acquired (not absolute, can get to the bottom of capture may be covered)

session Source execution process

- save_seesion
     - time response, the value of the encrypted sequence of session enlarged into a cookie, to return to the browser
 - open_session
     - request, and takes a value from the cookie, reverse solution, generated session object, later view function sessoin directly on it.

Code Example:

from flask import Flask,session

app = Flask(__name__)
app.secret_key="askjdaksd"
app.config['SESSION_COOKIE_NAME']="dsb"

@app.route("/")
def index():
    session['jason']="gdx"
    return "ok"

@app.route("/index1")
def index1():
    print(session['jason'])
    return "ok1"

if __name__ == '__main__':
    app.run()

 

 

Guess you like

Origin www.cnblogs.com/wangcuican/p/11844342.html