Skip to content
Myr

Updated documentation. Starting to look pretty good

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent 3b36bef · Browse files · 6 files+359 added−4 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+359 added−4 removed

  • other:+359 added−4 removed

6 files+359 added−4 removed

modified:docs/api.rst+20 added
66 unmodified lines
67 standard file object you know from Python, with the difference that68 it also has a :meth:`~werkzeug.FileStorage.save` function that can69 store the file on the filesystem.7071 .. attribute:: environ7273 The underlying WSGI environment.7475 .. attribute:: method7677 The current request method (``POST``, ``GET`` etc.)78
60 unmodified lines
139 # so mark it as modified yourself140 session.modified = True141142143Application Globals144-------------------145146To share data that is valid for one request only from one function to147another, a global variable is not good enough because it would break in148threaded environments. Flask provides you with a special object that149ensures it is only valid for the active request and that will return150different values for each request. In a nutshell: it does the right151thing, like it does for :class:`request` and :class:`session`.152153.. data:: g154 155 Just store on this whatever you want. For example a database156 connection or the user that is currently logged in.157158159Useful Functions and Classes160----------------------------161162.. autofunction:: url_for
23 unmodified lines
modified:docs/index.rst+2 added
6 unmodified lines
78.. toctree::9 :maxdepth: 21011 installation12 quickstart13 api
added:docs/installation.rst+6 added
1.. _installation:23Installation4============56Blafasel, add me
added:docs/quickstart.rst+312 added
1Quickstart2==========34Eager to get started? This page gives a good introduction in how to gets5started with Flask. This assumes you already have Flask installed. If6you do not, head over to the :ref:`installation` section.789A Minimal Application10---------------------1112A minimal Flask application looks something like that::1314 from flask import Flask15 app = Flask(__name__)1617 @app.route('/')18 def hello_world():19 return "Hello World!"2021 if __name__ == '__main__':22 app.run()2324If you now start that application with your Python interpreter and head25over to `http://localhost:5000/ <http://localhost:5000/>`_, you should see26your hello world application.2728So what did that code do?29301. first we imported the :class:`~flask.Flask` class. An instance of this31 class will be our WSGI application.322. next we create an instance of it. We pass it the name of the module /33 package. This is needed so that Flask knows where it should look for34 templates, static files and so on.353. Then we use the :meth:`~flask.Flask.route` decorator to tell Flask36 what URL should trigger our function.374. The function then has a name which is also used to generate URLs to38 that particular function, and returns the message we want to display in39 the user's browser.405. Finally we use the :meth:`~flask.Flask.run` function to run the41 local server with our application. The ``if __name__ == '__main__':``42 makes sure the server only runs if the script is executed directly from43 the Python interpreter and not used as imported module.444546Routing47-------4849As you have seen above, the :meth:`~flask.Flask.route` decorator is used50to bind a function to a URL. But there is more to it! You can make51certain parts of the URL dynamic and attach multiple rules to a function.5253Here some examples::5455 @app.route('/')56 def index():57 return 'Index Page'5859 @app.route('/hello')60 def hello():61 return 'Hello World'626364Variable Rules65``````````````6667Modern web applications have beautiful URLs. This helps people remember68the URLs which is especially handy for applications that are used from69mobile devices with slower network connections. If the user can directly70go to the desired page without having to hit the index page it is more71likely he will like the page and come back next time.7273To add variable parts to a URL you can mark these special sections as74``<variable_name>``. Such a part is then passed as keyword argument to75your function. Optionally a converter can be specifed by specifying a76rule with ``<converter:variable_name>``. Here some nice examples::7778 @app.route('/user/<username>')79 def show_user_profile(username):80 # show the user profile for that user81 pass8283 @app.route('/post/<int:post_id>')84 def show_post(post_id):85 # show the post with the given id, the id is an integer86 pass8788The following converters exist:8990=========== ===========================================91`int` accepts integers92`float` like `int` but for floating point values93`path` like the default but also accepts slashes94=========== ===========================================959697HTTP Methods98````````````99100HTTP knows different methods to access URLs. By default a route only101answers to ``GET`` requests, but that can be changed by providing the102`methods` argument to the :meth:`~flask.Flask.route` decorator. Here some103examples::104105 @app.route('/login', methods=['GET', 'POST'])106 def login():107 if request.method == 'POST':108 do_the_login()109 else:110 show_the_login_form()111112If ``GET`` is present, ``HEAD`` will be added automatically for you. You113don't have to deal with that. It will also make sure that ``HEAD``114requests are handled like the RFC demands, so you can completely ignore115that part of the HTTP specification.116117118Accessing Request Data119----------------------120121For web applications it's crucial to react to the data a client sent to122the server. In Flask this information is provided by the global123:class:`~flask.request` object. If you have some experience with Python124you might be wondering how that object can be global and how Flask125manages to still be threadsafe. The answer are context locals:126127Context Locals128``````````````129130.. admonition:: Insider Information131132 If you want to understand how that works and how you can implement133 tests with context locals, read this section, otherwise just skip it.134135Certain objects in Flask are global objects, but not just a standard136global object, but actually a proxy to an object that is local to a137specific context. What a mouthful. But that is actually quite easy to138understand.139140Imagine the context being the handling thread. A request comes in and the141webserver decides to spawn a new thread (or something else, the142underlying object is capable of dealing with other concurrency systems143than threads as well). When Flask starts its internal request handling it144figures out that the current thread is the active context and binds the145current application and the WSGI environments to that context (thread).146It does that in an intelligent way that one application can invoke another147application without breaking.148149So what does this mean to you? Basically you can completely ignore that150this is the case unless you are unittesting or something different. You151will notice that code that depends on a request object will suddenly break152because there is no request object. The solution is creating a request153object yourself and binding it to the context. The easiest solution for154unittesting is by using the :meth:`~flask.Flask.test_request_context`155context manager. In combination with the `with` statement it will bind a156test request so that you can interact with it. Here an example::157158 from flask import request159160 with app.test_request_context('/hello', method='POST'):161 # now you can do something with the request until the162 # end of the with block, such as basic assertions:163 assert request.path == '/hello'164 assert request.method == 'POST'165166The other possibility is passing a whole WSGI environment to the167:meth:`~flask.Flask.request_context` method::168169 from flask import request170171 with app.request_context(environ):172 assert request.method == 'POST'173174The Request Object175``````````````````176177The request object is documented in the API section and we will not cover178it here in detail (see :class:`~flask.request`), but just mention some of179the most common operations. First of all you have to import it from the180the `flask` module::181182 from flask import request183184The current request method is available by using the185:attr:`~flask.request.method` attribute. To access form data (data186transmitted in a `POST` or `PUT` request) you can use the187:attr:`~flask.request.form` attribute. Here a full example of the two188attributes mentioned above::189190 @app.route('/login', method=['POST', 'GET'])191 def login():192 error = None193 if request.method == 'POST':194 if valid_login(request.form['username'],195 request.form['password']):196 return log_the_user_in(request.form['username'])197 else:198 error = 'Invalid username/password'199 # this is executed if the request method was GET or the200 # credentials were invalid201202What happens if the key does not exist in the `form` attribute? In that203case a special :exc:`KeyError` is raised. You can catch it like a204standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request205error page is shown instead. So for many situations you don't have to206deal with that problem.207208To access parameters submitted in the URL (``?key=value``) you can use the209:attr:`~flask.request.args` attribute::210211 searchword = request.args.get('q', '')212213We recommend accessing URL parameters with `get` or by catching the214`KeyError` because users might change the URL and presenting them a 400215bad request page in that case is a bit user unfriendly.216217For a full list of methods and attribtues on that object, head over to the218:class:`~flask.request` documentation.219220221File Uploads222````````````223224Obviously you can handle uploaded files with Flask just as easy. Just225make sure not to forget to set the ``enctype="multipart/form-data"``226attribtue on your HTML form, otherwise the browser will not transmit your227files at all.228229Uploaded files are stored in memory or at a temporary location on the230filesystem. You can access those files by looking at the231:attr:`~flask.request.files` attribute on the request object. Each232uploaded file is stored in that dictionary. It behaves just like a233standard Python :class:`file` object, but it also has a234:meth:`~werkzeug.FileStorage.save` method that allows you to store that235file on the filesystem of the server. Here a simple example how that236works::237238 from flask import request239240 @app.route('/upload', methods=['GET', 'POST'])241 def upload_file():242 if request.method == 'POST':243 f = request.files['the_file']244 f.save('/var/www/uploads/uploaded_file.txt')245 ...246247If you want to know how the file was named on the client before it was248uploaded to your application, you can access the249:attr:`~werkzeug.FileStorage.filename` attribute. However please keep in250mind that this value can be forged so never ever trust that value. If you251want to use the filename of the client to store the file on the server,252pass it through the :func:`~werkzeug.secure_filename` function that253Werkzeug provides for you::254255 from flask import request256 from werkzeug import secure_filename257258 @app.route('/upload', methods=['GET', 'POST'])259 def upload_file():260 if request.method == 'POST':261 f= request.files['the_file']262 f.save('/var/www/uploads/' + secure_filename(f.filename))263 ...264265Cookies266```````267268To access cookies you can use the :attr:`~flask.request.cookies`269attribute. Again this is a dictionary with all the cookies the client270transmits. If you want to use sessions, do not use the cookies directly271but instead use the :ref:`sessions` in Flask that add some security on top272of cookies for you.273274.. _sessions:275276Sessions277--------278279Besides the request object there is also a second object called280:class:`~flask.session` that allows you to store information specific to a281user from one request to the next. This is implemented on top of cookies282for you and signes the cookies cryptographically. What this means is that283the user could look at the contents of your cookie but not modify it,284unless he knows the secret key used for signing.285286In order to use sessions you have to set a secret key. Here is how287sessions work::288289 from flask import session, redirect, url_for, escape290291 @app.route('/')292 def index():293 if 'username' in session:294 return 'Logged in as %s' % escape(session['username'])295 return 'You are not logged in'296297 @app.route('/login', methods=['GET', 'POST'])298 def login():299 if request.method == 'POST':300 session['username'] = request.form['username']301 return redirect(url_for('index'))302 return '''303 <form action="" method="post">304 <p><input type=text name=username>305 <p><input type=submit value=Login>306 </form>307 '''308309 @app.route('/logout')310 def logout():311 # remove the username from the session if its there312 session.pop('username', None)
modified:examples/minitwit/minitwit.py+3 added-3 removed
146 unmodified lines
147 flash('You are no longer following "%s"' % username)148 return redirect(url_for('user_timeline', username=username))149150151@app.route('/add_message')151@app.route('/add_message', methods=['POST'])152def add_message():153 if 'user_id' not in session:154 abort(401)155 if request.form['text']:
4 unmodified lines
160 flash('Your message was recorded')161 return redirect(url_for('timeline'))162163164@app.route('/login')164@app.route('/login', methods=['GET', 'POST'])165def login():166 if 'user_id' in session:167 return redirect(url_for('timeline'))168 error = None
11 unmodified lines
180 return redirect(url_for('timeline'))181 return render_template('login.html', error=error)182183184@app.route('/register')184@app.route('/register', methods=['GET', 'POST'])185def register():186 if 'user_id' in session:187 return redirect(url_for('timeline'))188 error = None
40 unmodified lines
modified:flask.py+16 added-1 removed
324 unmodified lines
325 @app.route('/post/<int:post_id>')326 def show_post(post_id):327 pass328329 An important detail to keep in mind is how Flask deals with trailing330 slashes. The idea is to keep each URL unique so the following rules331 apply:332333 1. If a rule ends with a slash and is requested without a slash334 by the user, the user is automatically redirected to the same335 page with a trailing slash attached.336 2. If a rule does not end with a trailing slash and the user request337 the page with a trailing slash, a 404 not found is raised.338339 This is consistent with how web servers deal with static files. This340 also makes it possible to use relative link targets safely.341342 The :meth:`route` decorator accepts a couple of other arguments343 as well:344345 :param methods: a list of methods this rule should be limited333 to (``GET``, ``POST`` etc.)346 to (``GET``, ``POST`` etc.). By default a rule347 just listens for ``GET`` (and implicitly ``HEAD``).348 :param subdomain: specifies the rule for the subdoain in case349 subdomain matching is in use.350 :param strict_slashes: can be used to disable the strict slashes351 setting for this rule. See above.352 """353 def decorator(f):354 if 'endpoint' not in options:355 options['endpoint'] = f.__name__356 options.setdefault('methods', ('GET',))357 self.url_map.add(Rule(rule, **options))358 self.view_functions[options['endpoint']] = f359 return f360 return decorator
137 unmodified lines