Home>

The simplest 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)

After that, visit http://localhost:5000

Support post/get submission

@ app.route ("/", methods=["get", "post"])

Multiple URLs point to

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

Regardless of whether post/get uses uniform reception

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

Handling json requestsrequest header

"content-type":"application/json"

When processing:

data=request.get_json (silent=false)

Get checkbox in post submission

{%for page in pages%}
<tr><td>
{%endfor%}
page_ids=request.form.getlist ("do_delete")

Use parameters in url

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

Dosomething at the beginning and end of the request

Can generally handle database connections, etc.

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

Register the filters 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

Can be used like this

def a ():...
def b ():...
fil={"a":a, "b":b}
app.jinja_env.filters.update (fil)

Register global variables used in jinja2 template

jinja2_globals={"media_prefix":"/media /"}
app.jinja_env.globals.update (jinja2_globals)

Define the template and static directories used by the application

app=flask (__ name__, template_folder=settings.template_folder, static_folder=settings.static_path)

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

Example:

bp_video=blueprint ("video", __name__, url_prefix="/kw_news/video")
@ bp_video.route ("/search/category /", methods=["post", "get"])
#Note that in this case url_prefix in blueprint cannot end with "/", otherwise 404

Use sessionWrapped cookie implementation, no session id

app.secret_key="ps #yio`%_! ((f_or (%))) s"

then

from flask import session
session ["somekey"]=1
session.pop ("logged_in", none)
session.clear ()
#expire date,Via cookies
from datetime import timedelta
session.permanent=true
app.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 ()

Return directly to a file

return send_file (settings.template_folder + "tweet/tweet_list.html")

Request 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!"

Get user real ipGet from request.headers

real_ip=request.headers.get ("x-real-ip", request.remote_addr)

Or, use werkzeug's middleware documentation

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)

Configuration read method

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

A few less commonly used methods

from flask import abort, flash
abort
if not session.get ("logged_in"):
  abort (401)
flash
flash ("new entry was successfully posted")

Asynchronous callI want to handle asynchronous in one request of flask, In addition to using the message system, Can be processed with simple threads

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

Project configuration1. Directly

app.config ["host"]="xxx.a.com"
print app.config.get ("host")

2. Environment variables

export myappconfig =/path/to/settings.cfg
app.config.from_envvar ("myappconfig")

3. Object

class config (object):
   debug=false
   testing=false
   database_uri="sqlite://:memory:"
 class productionconfig (config):
   database_uri="mysql://[email protected]/foo"
 app.config.from_object (productionconfig)
 print app.config.get ("database_uri") #mysql://[email protected]/foo

4. file

#default_config.py
host="localhost"
port=5000
debug=true
app.config.from_pyfile ("default_config.py")

eg. a create_app method

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
  • Previous Android programming method for SD card to read database
  • Next Example code explain jqueryslidesjs