路由
前言:
现在web技术,使用路由技术(route)将URL绑定到函数,这样可以直接访问指定URL页面,无需从主页导航开始。
一、@app.route():
@app.route('/hello') def hello_world(): return 'hello world'
hello_world加上装饰器@app.route('/hello')后,会将路径/hello绑定到hello_world,这个过程称为“注册”, hello_world()函数被
成为视图函数(view_func)
二、访问:
from flask import Flask app = Flask(__name__) @app.route('/hello') def hello_world(): return 'hello_world' if __name__ == '__main__': app.run(host='127.0.0.1', port='8001')
上面的示例中,在app.run中设置了host与port(主机与域名),访问http://127.0.0.1/test,结果如下:
hello_world
三、@app.route()装饰器与add_url_rule():
@app.route()装饰器的源码:
def route(self, rule, **options): def decorator(f): endpoint = options.pop("endpoint", None) self.add_url_rule(rule, endpoint, f, **options) return f return decorator
可以看到,装饰器的方式,其实也是调用了add_url_rule()这个方法。
注:关于endpoint这个参数,本人暂时还未清晰的了解。
@app.route()中,路径规则是必填的。
那么,我们可以自己手动调用add_url_rule来将url绑定到函数吗?当然是可以的。
from flask import Flask app = Flask(__name__) @app.route('/hello') def hello_world(): return 'hello_world' def say_hi(): return "say_hi" app.add_url_rule('/hi', view_func=say_hi) if __name__ == '__main__': app.run(host='127.0.0.1', port='8001')
方位127.0.0.1:8001/hi,可以看到返回 say_hi
add_url_rule(self,
rule: Any,
endpoint: Any = None,
view_func: Any = None,
provide_automatic_options: Any = None,
**options: Any) -> Any
):
rule: 函数对应的url规则,满足条件和app.route()的第一个参数一样,必须以'/'开始。
endpoint: 站点,使用url_for()进行反转的时,传入的第一个参数就是这个endpoint对应的值。这个值也可以不指定,那么默认就会使用函数的名字作为endpoint的值。
view_func: 视图函数名。
浙公网安备 33010602011771号