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
Provenance
- Commit
4aa7621- Tree
191ecd4- Author
Armin Ronacher <mitsuhiko@nausicaa.local>- Committer
Armin Ronacher <mitsuhiko@nausicaa.local>- Parent
3b36bef
6 files changed+359 added−4 removed
modified:docs/api.rst+20 added
66 unmodified lines67 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.70 71+ .. attribute:: environ72+73+ The underlying WSGI environment.74+75 .. attribute:: method76 77 The current request method (``POST``, ``GET`` etc.)78 60 unmodified lines139 # so mark it as modified yourself140 session.modified = True141 142 143+Application Globals144+-------------------145+146+To share data that is valid for one request only from one function to147+another, a global variable is not good enough because it would break in148+threaded environments. Flask provides you with a special object that149+ensures it is only valid for the active request and that will return150+different values for each request. In a nutshell: it does the right151+thing, like it does for :class:`request` and :class:`session`.152+153+.. data:: g154+ 155+ Just store on this whatever you want. For example a database156+ connection or the user that is currently logged in.157+158+159 Useful Functions and Classes160 ----------------------------161 162 .. autofunction:: url_for23 unmodified linesmodified:docs/index.rst+2 added
6 unmodified lines7 8 .. toctree::9 :maxdepth: 210 11+ installation12+ quickstart13 apiadded:docs/installation.rst+6 added
1+.. _installation:2+3+Installation4+============5+6+Blafasel, add meadded:docs/quickstart.rst+312 added
1+Quickstart2+==========3+4+Eager to get started? This page gives a good introduction in how to gets5+started with Flask. This assumes you already have Flask installed. If6+you do not, head over to the :ref:`installation` section.7+8+9+A Minimal Application10+---------------------11+12+A minimal Flask application looks something like that::13+14+ from flask import Flask15+ app = Flask(__name__)16+17+ @app.route('/')18+ def hello_world():19+ return "Hello World!"20+21+ if __name__ == '__main__':22+ app.run()23+24+If you now start that application with your Python interpreter and head25+over to `http://localhost:5000/ <http://localhost:5000/>`_, you should see26+your hello world application.27+28+So what did that code do?29+30+1. first we imported the :class:`~flask.Flask` class. An instance of this31+ class will be our WSGI application.32+2. 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.35+3. Then we use the :meth:`~flask.Flask.route` decorator to tell Flask36+ what URL should trigger our function.37+4. 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.40+5. 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.44+45+46+Routing47+-------48+49+As you have seen above, the :meth:`~flask.Flask.route` decorator is used50+to bind a function to a URL. But there is more to it! You can make51+certain parts of the URL dynamic and attach multiple rules to a function.52+53+Here some examples::54+55+ @app.route('/')56+ def index():57+ return 'Index Page'58+59+ @app.route('/hello')60+ def hello():61+ return 'Hello World'62+63+64+Variable Rules65+``````````````66+67+Modern web applications have beautiful URLs. This helps people remember68+the URLs which is especially handy for applications that are used from69+mobile devices with slower network connections. If the user can directly70+go to the desired page without having to hit the index page it is more71+likely he will like the page and come back next time.72+73+To add variable parts to a URL you can mark these special sections as74+``<variable_name>``. Such a part is then passed as keyword argument to75+your function. Optionally a converter can be specifed by specifying a76+rule with ``<converter:variable_name>``. Here some nice examples::77+78+ @app.route('/user/<username>')79+ def show_user_profile(username):80+ # show the user profile for that user81+ pass82+83+ @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+ pass87+88+The following converters exist:89+90+=========== ===========================================91+`int` accepts integers92+`float` like `int` but for floating point values93+`path` like the default but also accepts slashes94+=========== ===========================================95+96+97+HTTP Methods98+````````````99+100+HTTP knows different methods to access URLs. By default a route only101+answers to ``GET`` requests, but that can be changed by providing the102+`methods` argument to the :meth:`~flask.Flask.route` decorator. Here some103+examples::104+105+ @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()111+112+If ``GET`` is present, ``HEAD`` will be added automatically for you. You113+don't have to deal with that. It will also make sure that ``HEAD``114+requests are handled like the RFC demands, so you can completely ignore115+that part of the HTTP specification.116+117+118+Accessing Request Data119+----------------------120+121+For web applications it's crucial to react to the data a client sent to122+the server. In Flask this information is provided by the global123+:class:`~flask.request` object. If you have some experience with Python124+you might be wondering how that object can be global and how Flask125+manages to still be threadsafe. The answer are context locals:126+127+Context Locals128+``````````````129+130+.. admonition:: Insider Information131+132+ If you want to understand how that works and how you can implement133+ tests with context locals, read this section, otherwise just skip it.134+135+Certain objects in Flask are global objects, but not just a standard136+global object, but actually a proxy to an object that is local to a137+specific context. What a mouthful. But that is actually quite easy to138+understand.139+140+Imagine the context being the handling thread. A request comes in and the141+webserver decides to spawn a new thread (or something else, the142+underlying object is capable of dealing with other concurrency systems143+than threads as well). When Flask starts its internal request handling it144+figures out that the current thread is the active context and binds the145+current application and the WSGI environments to that context (thread).146+It does that in an intelligent way that one application can invoke another147+application without breaking.148+149+So what does this mean to you? Basically you can completely ignore that150+this is the case unless you are unittesting or something different. You151+will notice that code that depends on a request object will suddenly break152+because there is no request object. The solution is creating a request153+object yourself and binding it to the context. The easiest solution for154+unittesting is by using the :meth:`~flask.Flask.test_request_context`155+context manager. In combination with the `with` statement it will bind a156+test request so that you can interact with it. Here an example::157+158+ from flask import request159+160+ 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'165+166+The other possibility is passing a whole WSGI environment to the167+:meth:`~flask.Flask.request_context` method::168+169+ from flask import request170+171+ with app.request_context(environ):172+ assert request.method == 'POST'173+174+The Request Object175+``````````````````176+177+The request object is documented in the API section and we will not cover178+it here in detail (see :class:`~flask.request`), but just mention some of179+the most common operations. First of all you have to import it from the180+the `flask` module::181+182+ from flask import request183+184+The current request method is available by using the185+:attr:`~flask.request.method` attribute. To access form data (data186+transmitted in a `POST` or `PUT` request) you can use the187+:attr:`~flask.request.form` attribute. Here a full example of the two188+attributes mentioned above::189+190+ @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 invalid201+202+What happens if the key does not exist in the `form` attribute? In that203+case a special :exc:`KeyError` is raised. You can catch it like a204+standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request205+error page is shown instead. So for many situations you don't have to206+deal with that problem.207+208+To access parameters submitted in the URL (``?key=value``) you can use the209+:attr:`~flask.request.args` attribute::210+211+ searchword = request.args.get('q', '')212+213+We recommend accessing URL parameters with `get` or by catching the214+`KeyError` because users might change the URL and presenting them a 400215+bad request page in that case is a bit user unfriendly.216+217+For a full list of methods and attribtues on that object, head over to the218+:class:`~flask.request` documentation.219+220+221+File Uploads222+````````````223+224+Obviously you can handle uploaded files with Flask just as easy. Just225+make sure not to forget to set the ``enctype="multipart/form-data"``226+attribtue on your HTML form, otherwise the browser will not transmit your227+files at all.228+229+Uploaded files are stored in memory or at a temporary location on the230+filesystem. You can access those files by looking at the231+:attr:`~flask.request.files` attribute on the request object. Each232+uploaded file is stored in that dictionary. It behaves just like a233+standard Python :class:`file` object, but it also has a234+:meth:`~werkzeug.FileStorage.save` method that allows you to store that235+file on the filesystem of the server. Here a simple example how that236+works::237+238+ from flask import request239+240+ @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+ ...246+247+If you want to know how the file was named on the client before it was248+uploaded to your application, you can access the249+:attr:`~werkzeug.FileStorage.filename` attribute. However please keep in250+mind that this value can be forged so never ever trust that value. If you251+want to use the filename of the client to store the file on the server,252+pass it through the :func:`~werkzeug.secure_filename` function that253+Werkzeug provides for you::254+255+ from flask import request256+ from werkzeug import secure_filename257+258+ @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+ ...264+265+Cookies266+```````267+268+To access cookies you can use the :attr:`~flask.request.cookies`269+attribute. Again this is a dictionary with all the cookies the client270+transmits. If you want to use sessions, do not use the cookies directly271+but instead use the :ref:`sessions` in Flask that add some security on top272+of cookies for you.273+274+.. _sessions:275+276+Sessions277+--------278+279+Besides the request object there is also a second object called280+:class:`~flask.session` that allows you to store information specific to a281+user from one request to the next. This is implemented on top of cookies282+for you and signes the cookies cryptographically. What this means is that283+the user could look at the contents of your cookie but not modify it,284+unless he knows the secret key used for signing.285+286+In order to use sessions you have to set a secret key. Here is how287+sessions work::288+289+ from flask import session, redirect, url_for, escape290+291+ @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'296+297+ @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+ '''308+309+ @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 lines147 flash('You are no longer following "%s"' % username)148 return redirect(url_for('user_timeline', username=username))149 150 151-@app.route('/add_message')151+@app.route('/add_message', methods=['POST'])152 def add_message():153 if 'user_id' not in session:154 abort(401)155 if request.form['text']:4 unmodified lines160 flash('Your message was recorded')161 return redirect(url_for('timeline'))162 163 164-@app.route('/login')164+@app.route('/login', methods=['GET', 'POST'])165 def login():166 if 'user_id' in session:167 return redirect(url_for('timeline'))168 error = None11 unmodified lines180 return redirect(url_for('timeline'))181 return render_template('login.html', error=error)182 183 184-@app.route('/register')184+@app.route('/register', methods=['GET', 'POST'])185 def register():186 if 'user_id' in session:187 return redirect(url_for('timeline'))188 error = None40 unmodified linesmodified:flask.py+16 added-1 removed
324 unmodified lines325 @app.route('/post/<int:post_id>')326 def show_post(post_id):327 pass328 329+ 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:332+333+ 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.338+339+ This is consistent with how web servers deal with static files. This340+ also makes it possible to use relative link targets safely.341+342 The :meth:`route` decorator accepts a couple of other arguments343 as well:344 345 :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 decorator137 unmodified lines