Python Flask development framework easy to use notes, pythonflask

Source: Internet
Author: User

Python Flask development framework easy to use notes, pythonflask

The simplest hello world

#!/usr/bin/env python# encoding: utf-8from flask import Flaskapp = 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)

Then, access http: // localhost: 5000

Supports post/get submission

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

Multiple URLs direct

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

No matter whether post/get is used, the unified reception

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

Process json requests
Request header

"Content-Type": "application/json"

Processing time:

data = request.get_json(silent=False)

Get the checkbox in post submission

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

Use parameters in the url

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

End dosomething at request start
Generally, you can process database connections.

from flask import gapp = .....@app.before_requestdef before_request():  g.session = create_session()@app.teardown_requestdef teardown_request(exception):  g.session.close()

Register the filter used in the Jinja2 Template

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

Or

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

This can be used.

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

Register the global variables used in the Jinja2 Template

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

Define the template and static directory used by the application

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

Use Blueprint

from flask import Blueprintbp_test = Blueprint('test', __name__)#bp_test = Blueprint('test', __name__, url_prefix='/abc')@bp_test.route('/')--------from xxx import bp_testapp = Flask(__name__)app.register_blueprint(bp_test)

Instance:

Bp_video = Blueprint ('video', _ name __, url_prefix = '/kw_news/video') @ bp_video.route ('/search/category/', methods = ['post ', 'get']) # in this case, the url_prefix in Blueprint cannot end with '/'; otherwise, 404

Use session
Cookie wrapped, no session id

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

Then

From flask import sessionsession ['somekey'] = 1session. pop ('logged _ in', None) session. clear () # expiration time, from datetime import timedeltasession implemented by cookie. permanent = Trueapp. permanent_session_lifetime = timedelta (minutes = 5)

Reverse Routing

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

Upload files

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

Receive

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

Directly return an object

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

Request redirection

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

Obtain the user's real ip Address
Obtain from request. headers

Real_ip = request. headers. get ('x-Real-ip', request. remote_addr)
Alternatively, use the middleware document of werkzeug.

from werkzeug.contrib.fixers import ProxyFixapp.wsgi_app = ProxyFix(app.wsgi_app)return json & jsonpimport jsonfrom flask import jsonify, Response, jsondata = [] # or othersreturn 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)

Configure read Methods

# create our little application :)app = Flask(__name__)# Load default config and override config from an environment variableapp.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)------------------# configurationDATABASE = '/tmp/minitwit.db'PER_PAGE = 30DEBUG = TrueSECRET_KEY = 'development key'# create our little application :)app = Flask(__name__)app.config.from_object(__name__)app.config.from_envvar('MINITWIT_SETTINGS', silent=True)

Several uncommon Methods

from flask import abort, flashabortif not session.get('logged_in'):  abort(401)flashflash('New entry was successfully posted')

Asynchronous call
To process Asynchronization in a flask request, you can use a simple thread to process it in addition to the message system.

from threading import Threaddef async(f):  def wrapper(*args, **kwargs):    thr = Thread(target=f, args=args, kwargs=kwargs)    thr.start()  return wrapper@asyncdef dosomething(call_args):  print call_argsin 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

Project Configuration
1. Direct

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

2. Environment Variables

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

3. Object

 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. File

# default_config.pyHOST = 'localhost'PORT = 5000DEBUG = Trueapp.config.from_pyfile('default_config.py')

EG. A create_app Method

from flask import Flask, gdef 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 appapp = create_app(settings.DEBUG)host=settings.SERVER_IPport=settings.SERVER_PORTapp.run(host=host, port=port)change log:2013-09-09 create2014-10-25 update

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.