python的flask开发框架简单上手笔记

最简单的hello world

#!/usr/bin/env python
# encoding: utf-8
from flask import flask
app = flask(__name__)
@app.route(‘/’)
def index():
return ‘hello world’
if __name__ == ‘__main__’:
app.run(debug=true)
#app.run(host=’127.0.0.1′, port=8000)

之后,访问http://localhost:5000

支持post/get提交

@app.route(‘/’, methods=[‘get’, ‘post’])

多个url指向

@app.route(‘/’)
@app.route(‘/index’)

不管post/get使用统一的接收

from flask import request
args = request.args if request.method == ‘get’ else request.form
a = args.get(‘a’, ‘default’)

处理json请求
request的header中

“content-type”: “application/json”

处理时:

data = request.get_json(silent=false)

获取post提交中的checkbox

{%for page in pages %}

{%endfor%}
page_ids = request.form.getlist(“do_delete”)

使用url中的参数

@app.route(‘/query//’)
def query(qid):
pass

在request开始结束dosomething
一般可以处理数据库连接等等

from flask import g
app = …..
@app.before_request
def before_request():
g.session = create_session()
@app.teardown_request
def teardown_request(exception):
g.session.close()

注册jinja2模板中使用的过滤器

@app.template_filter(‘reverse’)
def reverse_filter(s):
return s[::-1]

或者

def reverse_filter(s):
return s[::-1]
app.jinja_env.filters[‘reverse’] = reverse_filter

可以这么用

def a():…
def b():…
fil = {‘a’: a, ‘b’:b}
app.jinja_env.filters.update(fil)

注册jinja2模板中使用的全局变量

jinja2_globals = {‘media_prefix’: ‘/media/’}
app.jinja_env.globals.update(jinja2_globals)

定义应用使用的template和static目录

app = flask(__name__, template_folder=settings.template_folder, static_folder = settings.static_path)

使用blueprint

from flask import blueprint
bp_test = blueprint(‘test’, __name__)
#bp_test = blueprint(‘test’, __name__, url_prefix=’/abc’)
@bp_test.route(‘/’)
——–
from xxx import bp_test
app = flask(__name__)
app.register_blueprint(bp_test)

实例:

bp_video = blueprint(‘video’, __name__, url_prefix=’/kw_news/video’)
@bp_video.route(‘/search/category/’, methods=[‘post’, ‘get’])
#注意这种情况下blueprint中url_prefix不能以 ‘/’ 结尾, 否则404

使用session
包装cookie实现的,没有session id

app.secret_key = ‘ps#yio`%_!((f_or(%)))s’

然后

from flask import session
session[‘somekey’] = 1
session.pop(‘logged_in’, none)
session.clear()
#过期时间,通过cookie实现的
from datetime import timedelta
session.permanent = true
app.permanent_session_lifetime = timedelta(minutes=5)

反向路由

from flask import url_for, render_template
@app.route(“/”)
def home():
login_uri = url_for(“login”, next=url_for(“home”))
return render_template(“home.html”, **locals())

上传文件

接收

f = request.files.get(‘upload’)
img_data = f.read()

直接返回某个文件

return send_file(settings.template_folder + ‘tweet/tweet_list.html’)

请求重定向

flask.redirect(location, code=302) the redirect status code. defaults to 302.supported codes are 301, 302, 303, 305, and 307. 300 is not supported.
@app.route(‘/’)
def hello():
return redirect(url_for(‘foo’))
@app.route(‘/foo’)
def foo():
return’hello foo!’

获取用户真实ip
从request.headers获取

real_ip = request.headers.get(‘x-real-ip’, request.remote_addr)
或者, 使用werkzeug的middleware 文档

from werkzeug.contrib.fixers import proxyfix
app.wsgi_app = proxyfix(app.wsgi_app)
return json & jsonp
import json
from flask import jsonify, response, json
data = [] # or others
return jsonify(ok=true, data=data)
jsonp_callback = request.args.get(‘callback’, ”)
if jsonp_callback:
return response(
“%s(%s);” % (jsonp_callback, json.dumps({‘ok’: true, ‘data’:data})),
mimetype=”text/javascript”
)
return ok_jsonify(data)

配置读取方法

# create our little application 🙂
app = flask(__name__)
# load default config and override config from an environment variable
app.config.update(dict(
database=’/tmp/flaskr.db’,
debug=true,
secret_key=’development key’,
username=’admin’,
password=’default’
))
app.config.from_envvar(‘flaskr_settings’, silent=true)
——————
# configuration
database = ‘/tmp/minitwit.db’
per_page = 30
debug = true
secret_key = ‘development key’
# create our little application 🙂
app = flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar(‘minitwit_settings’, silent=true)

几个不常用的方法

from flask import abort, flash
abort
if not session.get(‘logged_in’):
abort(401)
flash
flash(‘new entry was successfully posted’)

异步调用
想在flask的一个请求中处理异步, 除了使用消息系统, 可以用简单的线程处理

from threading import thread
def async(f):
def wrapper(*args, **kwargs):
thr = thread(target=f, args=args, kwargs=kwargs)
thr.start()
return wrapper
@async
def dosomething(call_args):
print call_args
in a request handler, call `dosomething`
error handler
@app.errorhandler(404)
def not_found_error(error):
return render_template(‘404.html’), 404
@app.errorhandler(500)
def internal_error(error):
db.session.rollback()
return render_template(‘500.html’), 500

项目配置
1.直接

app.config[‘host’]=’xxx.a.com’
print app.config.get(‘host’)

2.环境变量

export myappconfig=/path/to/settings.cfg
app.config.from_envvar(‘myappconfig’)

3.对象

class config(object):
debug = false
testing = false
database_uri = ‘sqlite://:memory:’
class productionconfig(config):
database_uri = ‘mysql://user@localhost/foo’
app.config.from_object(productionconfig)
print app.config.get(‘database_uri’) # mysql://user@localhost/foo

4.文件

# default_config.py
host = ‘localhost’
port = 5000
debug = true
app.config.from_pyfile(‘default_config.py’)

eg. 一个create_app方法

from flask import flask, g
def create_app(debug=settings.debug):
app = flask(__name__,
template_folder=settings.template_folder,
static_folder=settings.static_folder)
app.register_blueprint(bp_test)
app.jinja_env.globals.update(jinja2_globals)
app.jinja_env.filters.update(jinja2_filters)
app.secret_key = ‘po+_)(*&678ouijkko#%_!(((%)))’
@app.before_request
def before_request():
g.xxx = … #do some thing
@app.teardown_request
def teardown_request(exception):
g.xxx = … #do some thing
return app
app = create_app(settings.debug)
host=settings.server_ip
port=settings.server_port
app.run(host=host, port=port)
change log:
2013-09-09 create
2014-10-25 update

Posted in 未分类

发表评论