common logical view flask

 Return json

Flask using a write interface to return to the client when needed json data may be generated in response to a direct jsonfy json in the flask.

@app.route('/demo4')
def demo4():
    json_dict = {
        "user_id": 10,
        "user_name": "laowang"
    }
    return jsonify(json_dict)

  But there is a problem

 

 There would be an error. This error prompt a request of this kind is not is_xhr this property. This issue is not resolved. God saw big hope gets advice

So we got to here jsonfy this method does not work then we change ways

Is not return a json data it?

python json library is not there yet? The json.dump use of this library is used () to convert the data into a data structure of python json format

(The json.loads () and dumps the contrary)

Finally, the data is returned to the client through the return json format

Redirect

If we do site adjustments, such as changing the page directory structure

eg:

Redirection # 
@ app.route ( '/ demo5') 
DEF demo5 (): 
    return the redirect ( 'http://www.baidu.com')

  Redirected to Baidu

Of course, you can redirect to write your own view functions

  • You can point directly write your own path

  · Url_for may also be used to generate the function specified view corresponding to url

@app.route('/demo1')
def demo1():
    return 'demo1'

# 重定向
@app.route('/demo5')
def demo5():
    return redirect(url_for('demo1'))

  Or redirect them to view with parameters

# Routes pass parameters 
@ app.route ( '/ User / <int: user_id>') 
DEF USER_INFO (user_id): 
    return 'Hello% D' user_id% 

# redirect 
@ app.route ( '/ demo5') 
DEF demo5 ( ): 
    # url_for generated using the specified view url function corresponding 
    return redirect (url_for ( 'user_info' , user_id = 100))

  This is of course still need to pass parameters, the error will not pass Oh

Custom status codes

In the flask can easily return a custom status codes, in order to achieve the status code does not comply with the http protocol

app.route @ ( '/ demo6') 
DEF demo6 (): 
    return 'status code 666', 666

  Status code may be above BHC

 

Guess you like

Origin www.cnblogs.com/Jamsha/p/12458991.html