最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python的Flask開(kāi)發(fā)框架簡(jiǎn)單上手筆記

 更新時(shí)間:2015年11月16日 15:55:51   作者:凌岳  
這篇文章主要介紹了Python的Flask開(kāi)發(fā)框架的入門(mén)知識(shí)整理,Flask是一款極輕的Python web開(kāi)發(fā)框架,需要的朋友可以參考下

最簡(jiǎn)單的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)

之后,訪問(wèn)http://localhost:5000

支持post/get提交

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

多個(gè)url指向

@app.route('/')
@app.route('/index')

不管post/get使用統(tǒng)一的接收

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

處理json請(qǐng)求
request的header中

"Content-Type": "application/json"

處理時(shí):

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

使用url中的參數(shù)

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

在request開(kāi)始結(jié)束dosomething
一般可以處理數(shù)據(jù)庫(kù)連接等等

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

注冊(cè)Jinja2模板中使用的過(guò)濾器

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

注冊(cè)Jinja2模板中使用的全局變量

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

定義應(yīng)用使用的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)

實(shí)例:

bp_video = Blueprint('video', __name__, url_prefix='/kw_news/video')
@bp_video.route('/search/category/', methods=['POST', 'GET'])
#注意這種情況下Blueprint中url_prefix不能以 '/' 結(jié)尾, 否則404

使用session
包裝cookie實(shí)現(xiàn)的,沒(méi)有session id

app.secret_key = 'PS#yio`%_!((f_or(%)))s'

然后

from flask import session

session['somekey'] = 1
session.pop('logged_in', None)

session.clear()

#過(guò)期時(shí)間,通過(guò)cookie實(shí)現(xiàn)的
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()

直接返回某個(gè)文件

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

請(qǐng)求重定向

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

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

幾個(gè)不常用的方法

from flask import abort, flash

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

flash
flash('New entry was successfully posted')

異步調(diào)用
想在flask的一個(gè)請(qǐng)求中處理異步, 除了使用消息系統(tǒng), 可以用簡(jiǎn)單的線程處理

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

項(xiàng)目配置
1.直接

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

2.環(huán)境變量

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

3.對(duì)象

 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. 一個(gè)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

相關(guān)文章

  • python中scrapy處理項(xiàng)目數(shù)據(jù)的實(shí)例分析

    python中scrapy處理項(xiàng)目數(shù)據(jù)的實(shí)例分析

    在本篇文章里小編給大家整理了關(guān)于python中scrapy處理項(xiàng)目數(shù)據(jù)的實(shí)例分析內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。
    2020-11-11
  • python得到電腦的開(kāi)機(jī)時(shí)間方法

    python得到電腦的開(kāi)機(jī)時(shí)間方法

    今天小編就為大家分享一篇python得到電腦的開(kāi)機(jī)時(shí)間方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-10-10
  • python 檢查文件mime類型的方法

    python 檢查文件mime類型的方法

    今天小編就為大家分享一篇python 檢查文件mime類型的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-12-12
  • Python從文件中讀取數(shù)據(jù)的方法講解

    Python從文件中讀取數(shù)據(jù)的方法講解

    今天小編就為大家分享一篇關(guān)于Python從文件中讀取數(shù)據(jù)的方法講解,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2019-02-02
  • Flask學(xué)習(xí)筆記之日志操作配置實(shí)例講解

    Flask學(xué)習(xí)筆記之日志操作配置實(shí)例講解

    這篇文章主要為大家介紹了Flask學(xué)習(xí)筆記之日志操作配置實(shí)例講解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-11-11
  • python安裝gdal的兩種方法

    python安裝gdal的兩種方法

    這篇文章主要介紹了python安裝gdal的兩種方法,每種方法給大家介紹的都非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-10-10
  • Python字符串對(duì)齊和判斷方法匯總

    Python字符串對(duì)齊和判斷方法匯總

    本教程將詳細(xì)介紹Python中的字符串對(duì)齊方法以及字符串判斷方法,這些方法在文本處理、格式化輸出和字符串匹配中非常實(shí)用,無(wú)論你是Python初學(xué)者還是想要鞏固基礎(chǔ)知識(shí)的程序員,這篇教程都能幫助你全面理解這些操作,需要的朋友可以參考下
    2025-04-04
  • Python?calendar模塊詳情

    Python?calendar模塊詳情

    這篇文章主要介紹了?Python?calendar模塊,Python?專門(mén)為了處理日歷提供了calendar日歷模塊,下面文章基于time模塊和datetime模塊展開(kāi),具有一定的參考價(jià)值,需要的朋友可以參考一下
    2021-11-11
  • python函數(shù)也可以是一個(gè)對(duì)象,可以存放在列表中并調(diào)用方式

    python函數(shù)也可以是一個(gè)對(duì)象,可以存放在列表中并調(diào)用方式

    這篇文章主要介紹了python函數(shù)也可以是一個(gè)對(duì)象,可以存放在列表中并調(diào)用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-02-02
  • python環(huán)境下安裝opencv庫(kù)的方法

    python環(huán)境下安裝opencv庫(kù)的方法

    這篇文章主要介紹了python環(huán)境下安裝opencv庫(kù)的方法 ,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-03-03

最新評(píng)論

西昌市| 玉林市| 改则县| 宁远县| 敦煌市| 炉霍县| 永济市| 嘉义县| 区。| 盐池县| 自贡市| 建昌县| 定日县| 巴里| 尼勒克县| 儋州市| 临洮县| 商南县| 韶山市| 佛坪县| 玛纳斯县| 屏东县| 商丘市| 石嘴山市| 灵台县| 陕西省| 赤峰市| 台南县| 县级市| 蕲春县| 太和县| 溧水县| 海原县| 宣汉县| 六枝特区| 新安县| 南木林县| 高密市| 乌拉特中旗| 同仁县| 台南市|