flask学习
- virtualenv模块
- 解释,这个模块提供一个‘纯净的’python环境,保证了所安装的模块不受其他的影响,也就是想安装哪个版本就安装哪个版本。
- 创建一个独立的python运行环境
virtualenv --no-site-packages 环境名
- 进入该环境,
source 环境名/bin/activate
- 退出该环境,
deactivate
- 路由
-
route()
装饰器把一个函数绑定到对应的URL上
@app.route('/) def index(): return 'Index Page' @app.route('/hello') def hello(): return 'Hello World'
- 动态路由(路由含变量),变量字段用
<username>
这种形式
@app.route('/user/<username>') def show_user_profile(username): return 'User %s' % username @app.route('/post/<int:post_id>') #int指定类型,接受整数,也可以是float/path def show_post(post_id): return 'Post %d' % post_id
- 唯一url/重定向行为。
并没有看懂
- 构造url,
url_for()
函数可以给指定的函数构造url,接受函数名作为第一个参数,也接受对应URL规则的变量部分的命名参数(真够绕的),未知变量部分会添加到URL末位作为查询参数
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='Meng')
- HTTP方法,默认情况下,路由只回应GET请求,但是通过route()装饰器传递methods参数可以改变这个行为
@app.route('/login',methods=['GET','POST']) def login(): if request.method == 'POST': do_the_login() else: show_the_login_form()
-
- 静态文件
- 动态web应用需要静态文件,通常是CSS和javascript文件,通常放在static的文件夹中
url_for('static',filename='style.css')
- 模版渲染(jinja2),模板要放在templates文件夹下面
- 使用
render_template()
方法来渲染模版,需要做的就是将模板名和想作为关键字的参数传入模板的变量
form flask import render_template @app.route('hello/') @app.route('/hello/<name>') def hello(name=None): return render_template('hello.html',name=name)
- 使用
- 重定向和错误
-
redirect()
重新定向到其他地方
... return redirect(url_for('login))
-
abort()
放弃请求,并且返回错误代码
abort(404)
- 定制错误页面,
errorhandler()
装饰器
@app.errorhandler(404) def not_found(): return render_template('404.html')
-
网友评论