flask-redirect

# coding=utf-8

from config import Config
from flask import Flask,jsonify,abort, redirect,url_for

app = Flask(__name__)
app.config.from_object(Config)
# Return json data
import json
@app.route('/json ')
def demo1():
    my_dict = {"name":"tiantian","age":"10"}
    # return json.dumps(my_dict)  
    return jsonify(my_dict)
# Return the status code, return it directly by return, you can Return the status code that does not conform to the http protocol, mainly to realize the data interaction between the front and back ends
@app.route('/status')
def demo2():
    return 'demo2:',405 #Enter
127.0.0.1 in the browser above:5000/status, demo2 appears on the page: You can see that the status code is 405 in the inspection source code
# Exception handling, abort, similar to the raise statement in python, the function is to handle exception information, only the status code that conforms to the http protocol can be thrown, abort As long as the exception is caught, the code behind does not execute
@app.route('/')
def demo3():
    abort(404)
    return 'demo2:'403

@custom error message errorhandler will capture the exception status code thrown by the abort function
@app.errorhandler(404)
def demo4(e):
    return 'page not found , please visit a certain page'

# Redirect, when the project directory or file changes, you need to use redirect www.360buy.com
# When the active page does not exist, it is not recommended to use redirect to direct to a specific url, It is recommended to use dynamic url
# Reverse parsing
@app.route('/redirect')
def demo5():
    return redirect('http://www.baidu.com')
# Above when entering 127.0.0.1 in the browser :5000/redirect The page jumps to Baidu
"""
Or write like this
@app.route('/redirect')
def demo5():
    a = 'http://www.baidu.com'
    return redirect(a)

" "" #Use

url_for, the accepted parameter is the view function name
@app.route('/')
def demo6():
    return redirect(url_for('demo5'))
# Above when you enter 127.0.0.1:5000 in the browser, the page can jump to Baidu, it is best to use url_for



if __name__=='__main__':

    app.run()

 

Create the same level file config.py in the same directory

class Config:
    DEBUG = True
 SECRET_KEY='b1IHqfGBJbdmANeA3Ch/kEjd1jVw7EWifvdPUC8CXyu1+KsAKXnh8boLtjpwAoIOCLM='

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326521889&siteId=291194637