Flask 框架入门
2017-09-18 00:00
288 查看
快速开始
hello.pyfrom 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
备注:(转换器)
string | accepts any text without a slash (the default) |
int | accepts integers |
float | like intbut for floating point values |
path | like the default but also accepts slashes |
any | matches one of the items provided |
uuid | accepts UUID strings |
>>> 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_templatefrom 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'
访问请求数据
相关文章推荐
- Flask框架从入门到实战
- Python Web框架Flask下网站开发入门实例
- python中Flask框架简单入门实例
- Python Web 框架 Flask 入门示例
- [python]flask框架快速入门
- Flask微型框架入门笔记
- Python Web框架Flask下网站开发入门实例
- flask框架实战—简单图片社交网站(一):Python语言快速入门
- Flask微型框架入门笔记
- Flask 框架入门
- Python web 框架 Flask 入门 macOS 下实践记录
- Flask---框架快速入门
- Python的Flask框架中Flask-Admin库的简单入门指引
- 在Python的Flask框架中使用模版的入门教程
- Python的Flask框架入门-Ubuntu
- Flask框架——快速入门
- 框架 day70 Lucene全文检索技术入门
- Shiro权限控制框架入门1:Shiro的认证流程以及基本概念介绍
- VS2010/MFC编程入门之一(利用MFC向导生成单文档应用程序框架)
- SubSnoic 框架入门到提高---全程记录