Python's flask development Framework easy to get started notes

Source: Internet
Author: User
The simplest of 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)

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 the Post/get uses a unified receive

From flask Import Requestargs = Request.args if Request.method = = ' GET ' Else Request.forma = args.get (' A ', ' default ')

Working with JSON requests
In the header of request

"Content-type": "Application/json"

When processing:

data = Request.get_json (Silent=false)

Get a checkbox in a post submission

{%for page in pages%}{%endfor%}page_ids = request.form.getlist ("Do_delete")

Using the parameters in the URL

@app. Route ('/query/
 
  
   
  /') def query (qid):  pass
 
  

At the beginning of the request, dosomething
Generally can handle database connection and so on

From flask import GapP = ... @app. Before_requestdef before_request ():  g.session = create_session () @app. Teardown_ Requestdef teardown_request (Exception):  G.session.close ()

Registering 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

You can use this.

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

Registering 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 directories used by your app

App = Flask (__name__, template_folder=settings. Template_folder, Static_folder = settings. Static_path)

Using 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 ']) #注意这种情况下Blueprint中url_prefix不能以 '/' End, otherwise 404

Use session
Wrapper cookie implementation, no session ID

App.secret_key = ' Ps#yio '%_! ((F_or (%))) s '

And then

From flask import sessionsession[' somekey '] = 1session.pop (' logged_in ', None) session.clear () #过期时间, the from that is implemented via cookies DateTime import timedeltasession.permanent = Trueapp.permanent_session_lifetime = Timedelta (minutes=5)

Reverse route

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

Uploading files

 
  
  
   
 
  

Receive

f = request.files.get (' upload ') Img_data = F.read ()

Return a file directly

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 is 301, 302, 303, 305, and 307. Supported. @app. Route ('/') def hello ():  return Redirect (Url_for (' foo ')) @app. Route ('/foo ') def foo ():  return ' Hello foo! '

Get the user's real IP
Get 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 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.G ET (' callback ', ') if Jsonp_callback:  return Response (      "%s (%s);"% (Jsonp_callback, json.dumps ({' OK ': True, ' Data ':d ATA}),      mimetype= "Text/javascript"      ) return ok_jsonify (data)

Configuring the Read method

# Create our little application:) app = Flask (__name__) # Load default Config and override config from an environment varia Bleapp.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 appli cation:) app = Flask (__name__) app.config.from_object (__name__) app.config.from_envvar (' Minitwit_settings ', silent= True)

A few less common methods

From flask Import Abort, flashabortif not Session.get (' logged_in '):  abort (401) flashflash (' New entry ') Successfully posted ')

asynchronous invocation
To handle asynchrony in a request from flask, in addition to using the messaging system, you can use simple threading

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 (+) 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. Objects

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

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