| 
 | 
 
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册  
 
x
 
Flask学习笔记3:请求调度  
 
        URL映射 
 
程序收到客户端的请求时,需要寻找对应的视图函数, 
 
这时候Flask就会使用URL映射来寻找,URL映射就是URL和视图函数的对应关系。 
 
Flask使用@app.route或者app.add_url_rule()生成映射。 
 
查看映射的方法 
 
 
- from flask import Flask
 
 - from time import sleep
 
 - app = Flask(__name__)
 
  
- @app.route('/')
 
 - def index():
 
 -     return "<h1> HELLO WORLD!</h1>"
 
  
- @app.route('/name/<name>')
 
 - def user(name):
 
 -     return "<h1>YOUR NAME IS %s</h1>" % name
 
  
- @app.route('/math/<int:shu1> <p> <int:shu2>')
 
 - def math(shu1, p, shu2):
 
 -     if p == '+':
 
 -         return "<h1>%d + %d = %d</h1>" % (shu1, shu2, shu1 + shu2)
 
 -     elif p == '-':
 
 -         return "<h1>%d - %d = %d</h1>" % (shu1, shu2, shu1 - shu2)
 
 -     elif p == '*':
 
 -         return "<h1>%d * %d = %d</h1>" % (shu1, shu2, shu1 * shu2)
 
  
- @app.route('/math/chu/<int:shu1> <int:shu2>')
 
 - def chu(shu1, shu2):
 
 -     if shu2 != 0:
 
 -         return "<h1>%d / %d = %.2f</h1>" % (shu1, shu2, shu1 / shu2)
 
  
- if __name__ == "__main__":
 
 -     app.run(debug=True)
 
  复制代码 
- >>> from hello import app
 
 - >>> app.url_map
 
 - Map([<Rule '/' (GET, HEAD, OPTIONS) -> index>,
 
 -  <Rule '/math/chu/<shu1> <shu2>' (GET, HEAD, OPTIONS) -> chu>,
 
 -  <Rule '/math/<shu1> <p> <shu2>' (GET, HEAD, OPTIONS) -> math>,
 
 -  <Rule '/static/<filename>' (GET, HEAD, OPTIONS) -> static>, # 用于操作静态文件,会在后面学到
 
 -  <Rule '/name/<name>' (GET, HEAD, OPTIONS) -> user>])
 
  复制代码 
 
可以看到,上面代码只要写了@app.route,url_map里面就会有相应的路径。 
 
这里面的GET,Head,Options是请求方法,由路由进行处理。 |   
 
 
 
 |