flask官方快速指南quickStart

2017-01-23  本文已影响603人  icewinde

Quickstart


http://flask.pocoo.org/docs/0.12/quickstart/ 


Quickstart

Eager to get started? This page gives a good introduction to Flask. It assumes you already have Flask installed. If you do not, head over to theInstallationsection.

A Minimal Application

A minimal Flask application looks something like this:

fromflaskimportFlaskapp=Flask(__name__)@app.route('/')defhello_world():return'Hello, World!'

So what did that code do?

First we imported theFlaskclass. An instance of this class will be our WSGI application.

Next we create an instance of this class. The first argument is the name of the application’s module or package. If you are using a single module (as in this example), you should use__name__because depending on if it’s started as application or imported as module the name will be different ('__main__'versus the actual import name). This is needed so that Flask knows where to look for templates, static files, and so on. For more information have a look at theFlaskdocumentation.

We then use theroute()decorator to tell Flask what URL should trigger our function.

The function is given a name which is also used to generate URLs for that particular function, and returns the message we want to display in the user’s browser.

Just save it ashello.pyor something similar. Make sure to not call your applicationflask.pybecause this would conflict with Flask itself.

To run the application you can either use theflaskcommand or python’s-mswitch with Flask. Before you can do that you need to tell your terminal the application to work with by exporting theFLASK_APPenvironment variable:

$ export FLASK_APP=hello.py$ flask run * Running on http://127.0.0.1:5000/

If you are on Windows you need to usesetinstead ofexport.

Alternatively you can usepython -m flask:

$ export FLASK_APP=hello.py$ python -m flask run * Running on http://127.0.0.1:5000/

This launches a very simple builtin server, which is good enough for testing but probably not what you want to use in production. For deployment options seeDeployment Options.

Now head over tohttp://127.0.0.1:5000/, and you should see your hello world greeting.

Externally Visible Server

If you run the server you will notice that the server is only accessible from your own computer, not from any other in the network. This is the default because in debugging mode a user of the application can execute arbitrary Python code on your computer.

If you have the debugger disabled or trust the users on your network, you can make the server publicly available simply by adding--host=0.0.0.0to the command line:

flaskrun--host=0.0.0.0

This tells your operating system to listen on all public IPs.

What to do if the Server does not Start

In case thepython -m flaskfails orflaskdoes not exist, there are multiple reasons this might be the case. First of all you need to look at the error message.

Old Version of Flask

Versions of Flask older than 0.11 use to have different ways to start the application. In short, theflaskcommand did not exist, and neither didpython -m flask. In that case you have two options: either upgrade to newer Flask versions or have a look at theDevelopment Serverdocs to see the alternative method for running a server.

Invalid Import Name

TheFLASK_APPenvironment variable is the name of the module to import atflask run. In case that module is incorrectly named you will get an import error upon start (or if debug is enabled when you navigate to the application). It will tell you what it tried to import and why it failed.

The most common reason is a typo or because you did not actually create anappobject.

Debug Mode

(Want to just log errors and stack traces? SeeApplication Errors)

Theflaskscript is nice to start a local development server, but you would have to restart it manually after each change to your code. That is not very nice and Flask can do better. If you enable debug support the server will reload itself on code changes, and it will also provide you with a helpful debugger if things go wrong.

To enable debug mode you can export theFLASK_DEBUGenvironment variable before running the server:

$ export FLASK_DEBUG=1$ flask run

(On Windows you need to usesetinstead ofexport).

This does the following things:

it activates the debugger

it activates the automatic reloader

it enables the debug mode on the Flask application.

There are more parameters that are explained in theDevelopment Serverdocs.

Attention

Even though the interactive debugger does not work in forking environments (which makes it nearly impossible to use on production servers), it still allows the execution of arbitrary code. This makes it a major security risk and therefore itmust never be used on production machines.

Screenshot of the debugger in action:

Have another debugger in mind? SeeWorking with Debuggers.

Routing

Modern web applications have beautiful URLs. This helps people remember the URLs, which is especially handy for applications that are used from mobile devices with slower network connections. If the user can directly go to the desired page without having to hit the index page it is more likely they will like the page and come back next time.

As you have seen above, theroute()decorator is used to bind a function to a URL. Here are some basic examples:

@app.route('/')defindex():return'Index Page'@app.route('/hello')defhello():return'Hello, World'

But there is more to it! You can make certain parts of the URL dynamic and attach multiple rules to a function.

Variable Rules

To add variable parts to a URL you can mark these special sections as. Such a part is then passed as a keyword argument to your function. Optionally a converter can be used by specifying a rule with. Here are some nice examples:

@app.route('/user/')defshow_user_profile(username):# show the user profile for that userreturn'User%s'%username@app.route('/post/')defshow_post(post_id):# show the post with the given id, the id is an integerreturn'Post%d'%post_id

The following converters exist:

stringaccepts any text without a slash (the default)

intaccepts integers

floatlikeintbut for floating point values

pathlike the default but also accepts slashes

anymatches one of the items provided

uuidaccepts UUID strings

Unique URLs / Redirection Behavior

Flask’s URL rules are based on Werkzeug’s routing module. The idea behind that module is to ensure beautiful and unique URLs based on precedents laid down by Apache and earlier HTTP servers.

Take these two rules:

@app.route('/projects/')defprojects():return'The project page'@app.route('/about')defabout():return'The about page'

Though they look rather similar, they differ in their use of the trailing slash in the URLdefinition. In the first case, the canonical URL for theprojectsendpoint has a trailing slash. In that sense, it is similar to a folder on a filesystem. Accessing it without a trailing slash will cause Flask to redirect to the canonical URL with the trailing slash.

In the second case, however, the URL is defined without a trailing slash, rather like the pathname of a file on UNIX-like systems. Accessing the URL with a trailing slash will produce a 404 “Not Found” error.

This behavior allows relative URLs to continue working even if the trailing slash is omitted, consistent with how Apache and other servers work. Also, the URLs will stay unique, which helps search engines avoid indexing the same page twice.

URL Building

If it can match URLs, can Flask also generate them? Of course it can. To build a URL to a specific function you can use theurl_for()function. It accepts the name of the function as first argument and a number of keyword arguments, each corresponding to the variable part of the URL rule. Unknown variable parts are appended to the URL as query parameters. Here are some examples:

>>>fromflaskimportFlask,url_for>>>app=Flask(__name__)>>>@app.route('/')...defindex():pass...>>>@app.route('/login')...deflogin():pass...>>>@app.route('/user/')...defprofile(username):pass...>>>withapp.test_request_context():...printurl_for('index')...printurl_for('login')...printurl_for('login',next='/')...printurl_for('profile',username='John Doe')...//login/login?next=//user/John%20Doe

(This also uses thetest_request_context()method, explained below. It tells Flask to behave as though it is handling a request, even though we are interacting with it through a Python shell. Have a look at the explanation below.Context Locals).

Why would you want to build URLs using the URL reversing functionurl_for()instead of hard-coding them into your templates? There are three good reasons for this:

Reversing is often more descriptive than hard-coding the URLs. More importantly, it allows you to change URLs in one go, without having to remember to change URLs all over the place.

URL building will handle escaping of special characters and Unicode data transparently for you, so you don’t have to deal with them.

If your application is placed outside the URL root - say, in/myapplicationinstead of/-url_for()will handle that properly for you.

HTTP Methods

HTTP (the protocol web applications are speaking) knows different methods for accessing URLs. By default, a route only answers toGETrequests, but that can be changed by providing themethodsargument to theroute()decorator. Here are some examples:

fromflaskimportrequest@app.route('/login',methods=['GET','POST'])deflogin():ifrequest.method=='POST':do_the_login()else:show_the_login_form()

IfGETis present,HEADwill be added automatically for you. You don’t have to deal with that. It will also make sure thatHEADrequests are handled as theHTTP RFC(the document describing the HTTP protocol) demands, so you can completely ignore that part of the HTTP specification. Likewise, as of Flask 0.6,OPTIONSis implemented for you automatically as well.

You have no idea what an HTTP method is? Worry not, here is a quick introduction to HTTP methods and why they matter:

The HTTP method (also often called “the verb”) tells the server what the client wants todowith the requested page. The following methods are very common:

GET

The browser tells the server to justgetthe information stored on that page and send it. This is probably the most common method.

HEAD

The browser tells the server to get the information, but it is only interested in theheaders, not the content of the page. An application is supposed to handle that as if aGETrequest was received but to not deliver the actual content. In Flask you don’t have to deal with that at all, the underlying Werkzeug library handles that for you.

POST

The browser tells the server that it wants topostsome new information to that URL and that the server must ensure the data is stored and only stored once. This is how HTML forms usually transmit data to the server.

PUT

Similar toPOSTbut the server might trigger the store procedure multiple times by overwriting the old values more than once. Now you might be asking why this is useful, but there are some good reasons to do it this way. Consider that the connection is lost during transmission: in this situation a system between the browser and the server might receive the request safely a second time without breaking things. WithPOSTthat would not be possible because it must only be triggered once.

DELETE

Remove the information at the given location.

OPTIONS

Provides a quick way for a client to figure out which methods are supported by this URL. Starting with Flask 0.6, this is implemented for you automatically.

Now the interesting part is that in HTML4 and XHTML1, the only methods a form can submit to the server areGETandPOST. But with JavaScript and future HTML standards you can use the other methods as well. Furthermore HTTP has become quite popular lately and browsers are no longer the only clients that are using HTTP. For instance, many revision control systems use it.

Static Files

Dynamic web applications also need static files. That’s usually where the CSS and JavaScript files are coming from. Ideally your web server is configured to serve them for you, but during development Flask can do that as well. Just create a folder calledstaticin your package or next to your module and it will be available at/staticon the application.

To generate URLs for static files, use the special'static'endpoint name:

url_for('static',filename='style.css')

The file has to be stored on the filesystem asstatic/style.css.

Rendering Templates

Generating HTML from within Python is not fun, and actually pretty cumbersome because you have to do the HTML escaping on your own to keep the application secure. Because of that Flask configures theJinja2template engine for you automatically.

To render a template you can use therender_template()method. All you have to do is provide the name of the template and the variables you want to pass to the template engine as keyword arguments. Here’s a simple example of how to render a template:

fromflaskimportrender_template@app.route('/hello/')@app.route('/hello/')defhello(name=None):returnrender_template('hello.html',name=name)

Flask will look for templates in thetemplatesfolder. So if your application is a module, this folder is next to that module, if it’s a package it’s actually inside your package:

Case 1: a module:

/application.py/templates/hello.html

Case 2: a package:

/application/__init__.py/templates/hello.html

For templates you can use the full power of Jinja2 templates. Head over to the officialJinja2 Template Documentationfor more information.

Here is an example template:

Hello from Flask{%ifname%}

Hello{{name}}!

{%else%}

Hello, World!

{%endif%}

Inside templates you also have access to therequest,sessionandg[1]objects as well as theget_flashed_messages()function.

Templates are especially useful if inheritance is used. If you want to know how that works, head over to theTemplate Inheritancepattern documentation. Basically template inheritance makes it possible to keep certain elements on each page (like header, navigation and footer).

Automatic escaping is enabled, so ifnamecontains HTML it will be escaped automatically. If you can trust a variable and you know that it will be safe HTML (for example because it came from a module that converts wiki markup to HTML) you can mark it as safe by using theMarkupclass or by using the|safefilter in the template. Head over to the Jinja 2 documentation for more examples.

Here is a basic introduction to how theMarkupclass works:

>>>fromflaskimportMarkup>>>Markup('Hello%s!')%'hacker'Markup(u'Hello <blink>hacker</blink>!')>>>Markup.escape('hacker')Markup(u'<blink>hacker</blink>')>>>Markup('Marked up » HTML').striptags()u'Marked up \xbb HTML'

Changed in version 0.5:Autoescaping is no longer enabled for all templates. The following extensions for templates trigger autoescaping:.html,.htm,.xml,.xhtml. Templates loaded from a string will have autoescaping disabled.

[1]Unsure what thatgobject is? It’s something in which you can store information for your own needs, check the documentation of that object (g) and theUsing SQLite 3 with Flaskfor more information.

Accessing Request Data

For web applications it’s crucial to react to the data a client sends to the server. In Flask this information is provided by the globalrequestobject. If you have some experience with Python you might be wondering how that object can be global and how Flask manages to still be threadsafe. The answer is context locals:

Context Locals

Insider Information

If you want to understand how that works and how you can implement tests with context locals, read this section, otherwise just skip it.

Certain objects in Flask are global objects, but not of the usual kind. These objects are actually proxies to objects that are local to a specific context. What a mouthful. But that is actually quite easy to understand.

Imagine the context being the handling thread. A request comes in and the web server decides to spawn a new thread (or something else, the underlying object is capable of dealing with concurrency systems other than threads). When Flask starts its internal request handling it figures out that the current thread is the active context and binds the current application and the WSGI environments to that context (thread). It does that in an intelligent way so that one application can invoke another application without breaking.

So what does this mean to you? Basically you can completely ignore that this is the case unless you are doing something like unit testing. You will notice that code which depends on a request object will suddenly break because there is no request object. The solution is creating a request object yourself and binding it to the context. The easiest solution for unit testing is to use thetest_request_context()context manager. In combination with thewithstatement it will bind a test request so that you can interact with it. Here is an example:

fromflaskimportrequestwithapp.test_request_context('/hello',method='POST'):# now you can do something with the request until the# end of the with block, such as basic assertions:assertrequest.path=='/hello'assertrequest.method=='POST'

The other possibility is passing a whole WSGI environment to therequest_context()method:

fromflaskimportrequestwithapp.request_context(environ):assertrequest.method=='POST'

The Request Object

The request object is documented in the API section and we will not cover it here in detail (seerequest). Here is a broad overview of some of the most common operations. First of all you have to import it from theflaskmodule:

fromflaskimportrequest

The current request method is available by using themethodattribute. To access form data (data transmitted in aPOSTorPUTrequest) you can use theformattribute. Here is a full example of the two attributes mentioned above:

@app.route('/login',methods=['POST','GET'])deflogin():error=Noneifrequest.method=='POST':ifvalid_login(request.form['username'],request.form['password']):returnlog_the_user_in(request.form['username'])else:error='Invalid username/password'# the code below is executed if the request method# was GET or the credentials were invalidreturnrender_template('login.html',error=error)

What happens if the key does not exist in theformattribute? In that case a specialKeyErroris raised. You can catch it like a standardKeyErrorbut if you don’t do that, a HTTP 400 Bad Request error page is shown instead. So for many situations you don’t have to deal with that problem.

To access parameters submitted in the URL (?key=value) you can use theargsattribute:

searchword=request.args.get('key','')

We recommend accessing URL parameters withgetor by catching theKeyErrorbecause users might change the URL and presenting them a 400 bad request page in that case is not user friendly.

For a full list of methods and attributes of the request object, head over to therequestdocumentation.

File Uploads

You can handle uploaded files with Flask easily. Just make sure not to forget to set theenctype="multipart/form-data"attribute on your HTML form, otherwise the browser will not transmit your files at all.

Uploaded files are stored in memory or at a temporary location on the filesystem. You can access those files by looking at thefilesattribute on the request object. Each uploaded file is stored in that dictionary. It behaves just like a standard Pythonfileobject, but it also has asave()method that allows you to store that file on the filesystem of the server. Here is a simple example showing how that works:

fromflaskimportrequest@app.route('/upload',methods=['GET','POST'])defupload_file():ifrequest.method=='POST':f=request.files['the_file']f.save('/var/www/uploads/uploaded_file.txt')...

If you want to know how the file was named on the client before it was uploaded to your application, you can access thefilenameattribute. However please keep in mind that this value can be forged so never ever trust that value. If you want to use the filename of the client to store the file on the server, pass it through thesecure_filename()function that Werkzeug provides for you:

fromflaskimportrequestfromwerkzeug.utilsimportsecure_filename@app.route('/upload',methods=['GET','POST'])defupload_file():ifrequest.method=='POST':f=request.files['the_file']f.save('/var/www/uploads/'+secure_filename(f.filename))...

For some better examples, checkout theUploading Filespattern.

Cookies

To access cookies you can use thecookiesattribute. To set cookies you can use theset_cookiemethod of response objects. Thecookiesattribute of request objects is a dictionary with all the cookies the client transmits. If you want to use sessions, do not use the cookies directly but instead use theSessionsin Flask that add some security on top of cookies for you.

Reading cookies:

fromflaskimportrequest@app.route('/')defindex():username=request.cookies.get('username')# use cookies.get(key) instead of cookies[key] to not get a# KeyError if the cookie is missing.

Storing cookies:

fromflaskimportmake_response@app.route('/')defindex():resp=make_response(render_template(...))resp.set_cookie('username','the username')returnresp

Note that cookies are set on response objects. Since you normally just return strings from the view functions Flask will convert them into response objects for you. If you explicitly want to do that you can use themake_response()function and then modify it.

Sometimes you might want to set a cookie at a point where the response object does not exist yet. This is possible by utilizing theDeferred Request Callbackspattern.

For this also seeAbout Responses.

Redirects and Errors

To redirect a user to another endpoint, use theredirect()function; to abort a request early with an error code, use theabort()function:

fromflaskimportabort,redirect,url_for@app.route('/')defindex():returnredirect(url_for('login'))@app.route('/login')deflogin():abort(401)this_is_never_executed()

This is a rather pointless example because a user will be redirected from the index to a page they cannot access (401 means access denied) but it shows how that works.

By default a black and white error page is shown for each error code. If you want to customize the error page, you can use theerrorhandler()decorator:

fromflaskimportrender_template@app.errorhandler(404)defpage_not_found(error):returnrender_template('page_not_found.html'),404

Note the404after therender_template()call. This tells Flask that the status code of that page should be 404 which means not found. By default 200 is assumed which translates to: all went well.

SeeError handlersfor more details.

About Responses

The return value from a view function is automatically converted into a response object for you. If the return value is a string it’s converted into a response object with the string as response body, a200OKstatus code and atext/htmlmimetype. The logic that Flask applies to converting return values into response objects is as follows:

If a response object of the correct type is returned it’s directly returned from the view.

If it’s a string, a response object is created with that data and the default parameters.

If a tuple is returned the items in the tuple can provide extra information. Such tuples have to be in the form(response,status,headers)or(response,headers)where at least one item has to be in the tuple. Thestatusvalue will override the status code andheaderscan be a list or dictionary of additional header values.

If none of that works, Flask will assume the return value is a valid WSGI application and convert that into a response object.

If you want to get hold of the resulting response object inside the view you can use themake_response()function.

Imagine you have a view like this:

@app.errorhandler(404)defnot_found(error):returnrender_template('error.html'),404

You just need to wrap the return expression withmake_response()and get the response object to modify it, then return it:

@app.errorhandler(404)defnot_found(error):resp=make_response(render_template('error.html'),404)resp.headers['X-Something']='A value'returnresp

Sessions

In addition to the request object there is also a second object calledsessionwhich allows you to store information specific to a user from one request to the next. This is implemented on top of cookies for you and signs the cookies cryptographically. What this means is that the user could look at the contents of your cookie but not modify it, unless they know the secret key used for signing.

In order to use sessions you have to set a secret key. Here is how sessions work:

fromflaskimportFlask,session,redirect,url_for,escape,requestapp=Flask(__name__)@app.route('/')defindex():if'username'insession:return'Logged in as%s'%escape(session['username'])return'You are not logged in'@app.route('/login',methods=['GET','POST'])deflogin():ifrequest.method=='POST':session['username']=request.form['username']returnredirect(url_for('index'))return'''

'''@app.route('/logout')deflogout():# remove the username from the session if it's theresession.pop('username',None)returnredirect(url_for('index'))# set the secret key.  keep this really secret:app.secret_key='A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'

Theescape()mentioned here does escaping for you if you are not using the template engine (as in this example).

How to generate good secret keys

The problem with random is that it’s hard to judge what is truly random. And a secret key should be as random as possible. Your operating system has ways to generate pretty random stuff based on a cryptographic random generator which can be used to get such a key:

>>>importos>>>os.urandom(24)'\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O

A note on cookie-based sessions: Flask will take the values you put into the session object and serialize them into a cookie. If you are finding some values do not persist across requests, cookies are indeed enabled, and you are not getting a clear error message, check the size of the cookie in your page responses compared to the size supported by web browsers.

Besides the default client-side based sessions, if you want to handle sessions on the server-side instead, there are several Flask extensions that support this.

Message Flashing

Good applications and user interfaces are all about feedback. If the user does not get enough feedback they will probably end up hating the application. Flask provides a really simple way to give feedback to a user with the flashing system. The flashing system basically makes it possible to record a message at the end of a request and access it on the next (and only the next) request. This is usually combined with a layout template to expose the message.

To flash a message use theflash()method, to get hold of the messages you can useget_flashed_messages()which is also available in the templates. Check out theMessage Flashingfor a full example.

Logging

New in version 0.3.

Sometimes you might be in a situation where you deal with data that should be correct, but actually is not. For example you may have some client-side code that sends an HTTP request to the server but it’s obviously malformed. This might be caused by a user tampering with the data, or the client code failing. Most of the time it’s okay to reply with400BadRequestin that situation, but sometimes that won’t do and the code has to continue working.

You may still want to log that something fishy happened. This is where loggers come in handy. As of Flask 0.3 a logger is preconfigured for you to use.

Here are some example log calls:

app.logger.debug('A value for debugging')app.logger.warning('A warning occurred (%dapples)',42)app.logger.error('An error occurred')

The attachedloggeris a standard loggingLogger, so head over to the officiallogging documentationfor more information.

Read more onApplication Errors.

Hooking in WSGI Middlewares

If you want to add a WSGI middleware to your application you can wrap the internal WSGI application. For example if you want to use one of the middlewares from the Werkzeug package to work around bugs in lighttpd, you can do it like this:

fromwerkzeug.contrib.fixersimportLighttpdCGIRootFixapp.wsgi_app=LighttpdCGIRootFix(app.wsgi_app)

Using Flask Extensions

Extensions are packages that help you accomplish common tasks. For example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple and easy to use with Flask.

For more on Flask extensions, have a look atFlask Extensions.

Deploying to a Web Server

Ready to deploy your new Flask app? Go toDeployment Options.

上一篇下一篇

猜你喜欢

热点阅读