python -- Flask使用小结

最简单的hello world


[python]  view plain  copy
  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提交


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


多个url指向


@app.route('/')

@app.route('/index')


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


[python]  view plain  copy
  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中


"Content-Type": "application/json"


处理时:


data = request.get_json(silent=False)


获取post提交中的checkbox


{%forpageinpages %}

<tr><td><inputtype=checkboxname=do_deletevalue="{{ page['id'] }}"></td><td>

{%endfor%}

 

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


使用url中的参数


[python]  view plain  copy
  1. @app.route('/query/<qid>/')  
  2. def query(qid):  
  3.     pass  



在request开始结束dosomething


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


[python]  view plain  copy
  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模板中使用的过滤器


[python]  view plain  copy
  1. @app.template_filter('reverse')  
  2. defreverse_filter(s):  
  3.     returns[::-1]  



或者


[python]  view plain  copy
  1. def reverse_filter(s):  
  2.     returns[::-1]  
  3. app.jinja_env.filters['reverse'] = reverse_filter  



可以这么用


[python]  view plain  copy
  1. defa():...  
  2. defb():...  
  3.    
  4. FIL = {'a':a,'b':b}  
  5. app.jinja_env.filters.update(FIL)  



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


[python]  view plain  copy
  1. JINJA2_GLOBALS = {'MEDIA_PREFIX':'/media/'}  
  2. app.jinja_env.globals.update(JINJA2_GLOBALS)  



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


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


使用Blueprint


[python]  view plain  copy
  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)  



实例:


[python]  view plain  copy
  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


[python]  view plain  copy
  1. app.secret_key = 'PS#yio`%_!((f_or(%)))s'  
  2.    
  3. # 然后  
  4. from flask import session  
  5.    
  6. session['somekey'] = 1  
  7. session.pop('logged_in',None)  
  8.    
  9. session.clear()  
  10.    
  11. #过期时间,通过cookie实现的  
  12. fromd atetime import timedelta  
  13. session.permanent = True  
  14. app.permanent_session_lifetime = timedelta(minutes=5)  



反向路由


[python]  view plain  copy
  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())  


上传文件


<formaction="/image/upload/"method="post"enctype="multipart/form-data">

<inputtype="file"name="upload" />


接收


[python]  view plain  copy
  1. f = request.files.get('upload')  
  2. img_data = f.read()  



直接返回某个文件


[python]  view plain  copy
  1. 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.


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



获取用户真实ip


从request.headers获取


[python]  view plain  copy
  1. real_ip = request.headers.get('X-Real-Ip', request.remote_addr)  



或者, 使用werkzeug的middleware 文档


[python]  view plain  copy
  1. from werkzeug.contrib.fixers import ProxyFix  
  2. app.wsgi_app = ProxyFix(app.wsgi_app)  



return json & jsonp


[python]  view plain  copy
  1. import json  
  2. from flask import jsonify,Response,json  
  3.    
  4. data = []# or others  
  5. return jsonify(ok=True,data=data)  
  6.    
  7. jsonp_callback =  request.args.get('callback','')  
  8. if jsonp_callback:  
  9.     return Response(  
  10.             "%s(%s);" % (jsonp_callback,json.dumps({'ok':True,'data':data})),  
  11.             mimetype="text/javascript"  
  12.             )  
  13. return ok_jsonify(data)  



配置读取方法


[python]  view plain  copy
  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. # configuration  
  16. DATABASE = '/tmp/minitwit.db'  
  17. PER_PAGE = 30  
  18. DEBUG = True  
  19. SECRET_KEY = 'development key'  
  20.    
  21. # create our little application :)  
  22. app = Flask(__name__)  
  23. app.config.from_object(__name__)  
  24. app.config.from_envvar('MINITWIT_SETTINGS',silent=True)  



几个不常用的方法


[python]  view plain  copy
  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的一个请求中处理异步, 除了使用消息系统, 可以用简单的线程处理


[python]  view plain  copy
  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.     printcall_args  
  12.    
  13. inarequesthandler,call`dosomething`  



error handler


[python]  view plain  copy
  1. @app.errorhandler(404)  
  2. def not_found_error(error):  
  3.     return render_template('404.html'),404  
  4.   
  5. @app.errorhandler(500)  
  6. def internal_error(error):  
  7.     db.session.rollback()  
  8.     return render_template('500.html'),500  



项目配置


1.直接


[python]  view plain  copy
  1. app.config['HOST']='xxx.a.com'  
  2. print app.config.get('HOST')  



2.环境变量


[python]  view plain  copy
  1. exportMyAppConfig=/path/to/settings.cfg  
  2. app.config.from_envvar('MyAppConfig')  



3.对象


[python]  view plain  copy
  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.文件


[python]  view plain  copy
  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方法


[python]  view plain  copy
  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.     defbefore_request():  
  17.         g.xxx = ...    #do some thing  
  18.   
  19.     @app.teardown_request  
  20.     defteardown_request(exception):  
  21.         g.xxx = ...    #do some thing  
  22.    
  23.     returnapp  
  24.    
  25. app = create_app(settings.DEBUG)  
  26. host=settings.SERVER_IP  
  27. port=settings.SERVER_PORT  
  28. app.run(host=host,port=port)  

猜你喜欢

转载自blog.csdn.net/xuezhangjun0121/article/details/80348948