flask初探

来源:互联网 发布:淘宝千牛是什么 编辑:程序博客网 时间:2024/05/17 04:40

一个最小的应用

from flask import Flaskapp = Flask(__name__)@app.route('/')def hello_world():    return 'hello world'if __name__ == '__main__':    app.run()

保存为hello.py,打开命令行输入:

python hello.py

然后浏览器访问:http://127.0.0.1:5000/,会看到 hello world。

调试模式

两个启用方法:

app.debug = Trueapp.run()
app.run(debug=True)

路由

在开始的应用中,route()把一个函数绑定到对应的URL上。

@app.route('/')def index():    return 'Index Page'@app.route('/hello')def hello():    return 'hello world'

变量规则

如果想要给URL添加变量,可以把这些特殊的字段标记为

@app.route('/user/<username>')def show_user_profile(username):    # show the user profile for that user    return 'User %s' % username@app.route('/post/<int:post_id>')def show_post(post_id):    # show the post with the given id, the id is an integer    return 'Post %d' % post_id

构造url

可以用 url_for() 来给指定的函数构造 URL。它接受函数名作为第一个参数,也接受对应 URL 规则的变量部分的命名参数。未知变量部分会添加到 URL 末尾作为查询参数。

from flask import Flask, url_forapp = Flask(__name__)@app.route('/')    def index(): pass@app.route('/login')def login():pass@app.route('/user/<username>')def profile(username):passwith app.test_request_context():    print(url_for('index'))    print(url_for('login'))    print(url_for('login',next='/'))    print(url_for('index',username='John'))
//login/login?next=//user/John%20Doe

login中是没有参数的,所以 next 是未知变量,用‘?’连接。

http方法

HTTP (与 Web 应用会话的协议)有许多不同的访问 URL 方法。默认情况下,路由只回应 GET 请求,但是通过 route() 装饰器传递 methods 参数可以改变这个行为。GET,POST通常通过html里的表单来提交。
比如html中创建一个表单:

<form action="/hello" method='post'>    <input type="text" value="" name="val">    <input type="submit" value="提交" id="submit"></form>

点击提交键后,会向路由发起一个POST请求。在后端获取请求值,并打印出来。

@app.route('/hello', methods=['GET', 'POST'])def show():    if request.method == 'POST':        val = request.form['val']        return val    else:        return 'hello world'

静态文件

url_for('static', filename='style.css')

这个文件应该存储在文件系统上的 static/style.css。

模板渲染

Flask配备了Jinja2模板引擎,可以使用render_template() 方法来渲染模板。

from flask import render_template@app.route('/hello/')@app.route('/hello/<name>')def hello(name=None):    return render_template('hello.html', name=name)

hello.html里使用模板的一个小实例。

<!doctype html><title>Hello from Flask</title>{% if name %}  <h1>Hello {{ name }}!</h1>{% else %}  <h1>Hello World!</h1>{% endif %}

[1] http://docs.jinkan.org/docs/flask/quickstart.html#a-minimal-application flask中文文档

原创粉丝点击