国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python的Flask開發(fā)框架簡單上手筆記

2020-01-04 17:57:24
字體:
來源:轉載
供稿:網友

這篇文章主要介紹了Python的Flask開發(fā)框架的入門知識整理,Flask是一款極輕的Python web開發(fā)框架,需要的朋友可以參考下

最簡單的hello world

 

 
  1. #!/usr/bin/env python 
  2. # encoding: utf-8 
  3.  
  4. from flask import Flask 
  5. app = Flask(__name__) 
  6.  
  7. @app.route('/'
  8. def index(): 
  9. return 'hello world' 
  10.  
  11. if __name__ == '__main__'
  12. app.run(debug=True) 
  13. #app.run(host='127.0.0.1', port=8000) 

之后,訪問http://localhost:5000

支持post/get提交

 

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

多個url指向

 

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

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

 

 
  1. from flask import request 
  2. args = request.args if request.method == 'GET' else request.form 
  3. a = args.get('a''default'

處理json請求

request的header中

 

 
  1. "Content-Type""application/json" 

處理時:

 

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

獲取post提交中的checkbox

 

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

使用url中的參數

 

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

在request開始結束dosomething

一般可以處理數據庫連接等等

 

 
  1. from flask import g 
  2.  
  3. app = ..... 
  4.  
  5. @app.before_request 
  6. def before_request(): 
  7. g.session = create_session() 
  8.  
  9. @app.teardown_request 
  10. def teardown_request(exception): 
  11. g.session.close() 

注冊Jinja2模板中使用的過濾器

 

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

或者

 

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

可以這么用

 

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

注冊Jinja2模板中使用的全局變量

 

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

定義應用使用的template和static目錄

 

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

使用Blueprint

 

 
  1. from flask import Blueprint 
  2. bp_test = Blueprint('test', __name__) 
  3. #bp_test = Blueprint('test', __name__, url_prefix='/abc') 
  4.  
  5. @bp_test.route('/'
  6.  
  7. -------- 
  8. from xxx import bp_test 
  9.  
  10. app = Flask(__name__) 
  11. app.register_blueprint(bp_test) 

實例:

 

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

使用session

包裝cookie實現的,沒有session id

 

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

然后

 

 
  1. from flask import session 
  2.  
  3. session['somekey'] = 1 
  4. session.pop('logged_in', None) 
  5.  
  6. session.clear() 
  7.  
  8. #過期時間,通過cookie實現的 
  9. from datetime import timedelta 
  10. session.permanent = True 
  11. app.permanent_session_lifetime = timedelta(minutes=5) 

反向路由

 

 
  1. from flask import url_for, render_template 
  2.  
  3. @app.route("/"
  4. def home(): 
  5. login_uri = url_for("login", next=url_for("home")) 
  6. return render_template("home.html", **locals()) 

上傳文件

 

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

接收

 

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

直接返回某個文件

 

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

請求重定向

 

 
  1. 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. 
  2.  
  3. @app.route('/'
  4. def hello(): 
  5. return redirect(url_for('foo')) 
  6.  
  7. @app.route('/foo'
  8. def foo(): 
  9. return'Hello Foo!' 

獲取用戶真實ip

從request.headers獲取

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

或者, 使用werkzeug的middleware 文檔

 

 
  1. from werkzeug.contrib.fixers import ProxyFix 
  2. app.wsgi_app = ProxyFix(app.wsgi_app) 
  3. return json & jsonp 
  4. import json 
  5. from flask import jsonify, Response, json 
  6.  
  7. data = [] # or others 
  8. return jsonify(ok=True, data=data) 
  9.  
  10. jsonp_callback = request.args.get('callback'''
  11. if jsonp_callback: 
  12. return Response( 
  13. "%s(%s);" % (jsonp_callback, json.dumps({'ok': True, 'data':data})), 
  14. mimetype="text/javascript" 
  15. return ok_jsonify(data) 

配置讀取方法

 

 
  1. # create our little application :) 
  2. app = Flask(__name__) 
  3.  
  4. # Load default config and override config from an environment variable 
  5. app.config.update(dict( 
  6. DATABASE='/tmp/flaskr.db'
  7. DEBUG=True, 
  8. SECRET_KEY='development key'
  9. USERNAME='admin'
  10. PASSWORD='default' 
  11. )) 
  12. app.config.from_envvar('FLASKR_SETTINGS', silent=True) 
  13.  
  14.  
  15. ------------------ 
  16. # configuration 
  17. DATABASE = '/tmp/minitwit.db' 
  18. PER_PAGE = 30 
  19. DEBUG = True 
  20. SECRET_KEY = 'development key' 
  21.  
  22. # create our little application :) 
  23. app = Flask(__name__) 
  24. app.config.from_object(__name__) 
  25. app.config.from_envvar('MINITWIT_SETTINGS', silent=True) 

幾個不常用的方法

 

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

異步調用

想在flask的一個請求中處理異步, 除了使用消息系統, 可以用簡單的線程處理

 

 
  1. from threading import Thread 
  2.  
  3. def async(f): 
  4. def wrapper(*args, **kwargs): 
  5. thr = Thread(target=f, args=args, kwargs=kwargs) 
  6. thr.start() 
  7. return wrapper 
  8.  
  9. @async 
  10. def dosomething(call_args): 
  11. print call_args 
  12.  
  13.  
  14. in a request handler, call `dosomething` 
  15. error handler 
  16. @app.errorhandler(404) 
  17. def not_found_error(error): 
  18. return render_template('404.html'), 404 
  19.  
  20. @app.errorhandler(500) 
  21. def internal_error(error): 
  22. db.session.rollback() 
  23. return render_template('500.html'), 500 

項目配置

1.直接

 

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

2.環(huán)境變量

 

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

3.對象

 

 
  1. class Config(object): 
  2. DEBUG = False 
  3. TESTING = False 
  4. DATABASE_URI = 'sqlite://:memory:' 
  5.  
  6. class ProductionConfig(Config): 
  7. DATABASE_URI = 'mysql://user@localhost/foo' 
  8.  
  9. app.config.from_object(ProductionConfig) 
  10. print app.config.get('DATABASE_URI') # mysql://user@localhost/foo 

4.文件

 

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

EG. 一個create_app方法

 

 
  1. from flask import Flask, g 
  2.  
  3. def create_app(debug=settings.DEBUG): 
  4. app = Flask(__name__, 
  5. template_folder=settings.TEMPLATE_FOLDER, 
  6. static_folder=settings.STATIC_FOLDER) 
  7.  
  8. app.register_blueprint(bp_test) 
  9.  
  10. app.jinja_env.globals.update(JINJA2_GLOBALS) 
  11. app.jinja_env.filters.update(JINJA2_FILTERS) 
  12.  
  13. app.secret_key = 'PO+_)(*&678OUIJKKO#%_!(((%)))' 
  14.  
  15. @app.before_request 
  16. def before_request(): 
  17. g.xxx = ... #do some thing 
  18.  
  19. @app.teardown_request 
  20. def teardown_request(exception): 
  21. g.xxx = ... #do some thing 
  22.  
  23. return app 
  24.  
  25. app = create_app(settings.DEBUG) 
  26. host=settings.SERVER_IP 
  27. port=settings.SERVER_PORT 
  28. app.run(host=host, port=port) 
  29. change log: 
  30.  
  31. 2013-09-09 create 
  32. 2014-10-25 update 

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 禹城市| 西安市| 原阳县| 剑阁县| 阿城市| 田东县| 南部县| 壶关县| 湟源县| 马公市| 潮州市| 民和| 延川县| 德兴市| 河北省| 六安市| 洛隆县| 开鲁县| 舒城县| 韶山市| 通江县| 达孜县| 叙永县| 平远县| 罗定市| 江西省| 金门县| 葫芦岛市| 济源市| 阿合奇县| 古浪县| 崇仁县| 峨眉山市| 盘锦市| 鹤庆县| 余庆县| 梁平县| 平南县| 乌兰察布市| 枣庄市| 黄大仙区|