Flask 使用小結【Updating】

一、最簡單的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:5000javascript

二、支持post/get提交

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

多個url指向 java

@app.route('/')
python

@app.route('/index')mysql

無論post/get使用統一的接收 sql

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

三、使用url中的參數

@app.route('/query/<qid>/')
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模板中使用的過濾器
json

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

或者
flask

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

能夠這麼用
segmentfault

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目錄、使用Blueprint

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)

六、使用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())

八、上傳文件

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

接收
f = request.files.get('upload')
img_data = f.read()

直接返回某個文件

return send_file(settings.TEMPLATE_FOLDER + 'tweet/tweet_list.html')

九、請求重定向

文檔:http://flask.pocoo.org/docs/api/#flask.redirect

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!'



from flask import abort
@app.route('/*')
def page404():
    abort(404)

@app.errorhandler(404)
def page_not_found(e):
    print request.url + "\t404..."
    return render_template('page404.html'), 404

獲取用戶真實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)

十、Form 表單 post 數據

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys

reload(sys)
sys.setdefaultencoding('utf-8')
from commonFunc import  *
from flask import Flask, request, redirect, url_for

app = Flask(__name__)


@app.route('/')
def index():
    return redirect(url_for('username'), code=302)    # URL跳轉,默認代碼是302,能夠省略


@app.route('/username', methods=['GET', 'POST'])
def username():
    HTML = '''<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Flask POST方法演示</title>
</head>
<body>
{}
<form action="" method="POST">
    <textarea name="username" rows="30" cols="150"></textarea>
    <br>
    <input type="submit" name="enter" value="enter"
    style="width:60px;height:30px; font-size:14px; color:red;"
    />
</form>
  
</body>
</html>'''
    if request.method == 'GET':
        return HTML.format('')
    elif request.method == 'POST':
        if request.form['username']:
            urlList = request.form['username'].splitlines()
            resultStr = ""
            for url in urlList:
                resultStr += chkListPageContent(url, getUrlContent(url), "script") + "<br>"
            return HTML.format('<p>檢查結果<br><strong>{}</strong></p>'.format(resultStr))
        else:
            return redirect(url_for('username'))


if __name__ == '__main__':
    app.run(debug=True, host='127.0.0.1', port=8080)

十一、處理json請求、return json & jsonp

request的header中
"Content-Type": "application/json"
處理時:
data = request.get_json(silent=False)

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)

十二、獲取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三、配置讀取方法

# 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四、幾個不經常使用的方法:401 重定向

from flask import abort, flash

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

flash
flash('New entry was successfully posted')

Flask中實現域名301重定向

固然,這是一種很是不明智的作法,只是一種臨時性的手段。301重定向應該由服務器層面的應用程序(好比NGINX,APACHE,IIS等)來完成。
代碼示例以下:

def RedirectMiddleWare(request):
    url = None
    domain = 'www.digwtx.com'
    try:
        host, port = request.host.split(':')
        path = request.path
    except:
        host = request.host
        port = 80
        path = request.path

    if host != domain:
        print 'do 301'
        if port == 80:
            url = 'http://%s%s' % (domain, path)
        else:
            url = 'http://%s:%s%s' % (domain, port, path)
    return url

1五、異步調用

想在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`

1六、項目配置

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

1七、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)

1八、IE 訪問Flask自帶服務器假死問題解決方法

threaded 多線程支持,默認不開啓
processes 進程數量,默認爲1個

if __name__ == '__main__':
    #app.run(host='localhost', port=8080, debug=True)
    app.run(host='localhost', port=8080, threaded=True, debug=True)
    app.run(processes=10)

若是使用了Flask-Script來部署應用,能夠給runserver命令加上--threaded參數或者--processes N參數(參數意義同上)。例如:
python manage.py runserver --threaded
或者:
python manage.py runserver --processes 3

1九、Flask生成SECRET_KEY(密鑰)的一種簡單方法

>>> import os
>>> os.urandom(24)
'\xca\x0c\x86\x04\x98@\x02b\x1b7\x8c\x88]\x1b\xd7"+\xe6px@\xc3#\\'

而後:

app = Flask(__name__)
app.config['SECRET_KEY'] = '\xca\x0c\x86\x04\x98@\x02b\x1b7\x8c\x88]\x1b\xd7"+\xe6px@\xc3#\\'
# or
app.secret_key = '\xca\x0c\x86\x04\x98@\x02b\x1b7\x8c\x88]\x1b\xd7"+\xe6px@\xc3#\\'
# or
app.config.update(SECRET_KEY='\xca\x0c\x86\x04\x98@\x02b\x1b7\x8c\x88]\x1b\xd7"+\xe6px@\xc3#\\')

20、Flask加鹽密碼生成和驗證函數

>>> from werkzeug.security import generate_password_hash
>>> print generate_password_hash('123456')
'pbkdf2:sha1:1000$X97hPa3g$252c0cca000c3674b8ef7a2b8ecd409695aac370'

>>> from werkzeug.security import check_password_hash
>>> pwhash = 'pbkdf2:sha1:1000$X97hPa3g$252c0cca000c3674b8ef7a2b8ecd409695aac370'
>>> print check_password_hash(pwhash, '123456')
True


2一、Refer:

一、FLASK使用小結    http://wklken.me/posts/2013/09/09/python-framework-flask.html

二、Flask POST方法

http://www.itwhy.org/%E8%BD%AF%E4%BB%B6%E5%B7%A5%E7%A8%8B/python/flask-post%E6%96%B9%E6%B3%95.html

三、Day 3: Flask —— 使用Python和OpenShift進行即時Web開發

http://segmentfault.com/a/1190000000351512  

四、Flask Web Development —— 模板(中)

http://segmentfault.com/blog/young_ipython/1190000000755204

五、Flask技巧

http://flask123.sinaapp.com/category/flask-tips/

六、Python模板-Jinja2

http://python.jobbole.com/83560/

相關文章
相關標籤/搜索