flask 使用的一些整理

资源

Flask 文档|英文expore flask快速教材flask-adminFlask-DebugToolbarFlask-LoginFlask-Cache|flask-sqlalchemyflask-securityFlask-makoFlask-GenshiWTForms

Flask Extensions


最简单的hello world

Python
#!/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)

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/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提交

Python
@app.route('/', methods=['GET', 'POST'])
1
@app.route('/', methods=['GET', 'POST'])

多个url指向

Python
@app.route('/')
@app.route('/index')
1
2
@app.route('/')
@app.route('/index')

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

Python
from flask import request
args = request.args if request.method == 'GET' else request.form
a = args.get('a', 'default')
1
2
3
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"
1
"Content-Type": "application/json"

处理时:

Python
data = request.get_json(silent=False)
1
data = request.get_json(silent=False)

获取post提交中的checkbox

 
{%for page in pages %}
<tr><td><input type=checkbox name=do_delete value="{{ page['id'] }}"></td><td>
{%endfor%}

page_ids = request.form.getlist("do_delete")

1
2
3
4
5
{%for page in pages %}
<tr><td><input type=checkbox name=do_delete value="{{ page['id'] }}"></td><td>
{%endfor%}
 
page_ids = request.form.getlist("do_delete")

使用url中的参数

 
@app.route('/query/<qid>/')
def query(qid):
pass
1
2
3
@app.route('/query/<qid>/')
def query(qid):
    pass

在request开始结束dosomething

一般可以处理数据库连接等等

Python
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()

1
2
3
4
5
6
7
8
9
10
11
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模板中使用的过滤器

Python
@app.template_filter('reverse')
def reverse_filter(s):
return s[::-1]
1
2
3
@app.template_filter('reverse')
def reverse_filter(s):
    return s[::-1]

或者

Python
def reverse_filter(s):
return s[::-1]
app.jinja_env.filters['reverse'] = reverse_filter
1
2
3
def reverse_filter(s):
    return s[::-1]
app.jinja_env.filters['reverse'] = reverse_filter

可以这么用

Python
def a():...
def b():...

FIL = {'a': a, 'b':b}
app.jinja_env.filters.update(FIL)

1
2
3
4
5
def a():...
def b():...
 
FIL = {'a': a, 'b':b}
app.jinja_env.filters.update(FIL)

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

Python
JINJA2_GLOBALS = {'MEDIA_PREFIX': '/media/'}
app.jinja_env.globals.update(JINJA2_GLOBALS)
1
2
JINJA2_GLOBALS = {'MEDIA_PREFIX': '/media/'}
app.jinja_env.globals.update(JINJA2_GLOBALS)

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

Python
app = Flask(__name__, template_folder=settings.TEMPLATE_FOLDER, static_folder = settings.STATIC_PATH)
1
app = Flask(__name__, template_folder=settings.TEMPLATE_FOLDER, static_folder = settings.STATIC_PATH)

使用Blueprint

Python
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)

1
2
3
4
5
6
7
8
9
10
11
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)

实例:

Python
bp_video = Blueprint('video', __name__, url_prefix='/kw_news/video')
@bp_video.route('/search/category/', methods=['POST', 'GET'])
#注意这种情况下Blueprint中url_prefix不能以 '/' 结尾, 否则404
1
2
3
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

Python
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)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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)

反向路由

Python
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())

1
2
3
4
5
6
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())

上传文件

 
<form action="/image/upload/" method="post" enctype="multipart/form-data">
<input type="file" name="upload" />
1
2
<form action="/image/upload/" method="post" enctype="multipart/form-data">
<input type="file" name="upload" />

接收

Python
f = request.files.get('upload')
img_data = f.read()
1
2
f = request.files.get('upload')
img_data = f.read()

直接返回某个文件

Python
return send_file(settings.TEMPLATE_FOLDER + 'tweet/tweet_list.html')
1
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.

Python
@app.route('/')
def hello():
return redirect(url_for('foo'))

@app.route('/foo')
def foo():
return'Hello Foo!'

1
2
3
4
5
6
7
@app.route('/')
def hello():
    return redirect(url_for('foo'))
 
@app.route('/foo')
def foo():
    return'Hello Foo!'

获取用户真实ip

从request.headers获取

Python
real_ip = request.headers.get('X-Real-Ip', request.remote_addr)
1
real_ip = request.headers.get('X-Real-Ip', request.remote_addr)

或者, 使用werkzeug的middleware 文档

Python
from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
1
2
from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)

return json & jsonp

Python
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)

1
2
3
4
5
6
7
8
9
10
11
12
13
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)

配置读取方法

Python
# 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)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 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)

几个不常用的方法

Python
from flask import abort, flash

abort
if not session.get('logged_in'):
abort(401)

flash
flash('New entry was successfully posted')

1
2
3
4
5
6
7
8
from flask import abort, flash
 
abort
if not session.get('logged_in'):
    abort(401)
 
flash
flash('New entry was successfully posted')

异步调用

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

Python
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`

1
2
3
4
5
6
7
8
9
10
11
12
13
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

Python
@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
2
3
4
5
6
7
8
@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.直接

Python
app.config['HOST']='xxx.a.com'
print app.config.get('HOST')
1
2
app.config['HOST']='xxx.a.com'
print app.config.get('HOST')

2.环境变量

Python
export MyAppConfig=/path/to/settings.cfg
app.config.from_envvar('MyAppConfig')
1
2
export MyAppConfig=/path/to/settings.cfg
app.config.from_envvar('MyAppConfig')

3.对象

Python
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

1
2
3
4
5
6
7
8
9
10
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.文件

Python
# default_config.py
HOST = 'localhost'
PORT = 5000
DEBUG = True

app.config.from_pyfile('default_config.py')

1
2
3
4
5
6
# default_config.py
HOST = 'localhost'
PORT = 5000
DEBUG = True
 
app.config.from_pyfile('default_config.py')

EG. 一个create_app方法

Python
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)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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)

python基础===flask使用整理(转)的更多相关文章

  1. python基础面试题整理---从零开始 每天十题(01)

    最近在弄flask的东西,好久没写博客的,感觉少了点什么,感觉被别人落下好多,可能渐渐的养成了写博客的习惯吧.也是自己想学的东西太多了(说白了就是基础太差了,只是know how,不能做到konw w ...

  2. python基础全部知识点整理,超级全(20万字+)

    目录 Python编程语言简介 https://www.cnblogs.com/hany-postq473111315/p/12256134.html Python环境搭建及中文编码 https:// ...

  3. Python基础面试题整理

    基础 Python中lambda是什么意思 Python中的pass是什么意思 作为解释型语言,Python如何运行 什么是Python的单元测试 在Python中unittest是什么 如何将数字转 ...

  4. python基础面试题整理---从零开始 每天十题(02)

    书接上回,我们继续来说说python的面试题,我在各个网站搜集了一些,我给予你们一个推荐的答案,你们可以组织成自己的语言来说出来,让我们更好的做到面向工资编程 一.Q:说说你对zen of pytho ...

  5. Python基础语法学习整理

    1.基础 r’  ‘:原始字符串 pow.round是内建函数 2.序列通用操作: 索引:d[] 分片:[:] 相加:d+[] 乘法:[1,2]*3 成员判断:in 可用函数:len  max  mi ...

  6. python基础面试题整理---从零开始 每天十题(04)

    一.Q:如何用Python来进行查询和替换一个文本字符串? A:可以使用sub()方法来进行查询和替换,sub方法的格式为:sub(replacement, string[, count=0]) re ...

  7. python基础面试题整理---从零开始 每天十题(03)

    一.Q:用Python输出一个Fibonacci数列?(斐波那契额数列) A:我们先来看下代码 #!/usr/bin/env python # -*- coding: utf-8 -*- def fi ...

  8. python 基础部分重点复习整理--从意识那天开始进阶--已结

    pythonic 风格编码 入门python好博客 进阶大纲 有趣的灵魂 老齐的教程 老齐还整理了很多精华 听说 fluent python + pro python 这两本书还不错! 元组三种遍历, ...

  9. 高级测试工程师面试必问面试基础整理——python基础(一)(首发公众号:子安之路)

    现在深圳市场行情,高级测试工程师因为都需要对编程语言有较高的要求,但是大部分又没有python笔试机试题,所以面试必问python基础,这里我整理一下python基本概念,陆续收集到面试中python ...

随机推荐

  1. WPF 资源应用

    对资源的应用,有好多方法,以下是一些应用,可以参考 1.静态资源: 2.动态资源: 3.项目面板中的资源: 4.图片.声音等资源

  2. hash 默认使用equal进行元素比较 防止元素重复

    hash 默认使用equal进行元素比较 防止元素重复

  3. 【bzoj2435】[NOI2011]道路修建 树形dp

    题目描述 在 W 星球上有 n 个国家.为了各自国家的经济发展,他们决定在各个国家之间建设双向道路使得国家之间连通.但是每个国家的国王都很吝啬,他们只愿意修建恰好 n – 1条双向道路. 每条道路的修 ...

  4. 【bzoj4721】[Noip2016]蚯蚓 乱搞

    题目描述 本题中,我们将用符号[c]表示对c向下取整,例如:[3.0」= [3.1」=[3.9」=3.蛐蛐国最近蚯蚓成灾了!隔壁跳蚤国的跳蚤也拿蚯蚓们没办法,蛐蛐国王只好去请神刀手来帮他们消灭蚯蚓.蛐 ...

  5. BZOJ4000 TJOI2015棋盘(状压dp+矩阵快速幂)

    显然每一行棋子的某种放法是否合法只与上一行有关,状压起来即可.然后n稍微有点大,矩阵快速幂即可. #include<iostream> #include<cstdio> #in ...

  6. 【刷题】SPOJ 1812 LCS2 - Longest Common Substring II

    A string is finite sequence of characters over a non-empty finite set Σ. In this problem, Σ is the s ...

  7. [洛谷P3979]遥远的国度

    题目大意:有一棵$n$个点的树,每个点有一个点权,有三种操作: $1\;x:$把根变成$x$ $2\;u\;v\;x:$把路径$u->v$上的点权改为$x$ $3\;x:$询问以$x$为根的子树 ...

  8. ywy_c_asm题

    未知出处 题意: 定义一个无穷长的数列,满足以下性质:$1.X_{2n}=-{X_{n}}$ $2.X_{2n}=(-1)^{(n+1)}*X_{n}$ $3.X_{2n-1}=(-1)^{(n+1) ...

  9. 那些常用的JS命令

    window.location.reload()刷新当前页面. parent.location.reload()刷新父亲对象(用于框架) opener.location.reload()刷新父窗口对象 ...

  10. 第六章 指针与const

    const一词在字面上来源于常量constant,const对象在C/C++中是有不同解析的,如第二章所述,在C中常量表达式必须是编译期,运行期的不是常量表达式,因此C中的const不是常量表达式:但 ...