flask入门

安装

pip install flask

入门

最小的应用会是这样css

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()

把它保存为 hello.py (或是相似的),而后用 Python 解释器来运行。 确保你的应用文件名不是 flask.py ,由于这将与 Flask 自己冲突html

启动

$ python hello.py
 * Running on http://127.0.0.1:5000/

如今访问 http://127.0.0.1:5000/ ,你会看见 Hello World 问候。python

关闭

欲关闭服务器,按 Ctrl+C。flask

外部可访问的服务器

能够简单修改调用 run() 的方法使你的服务器公开可用,以下:api

app.run(host='0.0.0.0')

这会让操做系统监听全部公网 IP。

调试模式

虽然 run() 方法适用于启动本地的开发服务器,可是你每次修改代码后都要手动重启它。这样并不够优雅,并且 Flask 能够作到更好。若是你启用了调试支持,服务器会在代码修改后自动从新载入,并在发生错误时提供一个至关有用的调试器。注意:此操做仅限于开发模式,毫不能用于生产环境浏览器

有两种途径来启用调试模式。一种是直接在应用对象上设置:bash

app.debug = True
app.run()

另外一种是做为 run 方法的一个参数传入:服务器

app.run(debug=True)

两种方法的效果彻底相同。app

路由

构建路由有两种方式:函数

1. 使用@app.route()装饰器把一个函数绑定到对应的URL上

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

@app.route('/hello')
@app.route('/hello_two') # 能够定义多个URL到同一个视图函数上,Flask支持
def hello():
    return 'Hello World'

2. 经过 app.add_url_rule,使用格式为

add_url_rule(self, rule, endpoint=None, view_func=None, **options)

rule: url 规则字符串,能够是静态的 /path,也能够包含 /
endpoint:要注册规则的 endpoint,默认是 view_func 的名字,注意这里endpoint是不能重复的
view_func:对应 url 的处理函数,也被称为视图函数

示例以下:

def index():
    return 'Index Page'

def hello():
    return 'Hello World'

app.add_url_rule('/', 'index', index)
app.add_url_rule('/hello', 'hello', hello)

路由中变量

要给 URL 添加变量部分,你能够把这些特殊的字段标记为 <variable_name> , 这个部分将会做为命名参数传递到你的函数。规则能够用 <converter:variable_name> 指定一个可选的转换器。

@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

转换器converter有如下几种

int 接受整数
float 同 int ,可是接受浮点数
path 和默认的类似,但也接受斜线

惟一URL/重定向行为

Flask 的 URL 规则基于 Werkzeug 的路由模块。这个模块背后的思想是基于 Apache 以及更早的 HTTP 服务器主张的先例,保证优雅且惟一的 URL。

以这两个规则为例:

@app.route('/projects/')
def projects():
    return 'The project page'

@app.route('/about')
def about():
    return 'The about page'

虽然它们看起来着实类似,但它们结尾斜线的使用在 URL 定义 中不一样。 第一种状况中,指向 projects 的规范 URL 尾端有一个斜线。这种感受很像在文件系统中的文件夹。访问一个结尾不带斜线的 URL 会被 Flask 重定向到带斜线的规范 URL 去

如:

http://127.0.0.1:5000/projects 会被重定向到 http://127.0.0.1:5000/projects/

然而,第二种状况的 URL 结尾不带斜线,相似 UNIX-like 系统下的文件的路径名。访问结尾带斜线的 URL 会产生一个 404 “Not Found” 错误

如:

这个行为使得在遗忘尾斜线时,容许关联的 URL 接任工做,与 Apache 和其它的服务器的行为并没有二异。此外,也保证了 URL 的惟一,有助于避免搜索引擎索引同一个页面两次。

url_for/构造URL

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

from flask import Flask, url_for
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

@app.route('/user/<username>')
def show_user_profile(username):
    # show the user profile for that user
    return 'User %s' % username

@app.route('/projects/')
def projects():
    return 'The project page'

@app.route('/about')
def about():
    print(url_for('hello_world'))
    print(url_for('projects'))
    print(url_for('projects', next='/'))
    print(url_for('show_user_profile', username='zzq'))
    return 'The about page'


if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)

访问http://127.0.0.1:5000/about,输出

/
/projects/
/projects/?next=%2F
/user/z%20q

它能正确转义字符,相对路径等

HTTP方法

默认状况下,路由只回应 GET 请求,可是经过 route() 装饰器传递 methods 参数能够改变这个行为

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        do_the_login()
    else:
        show_the_login_form()

静态文件

只要在你的包中或是模块的所在目录中建立一个名为 static 的文件夹,在应用中使用 /static 便可访问。

如:static文件夹下有style.css, 那么访问路径: http://127.0.0.1:5000/static/style.css

注意:给静态文件生成 URL ,使用特殊的 'static' 端点名:

url_for('static', filename='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 %}

Flask 会在 templates 文件夹里寻找模板。因此,若是你的应用是个模块,这个文件夹应该与模块同级;若是它是一个包,那么这个文件夹做为包的子目录

状况 1: 模块:

/application.py
/templates
    /hello.html

状况 2: 包:

/application
    /__init__.py
    /templates
        /hello.html

自动转义功能默认是开启的,因此若是 name 包含 HTML ,它将会被自动转义。

有时咱们返回的有html标签,须要浏览器解析,这时就不须要转义。经过 |safe 处理

 

附:

flask官方文档

相关文章
相关标签/搜索