本文将通过实例告诉你如何使用flaskapp.route()函数来定义python中的静态和动态路由。
1.Flask app.route函数概述
- 将URL绑定到相关的进程函数。
- 有两种调用route()函数的方式:静态路由和动态路由。
2.静态路由和动态路由
2.1 静态路由的例子
-
使用注释函数@app.route("/ xxx")来定义一个静态路由函数。
-
XXX是一个静态路径,如/index、/base,这个函数可以返回一个值、字符串、页面等。
-
下面是一些flask静态路由函数定义的例子。
# Import the flask module. from flask import Flask # Get the flask app object. app = Flask(__name__) # Use the app.route() function to define the static route, it will be called when client request the url /hello. # This function will return a string to client. @app.route('/hello') def hello_world(): return 'Hello World!!!' # This static route function will be invoked when client request the url /pro. # This function will return a web page login.html. @app.route('/pro') def index(): return render_template('login.html') # Run the flask application when run this python program, set debug mode to true. if __name__ == '__main__': app.run(debug = True)
2.2 动态路由示例
-
动态路由函数仍然由注释函数@app.route("/< XXX >")定义。
-
<XXX>是一个动态路径,我们可以用< >来传输动态URL。 -
下面是一个如何定义和使用flask动态路由的例子。
# Import the flask module. from flask import Flask # Create the flask application object. app = Flask(__name__) # Define a dynamic route function to process any request with the URL start with /hello-world/ ( for example: /hello-world/jerry ) @app.route('/hello-world/<name>') def hello_world_name(name): return 'Hello World %s!' % name # Run the flask application. if __name__ == '__main__': app.run(debug = True) -
然后当客户端请求URLHTTP:// localhost:8080/hello-world/Trump。
-
它将在返回的网页上显示文字Hello World Trump。
3.Flask app.route函数的其他参数。
3.1 app.route函数的方法参数。
-
@app.route()函数的methods参数是当前视图函数所支持的请求方法。
-
方法有两个值,分别是**"GET**"和 "POST",如果没有设置,默认值是"GET"。
-
方法参数值是不区分大小写的。
-
设置methods = ['get']表示请求函数支持GET方法。
-
设置methods**= ['post']表示请求函数支持POST**方法。
-
设置方法 = ['get','post']表示请求函数同时支持GET和POST方法。
-
下面是一个使用方法参数的例子。
# Define the flask static route funciton, this function support both the HTTP GET and POST request method. @app.route('/login', methods=['GET', 'POST']) def login(): # If the request method is GET, then show the login.html page to the client. if request.method == 'GET': return render_template('login.html') # If the request method is POST, then get username, password value posted from the client. elif request.method == 'POST': # Get client post username and password. username = request.form.get('username') pwd = request.form.get('pwd') # username and password is correct. if username == 'jerry' and pwd == '123456': # Set username value in session. session['username'] = username # Return login success text. return 'login successed 200 ok!' else: # If username and password is not correct. # Return login fail text. return 'login failed!!!'