Skip to content
Myr

explain escape at top of quickstart

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

* introduce escape, and explain why it's omitted in examples * clean up imports in examples

authored by David Lord · committed by David Lord · parent db061cf · Browse files · 1 file+50 added−49 removed
This commit

State

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

Diff stats

1 file+50 added−49 removed

  • other:+50 added−49 removed

1 file+50 added−49 removed

modified:docs/quickstart.rst+50 added-49 removed
1 unmodified line
23Quickstart4==========56Eager to get started? This page gives a good introduction to Flask. It7assumes you already have Flask installed. If you do not, head over to the8:ref:`installation` section.6Eager to get started? This page gives a good introduction to Flask.7Follow :doc:`installation` to set up a project and install Flask first.8910A Minimal Application11---------------------1214A minimal Flask application looks something like this::13A minimal Flask application looks something like this:1415.. code-block:: python1617 from flask import Flask18 from markupsafe import escape1920 app = Flask(__name__)2119 @app.route('/')22 @app.route("/")23 def hello_world():21 return 'Hello, World!'24 return f"<p>Hello, {escape(name)}!</p>"2526So what did that code do?27251. First we imported the :class:`~flask.Flask` class. An instance of this26 class will be our WSGI application.272. Next we create an instance of this class. The first argument is the name of28 the application's module or package. If you are using a single module (as29 in this example), you should use ``__name__`` because depending on if it's30 started as application or imported as module the name will be different31 (``'__main__'`` versus the actual import name). This is needed so that32 Flask knows where to look for templates, static files, and so on. For more33 information have a look at the :class:`~flask.Flask` documentation.343. We then use the :meth:`~flask.Flask.route` decorator to tell Flask what URL35 should trigger our function.364. The function is given a name which is also used to generate URLs for that37 particular function, and returns the message we want to display in the38 user's browser.281. First we imported the :class:`~flask.Flask` class. An instance of29 this class will be our WSGI application.302. Next we create an instance of this class. The first argument is the31 name of the application's module or package. ``__name__`` is a32 convenient shortcut for this that is appropriate for most cases.33 This is needed so that Flask knows where to look for resources such34 as templates and static files.353. We then use the :meth:`~flask.Flask.route` decorator to tell Flask36 what URL should trigger our function.374. The function returns the message we want to display in the user's38 browser. The default content type is HTML, so HTML in the string39 will be rendered by the browser.4041.. note:: HTML escaping4243 When returning HTML (the default response type in Flask), any user44 input rendered in the output must be escaped to protect from45 injection attacks. HTML templates in Jinja, introduced later, will46 do this automatically. :func:`~markupsafe.escape`, shown above, can47 be used manually. It's omitted for brevity in the examples below.4840Just save it as :file:`hello.py` or something similar. Make sure to not call49Save it as :file:`hello.py` or something similar. Make sure to not call50your application :file:`flask.py` because this would conflict with Flask51itself.5244To run the application you can either use the :command:`flask` command or45python's ``-m`` switch with Flask. Before you can do that you need53To run the application, use the :command:`flask` command or54:command:`python -m flask`. Before you can do that you need55to tell your terminal the application to work with by exporting the47``FLASK_APP`` environment variable::56``FLASK_APP`` environment variable:5758.. code-block:: text5960 $ export FLASK_APP=hello.py61 $ flask run62 * Running on http://127.0.0.1:5000/63
5 unmodified lines
69And on PowerShell::7071 PS C:\path\to\app> $env:FLASK_APP = "hello.py"7262Alternatively you can use :command:`python -m flask`::6364 $ export FLASK_APP=hello.py65 $ python -m flask run66 * Running on http://127.0.0.1:5000/6773This launches a very simple builtin server, which is good enough for testing74but probably not what you want to use in production. For deployment options see75:ref:`deployment`.76
130 unmodified lines
207208 @app.route('/user/<username>')209 def show_user_profile(username):210 # show the user profile for that user206 return 'User %s' % escape(username)211 return f'User {username}'212213 @app.route('/post/<int:post_id>')214 def show_post(post_id):215 # show the post with the given id, the id is an integer211 return 'Post %d' % post_id216 return f'Post {post_id}'217218 @app.route('/path/<path:subpath>')219 def show_subpath(subpath):220 # show the subpath after /path/216 return 'Subpath %s' % escape(subpath)221 return f'Subpath {subpath}'222223Converter types:224225========== ==========================================
59 unmodified lines
285Python shell. See :ref:`context-locals`.286287.. code-block:: python288284 from flask import Flask, escape, url_for289 from flask import url_for290286 app = Flask(__name__)287291 @app.route('/')292 def index():293 return 'index'294
2 unmodified lines
297 return 'login'298299 @app.route('/user/<username>')300 def profile(username):298 return '{}\'s profile'.format(escape(username))301 return f'{username}\'s profile'302303 with app.test_request_context():304 print(url_for('index'))305 print(url_for('login'))
112 unmodified lines
418Automatic escaping is enabled, so if ``name`` contains HTML it will be escaped419automatically. If you can trust a variable and you know that it will be420safe HTML (for example because it came from a module that converts wiki421markup to HTML) you can mark it as safe by using the419:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the422:class:`~markupsafe.Markup` class or by using the ``|safe`` filter in the423template. Head over to the Jinja 2 documentation for more examples.424425Here is a basic introduction to how the :class:`~jinja2.Markup` class works::426424 >>> from flask import Markup427 >>> from markupsafe import Markup428 >>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'429 Markup(u'<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')430 >>> Markup.escape('<blink>hacker</blink>')431 Markup(u'&lt;blink&gt;hacker&lt;/blink&gt;')
65 unmodified lines
497498The other possibility is passing a whole WSGI environment to the499:meth:`~flask.Flask.request_context` method::500498 from flask import request499501 with app.request_context(environ):502 assert request.method == 'POST'503504The Request Object
77 unmodified lines
582of the client to store the file on the server, pass it through the583:func:`~werkzeug.utils.secure_filename` function that584Werkzeug provides for you::585585 from flask import request586 from werkzeug.utils import secure_filename587588 @app.route('/upload', methods=['GET', 'POST'])589 def upload_file():
115 unmodified lines
705you can use the :func:`~flask.make_response` function.706707Imagine you have a view like this::708709 from flask import render_template710711 @app.errorhandler(404)712 def not_found(error):713 return render_template('error.html'), 404714715You just need to wrap the return expression with716:func:`~flask.make_response` and get the response object to modify it, then717return it::718719 from flask import make_response720721 @app.errorhandler(404)722 def not_found(error):723 resp = make_response(render_template('error.html'), 404)724 resp.headers['X-Something'] = 'A value'
25 unmodified lines
750more complex applications.751752.. code-block:: python753754 from flask import jsonify755756 @app.route("/users")757 def users_api():758 users = get_all_users()759 return jsonify([user.to_json() for user in users])
13 unmodified lines
773774In order to use sessions you have to set a secret key. Here is how775sessions work::776771 from flask import Flask, session, redirect, url_for, escape, request777 from flask import session778773 app = Flask(__name__)774779 # Set the secret key to some random bytes. Keep this really secret!780 app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'781782 @app.route('/')783 def index():784 if 'username' in session:781 return 'Logged in as %s' % escape(session['username'])785 return f'Logged in as {session["username"]}'786 return 'You are not logged in'787788 @app.route('/login', methods=['GET', 'POST'])789 def login():
12 unmodified lines
802 # remove the username from the session if it's there803 session.pop('username', None)804 return redirect(url_for('index'))805802The :func:`~flask.escape` mentioned here does escaping for you if you are803not using the template engine (as in this example).804806.. admonition:: How to generate good secret keys807808 A secret key should be as random as possible. Your operating system has809 ways to generate pretty random data based on a cryptographic random
85 unmodified lines