您的位置:首页 > 其它

Flask 框架入门

2017-09-18 00:00 288 查看

快速开始

hello.py

from flask import Flask
app = Flask(__name__)

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

配置应用名称

export FLASK_APP=hello.py

运行

flask run 或者 python -m flask run

开启 DEBUG模式

export FLASK_DEBUG=1


路由

普通路由

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

@app.route('/hello')
def hello():
return 'Hello, World'

命名路由(Variable Rules)

可以指定变量的名字并添加转换器

@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

备注:(转换器)

stringaccepts any text without a slash (the default)
intaccepts integers
floatlike
int
but for floating point values
pathlike the default but also accepts slashes
anymatches one of the items provided
uuidaccepts UUID strings
自定义路由:(url_for())

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

* Http 方法

from flask import request

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

静态资源路由(static files)

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


模板渲染

默认配置了 Jinja2 模板引擎,需要 render_template

from flask import Flask
from flask import render_template

app = Flask(__name__)

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

在当前目录创建一个 templates(默认)目录,该目录下创建文件 hello.html

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

* 将真实html转义

>>> from flask import Markup
>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'
Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')
>>> Markup.escape('<blink>hacker</blink>')
Markup(u'<blink>hacker</blink>')
>>> Markup('<em>Marked up</em> » HTML').striptags()
u'Marked up \xbb HTML'


访问请求数据

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: