Flask Web Development Note-Quick Start

Source: Internet
Author: User
Tags passthrough

Flask Web Development Note-Quick StartInitialization

Flask applications need to create application instances. The Web server passes the request received from the client to the object through the Web server Gateway Interface (WSGI) protocol. An application instance is a flask class object that is typically created as follows:

From flask Import Flaskapp = Flask (__name__)

The only parameter to the constructor of the Flask class is the application's main module name or package name, which determines the root directory of the app. For most applications, use Python's __name__ variable.

Routing and view functions

The client sends the request to the Web server, such as a Web browser, and forwards it to the flask application instance. Application instances need to know what code each URL executes, so it preserves the mapping of the URL to the Python function. The Association of URLs and processing functions is called route (route).

The most convenient way to add a route is through the adorner app.route of the application instance, which registers the function as a route. Like what:

@app. Route ('/') def index (): Return ' 

Adorners are the standard function of the Python language and can modify the behavior of functions. The common adorner registration function is the event handler. The index above is called the view function.

Handling variables:

@app. Route ('/user/<name> ') def user (name): Return ' 

The default is the string, which also supports int, float, and path. Like/user/<int:id>. Path is similar to a string, but does not take a slash as a delimiter.

Start the server
if __name__ = = ' __main__ ': App.run (debug=true)

If you visit a nonexistent URL, you will return 404.

Full application
From flask Import Flaskapp = Flask (__name__) @app. Route ('/') def index (): Return ' 

Execution Server side:

#python hello.py * Running on http://0.0.0.0:80/* Restarting with reloader192.168.0.231--[01/sep/2014 05:03:41] "GET /user/andrew http/1.1 "200-192.168.0.231--[01/sep/2014 05:03:45]" get/http/1.1 "200-

Execute client:

#curl Http://192.168.0.233/user/Andrew

Request Response Mechanism
    • Application and request contexts

Flask temporarily stores some objects using the context. For example, the request object encapsulates the client's HTTP request. Flask the request data into the global space through the context. So you can do this.

From flask import flaskfrom flask Import Requestapp = Flask (__name__) @app. Route ('/') def index (): User_agent = request.h Eaders.get (' user-agent ') return ' <p>your browser is%s</p> '% user_agentif __name__ = ' __main__ ': APP.R Un (debug=true,host= ' 0.0.0.0 ', port=80)

Execution Result:

$ Curl Http://192.168.1.100<p>Your Browser is curl/7.35.0</p># browser executes Your browser is mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:28.0) gecko/20100101 firefox/28.0

Note that different threads see a different request. The global context is as follows:

Variable name Context Description
Current_app Application context An instance of an active app.
G Application context Temporary storage that is used when the app is processed, and each request will be reset
Request Request context The request object that encapsulates the client's HTTP request
Session Request context User session, applying a dictionary of values that can be stored for common data between different requests

These four variables can be seen after push.

>>> from hello import app>>> from flask import current_app>>> current_app.nametraceback (most Recent call last): ... Runtimeerror:working outside of application context>>> App_ctx = App.app_context () >>> App_ctx.push () >>> current_app.name ' Hello ' >>> app_ctx.pop ()

    • Request distribution

App.route adds a URL map, which is equivalent to Method App.add_url_rule (). App.add_url_rule () stores the URL mappings.

(venv) $ python>>> from Hello import app>>> app.url_mapmap ([<rule '/' (HEAD, OPTIONS, GET), Inde X>, <rule '/static/<filename> ' (head, OPTIONS, GET), Static>, <rule '/user/<name> ' (head, OP tions, GET), User>])

    • Request Hooks

Hooks are suitable for a number of versatile operations. At present there are before_first_request, Before_request, After_request (with exception will not execute), Teardown_request (exception will be executed). Hook and view functions can pass parameters using global variable g before.

    • Response

The default return status code 200, can be modified:

@app. Route ('/') def index (): Return ' 

Execution Result:

$ Curl Http://127.0.0.1

You can add a dictionary of headers as a 3rd parameter, but it is seldom used. Alternatively, you can return the response object. Make_response () accepts 1-3 parameters for custom response of view functions, such as:

From flask import make_response@app.route ('/') def index (): Response = make_response (' 

There is also a special response redirect, which is used more for the form. REDIRECT Returns status code 302 and URL. You can also return directly to a 3 value or response object, but redirect is faster.

From flask Import Flaskapp = Flask (__name__) from flask import redirect@app.route ('/') def index (): Return redirect (' http ://automationtesting.sinaapp.com/') if __name__ = = ' __main__ ': App.run (debug=true,host= ' 0.0.0.0 ', port=80)

Execution Result:

$ Curl http://127.0.0.1<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 3.2 final//en" ><title>Redirecting...</title>

Browser access usually jumps directly.

Abort is also a special response for error handling. It directly generates an exception and gives control to the Web server.

From flask import abort@app.route ('/user/<id> ') def get_user (id): User = Load_user (ID) if not User:abor T (404) Return ' 

Simplified Example:

From flask Import Flaskapp = Flask (__name__) from flask import abort@app.route ('/user/<id> ') def get_user (ID): Abor T (404) Return ' 

Execution Result:

$ Curl http://127.0.0.1<! DOCTYPE HTML public '-//w3c//dtd HTML 3.2 final//en ' ><title>404 not found</title>

Flask Extension

Flask supports a number of boot configuration options by passing them as parameters to App.run (). The flask-script extension adds command-line parameter support.

# pip install flask-scriptcollecting flask-script  downloading  flask-script-2.0.5.tar.gz  (42kB)     100% |################################|  45kB 236kB/s Requirement already satisfied  (use --upgrade to  Upgrade): flask in /usr/local/lib/python2.7/dist-packages  (From flask-script) requirement already satisfied  (use --upgrade to upgrade):  Werkzeug>=0.7  in /usr/local/lib/python2.7/dist-packages  (From flask->flask-script) requirement  already satisfied  (use --upgrade to upgrade):  jinja2>=2.4 in /usr/ local/lib/python2.7/dist-packages  (From flask->flask-script) requirement already  satisfied  (use --upgrade to upgrade):  itsdangerous>=0.21 in /usr/local/ lib/python2.7/dist-packages  (From flask->flask-script) requirement already satisfied  (Use --upgrade to upgrade):  markupsafe in /usr/local/lib/python2.7/dist-packages  (from jinja2>=2.4->flask- >flask-script) installing collected packages: flask-script  running setup.py  install for flask-scriptsuccessfully installed flask-script-2.0.5

From flask import Flaskfrom flask.ext.script Import Managerapp = Flask (__name__) Manager = Manager (APP) @app. Route ('/') def Index (): Return ' 

Usage:

]# python hello.pyusage: hello.py [-?]  {shell,runserver} ...positional arguments:  {shell,runserver}     shell            runs a python  shell inside Flask application context.    runserver         Runs the Flask development server i.e.  App.run () optional arguments:  -?,  --help          show this help message and exit# python hello.py runserver  --helpusage: hello.py runserver [-?]  [-h HOST] [-p PORT] [--threaded]                           [- -processes processes]  [--passthrough-errors] [-d]                           [-d] [-r] [-r]runs  the flask development server i.e. app.run () optional arguments:   -?,  --help            show this  Help message and exit  -h host, --host host  -p port,  --port port  --threaded  --processes processes  -- passthrough-errors  -d, --debug            enable the Werkzeug debugger  (do not use in production                          code)   -d, --no-debug        disable the werkzeug  debugger  -r, --reload          monitor  python files for changes  (not 100{' const ':                         true,   ' help ':  ' monitor python files for changes  (not                          100% safe for production use) ',  ' option_strings ':                          ['-R ',  '--reload '],  ' dest ':  ' Use_reloader ',                          ' Required ': False,  ' Nargs ': 0,  ' choices ': none,                          ' default ': none,  ' prog ':  ' Hello.py runserver ',                          ' container ':  <argparse._ argumentgroup object at                         0x21dc150>,  ' type ':  none,   ' Metavar ': none}afe for                         production use)    -r, --no-reload       do not monitor Python files for changes#  The default is to listen localhost# python hello.py runserver --host 0.0.0.0 -p 80 *  running on http://0.0.0.0:80/


Resources
    • Comparison_of_web_application_frameworks

    • Flask Web Framework

    • Author Blog: http://my.oschina.net/u/1433482


Flask Web Development Note-Quick Start

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.