首页 > 代码库 > Flask之 路由(routing)
Flask之 路由(routing)
# -*- coding:utf-8 -*-from flask import Flask#创建一个flask应用对象app = Flask(__name__)app.debug = True#使用 route()装饰器告诉flask哪个url触发哪个函数@app.route(‘/‘)def hello_world(): return ‘Index page‘#route()装饰器绑定了一个函数hello()到一个URL "/hello"@app.route(‘/hello‘)def hello(): return ‘Hello world‘if __name__ == ‘__main__‘: app.run()
静态文件:
Static Files
Dynamic web applications also need static files. That’s usually where the CSS and JavaScript files are coming from. Ideally your web server is configured to serve them for you, but during development Flask can do that as well. Just create a folder called static in your package or next to your module and it will be available at /static on the application.
To generate URLs for static files, use the special ‘static‘ endpoint name:
url_for(‘static‘, filename=‘style.css‘)
The file has to be stored on the filesystem as static/style.css.
变量规则:
我们可以通过<variable_name>来在我们的url上添加一个变量。比如我们的函数的变量,我们也可以使用转换器来要我们指定的类型值<converter:variable_name>,例如<int:post_id>
# 这里我们接受一个username变量,http://127.0.0.1:5000/user/xxx@app.route(‘/user/<username>‘)def show_user_profile(username): #显示指定用户的信息 return ‘User %s‘ % username# http://127.0.0.1:5000/post/xx(为int的数字)@app.route(‘/post/<int:post_id>‘)def show_post(post_id): #显示指定id的文章内容 return ‘Post %d‘ % post_id
The following converters exist:
int | accepts integers |
float | like int but for floating point values |
path | like the default but also accepts slashes |
Url小提示:
版本一#route()装饰器绑定了另外一个URL@app.route(‘/hello‘)def hello(): return ‘Hello world‘#当我们访问http://127.0.0.1:5000/hello/会出错#版本二#route()装饰器绑定了另外一个URL@app.route(‘/hello/‘)def hello(): return ‘Hello world‘#当我们访问http://127.0.0.1:5000/hello 会转到 http://127.0.0.1:5000/hello/
HTTP方法
from flask import Flask, requestapp = Flask(__name__)app.debug=True@app.route(‘/login‘, methods=[‘GET‘, ‘POST‘])def login(): if request.method == ‘GET‘: return ‘GET‘ else: return ‘POST‘
Flask之 路由(routing)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。