diff --git a/docs/appcontext.rst b/docs/appcontext.rst index 2ccacc8c..166c5aa3 100644 --- a/docs/appcontext.rst +++ b/docs/appcontext.rst @@ -74,9 +74,9 @@ The application context is also used by the :func:`~flask.url_for` function in case a ``SERVER_NAME`` was configured. This allows you to generate URLs even in the absence of a request. -If no request context has been pushed and an application context has -not been explicitly set, a ``RuntimeError`` will be raised. -:: +If no request context has been pushed and an application context has +not been explicitly set, a ``RuntimeError`` will be raised. :: + RuntimeError: Working outside of application context. Locality of the Context diff --git a/docs/cli.rst b/docs/cli.rst index 42596daf..10f5b34c 100644 --- a/docs/cli.rst +++ b/docs/cli.rst @@ -32,7 +32,7 @@ Python module that contains a Flask application. In that imported file the name of the app needs to be called ``app`` or optionally be specified after a colon. For instance -`mymodule:application` would tell it to use the `application` object in +``mymodule:application`` would tell it to use the `application` object in the :file:`mymodule.py` file. Given a :file:`hello.py` file with the application in it named ``app`` @@ -218,13 +218,13 @@ step. CLI Plugins ----------- -Flask extensions can always patch the `Flask.cli` instance with more +Flask extensions can always patch the :attr:`Flask.cli` instance with more commands if they want. However there is a second way to add CLI plugins -to Flask which is through `setuptools`. If you make a Python package that -should export a Flask command line plugin you can ship a `setup.py` file +to Flask which is through ``setuptools``. If you make a Python package that +should export a Flask command line plugin you can ship a :file:`setup.py` file that declares an entrypoint that points to a click command: -Example `setup.py`:: +Example :file:`setup.py`:: from setuptools import setup @@ -237,7 +237,7 @@ Example `setup.py`:: ''', ) -Inside `mypackage/commands.py` you can then export a Click object:: +Inside :file:`mypackage/commands.py` you can then export a Click object:: import click diff --git a/docs/conf.py b/docs/conf.py index 2f449da2..b37427a8 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -11,13 +11,16 @@ # All configuration values have a default; values that are commented out # serve to show the default. from __future__ import print_function -import sys, os +from datetime import datetime +import os +import sys +import pkg_resources # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.append(os.path.abspath('_themes')) -sys.path.append(os.path.abspath('.')) +sys.path.append(os.path.join(os.path.dirname(__file__), '_themes')) +sys.path.append(os.path.dirname(__file__)) # -- General configuration ----------------------------------------------------- @@ -46,22 +49,21 @@ master_doc = 'index' # General information about the project. project = u'Flask' -copyright = u'2015, Armin Ronacher' +copyright = u'2010 - {0}, Armin Ronacher'.format(datetime.utcnow().year) # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. -import pkg_resources try: release = pkg_resources.get_distribution('Flask').version except pkg_resources.DistributionNotFound: print('Flask must be installed to build the documentation.') print('Install from source using `pip install -e .` in a virtualenv.') sys.exit(1) -del pkg_resources if 'dev' in release: - release = release.split('dev')[0] + 'dev' + release = ''.join(release.partition('dev')[:2]) + version = '.'.join(release.split('.')[:2]) # The language for content autogenerated by Sphinx. Refer to documentation @@ -100,14 +102,12 @@ exclude_patterns = ['_build'] # The theme to use for HTML and HTML Help pages. Major themes that come with # Sphinx are currently 'default' and 'sphinxdoc'. -html_theme = 'flask' +# html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. -html_theme_options = { - 'touch_icon': 'touch-icon.png' -} +# html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ['_themes'] @@ -126,7 +126,7 @@ html_theme_path = ['_themes'] # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. -html_favicon = "flask-favicon.ico" +html_favicon = '_static/flask-favicon.ico' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, @@ -143,9 +143,18 @@ html_static_path = ['_static'] # Custom sidebar templates, maps document names to template names. html_sidebars = { - 'index': ['sidebarintro.html', 'sourcelink.html', 'searchbox.html'], - '**': ['sidebarlogo.html', 'localtoc.html', 'relations.html', - 'sourcelink.html', 'searchbox.html'] + 'index': [ + 'sidebarintro.html', + 'sourcelink.html', + 'searchbox.html' + ], + '**': [ + 'sidebarlogo.html', + 'localtoc.html', + 'relations.html', + 'sourcelink.html', + 'searchbox.html' + ] } # Additional templates that should be rendered to pages, maps page names to @@ -187,8 +196,7 @@ htmlhelp_basename = 'Flaskdoc' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ - ('latexindex', 'Flask.tex', u'Flask Documentation', - u'Armin Ronacher', 'manual'), + ('latexindex', 'Flask.tex', u'Flask Documentation', u'Armin Ronacher', 'manual'), ] # Documents to append as an appendix to all manuals. @@ -198,10 +206,10 @@ latex_documents = [ latex_use_modindex = False latex_elements = { - 'fontpkg': r'\usepackage{mathpazo}', - 'papersize': 'a4paper', - 'pointsize': '12pt', - 'preamble': r'\usepackage{flaskstyle}' + 'fontpkg': r'\usepackage{mathpazo}', + 'papersize': 'a4paper', + 'pointsize': '12pt', + 'preamble': r'\usepackage{flaskstyle}' } latex_use_parts = True @@ -245,21 +253,23 @@ latex_additional_files = ['flaskstyle.sty', 'logo.pdf'] #epub_tocdepth = 3 intersphinx_mapping = { - 'https://docs.python.org/dev': None, - 'http://werkzeug.pocoo.org/docs/': None, - 'http://click.pocoo.org/': None, - 'http://jinja.pocoo.org/docs/': None, - 'http://www.sqlalchemy.org/docs/': None, - 'https://wtforms.readthedocs.io/en/latest/': None, - 'https://pythonhosted.org/blinker/': None + 'python': ('https://docs.python.org/3/', None), + 'werkzeug': ('http://werkzeug.pocoo.org/docs/', None), + 'click': ('http://click.pocoo.org/', None), + 'jinja': ('http://jinja.pocoo.org/docs/', None), + 'sqlalchemy': ('http://docs.sqlalchemy.org/en/latest/', None), + 'wtforms': ('https://wtforms.readthedocs.io/en/latest/', None), + 'blinker': ('https://pythonhosted.org/blinker/', None) } -pygments_style = 'flask_theme_support.FlaskyStyle' - -# fall back if theme is not there try: __import__('flask_theme_support') -except ImportError as e: + pygments_style = 'flask_theme_support.FlaskyStyle' + html_theme = 'flask' + html_theme_options = { + 'touch_icon': 'touch-icon.png' + } +except ImportError: print('-' * 74) print('Warning: Flask themes unavailable. Building with default theme') print('If you want the Flask themes, run this command and build again:') @@ -267,10 +277,6 @@ except ImportError as e: print(' git submodule update --init') print('-' * 74) - pygments_style = 'tango' - html_theme = 'default' - html_theme_options = {} - # unwrap decorators def unwrap_decorators(): diff --git a/docs/installation.rst b/docs/installation.rst index 533a6fff..638d07ce 100644 --- a/docs/installation.rst +++ b/docs/installation.rst @@ -143,8 +143,8 @@ packages you will need are setuptools and pip - these will let you install anything else (like virtualenv). Fortunately there are two "bootstrap scripts" you can run to install either. -If you don't currently have either, then `get-pip.py` will install both for you -(you won't need to run ez_setup.py). +If you don't currently have either, then :file:`get-pip.py` will install both for you +(you won't need to run :file:`ez_setup.py`). `get-pip.py`_ diff --git a/docs/patterns/distribute.rst b/docs/patterns/distribute.rst index 8f79a2dd..72cc25d6 100644 --- a/docs/patterns/distribute.rst +++ b/docs/patterns/distribute.rst @@ -39,10 +39,8 @@ the process, also read the :ref:`fabric-deployment` chapter. Basic Setup Script ------------------ -Because you have Flask running, you have setuptools available on your system anyways. -Flask already depends upon setuptools. If you do not, fear not, there is a -script to install it for you: `ez_setup.py`_. Just download and -run with your Python interpreter. +Because you have Flask installed, you have setuptools available on your system. +Flask already depends upon setuptools. Standard disclaimer applies: :ref:`you better use a virtualenv `. @@ -67,7 +65,7 @@ A basic :file:`setup.py` file for a Flask application looks like this:: Please keep in mind that you have to list subpackages explicitly. If you want setuptools to lookup the packages for you automatically, you can use -the `find_packages` function:: +the ``find_packages`` function:: from setuptools import setup, find_packages @@ -76,12 +74,12 @@ the `find_packages` function:: packages=find_packages() ) -Most parameters to the `setup` function should be self explanatory, -`include_package_data` and `zip_safe` might not be. -`include_package_data` tells setuptools to look for a :file:`MANIFEST.in` file +Most parameters to the ``setup`` function should be self explanatory, +``include_package_data`` and ``zip_safe`` might not be. +``include_package_data`` tells setuptools to look for a :file:`MANIFEST.in` file and install all the entries that match as package data. We will use this to distribute the static files and templates along with the Python module -(see :ref:`distributing-resources`). The `zip_safe` flag can be used to +(see :ref:`distributing-resources`). The ``zip_safe`` flag can be used to force or prevent zip Archive creation. In general you probably don't want your packages to be installed as zip files because some tools do not support them and they make debugging a lot harder. @@ -123,13 +121,13 @@ your tarball:: Don't forget that even if you enlist them in your :file:`MANIFEST.in` file, they won't be installed for you unless you set the `include_package_data` -parameter of the `setup` function to ``True``! +parameter of the ``setup`` function to ``True``! Declaring Dependencies ---------------------- -Dependencies are declared in the `install_requires` parameter as a list. +Dependencies are declared in the ``install_requires`` parameter as a list. Each item in that list is the name of a package that should be pulled from PyPI on installation. By default it will always use the most recent version, but you can also provide minimum and maximum version @@ -159,20 +157,20 @@ Installing / Developing ----------------------- To install your application (ideally into a virtualenv) just run the -:file:`setup.py` script with the `install` parameter. It will install your +:file:`setup.py` script with the ``install`` parameter. It will install your application into the virtualenv's site-packages folder and also download and install all dependencies:: $ python setup.py install If you are developing on the package and also want the requirements to be -installed, you can use the `develop` command instead:: +installed, you can use the ``develop`` command instead:: $ python setup.py develop This has the advantage of just installing a link to the site-packages folder instead of copying the data over. You can then continue to work on -the code without having to run `install` again after each change. +the code without having to run ``install`` again after each change. .. _pip: https://pypi.python.org/pypi/pip diff --git a/docs/quickstart.rst b/docs/quickstart.rst index ae1c7afa..433e4e08 100644 --- a/docs/quickstart.rst +++ b/docs/quickstart.rst @@ -26,7 +26,7 @@ So what did that code do? class will be our WSGI application. 2. 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 + 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 @@ -42,17 +42,17 @@ your application :file:`flask.py` because this would conflict with Flask itself. To run the application you can either use the :command:`flask` command or -python's :option:`-m` switch with Flask. Before you can do that you need +python's ``-m`` switch with Flask. Before you can do that you need to tell your terminal the application to work with by exporting the -`FLASK_APP` environment variable:: +``FLASK_APP`` environment variable:: $ export FLASK_APP=hello.py $ flask run * Running on http://127.0.0.1:5000/ -If you are on Windows you need to use `set` instead of `export`. +If you are on Windows you need to use ``set`` instead of ``export``. -Alternatively you can use `python -m flask`:: +Alternatively you can use :command:`python -m flask`:: $ export FLASK_APP=hello.py $ python -m flask run @@ -86,7 +86,7 @@ should see your hello world greeting. What to do if the Server does not Start --------------------------------------- -In case the ``python -m flask`` fails or :command:`flask` does not exist, +In case the :command:`python -m flask` fails or :command:`flask` does not exist, there are multiple reasons this might be the case. First of all you need to look at the error message. @@ -95,14 +95,14 @@ Old Version of Flask Versions of Flask older than 0.11 use to have different ways to start the application. In short, the :command:`flask` command did not exist, and -neither did ``python -m flask``. In that case you have two options: +neither did :command:`python -m flask`. In that case you have two options: either upgrade to newer Flask versions or have a look at the :ref:`server` docs to see the alternative method for running a server. Invalid Import Name ``````````````````` -The :option:`-a` argument to :command:`flask` is the name of the module to +The ``-a`` argument to :command:`flask` is the name of the module to import. 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. @@ -123,13 +123,13 @@ 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 the `FLASK_DEBUG` environment variable +To enable debug mode you can export the ``FLASK_DEBUG`` environment variable before running the server:: $ export FLASK_DEBUG=1 $ flask run -(On Windows you need to use `set` instead of `export`). +(On Windows you need to use ``set`` instead of ``export``). This does the following things: @@ -202,7 +202,7 @@ The following converters exist: =========== =============================================== `string` accepts any text without a slash (the default) `int` accepts integers -`float` like `int` but for floating point values +`float` like ``int`` but for floating point values `path` like the default but also accepts slashes `any` matches one of the items provided `uuid` accepts UUID strings @@ -226,7 +226,7 @@ The following converters exist: Though they look rather similar, they differ in their use of the trailing slash in the URL *definition*. In the first case, the canonical URL for the - `projects` endpoint has a trailing slash. In that sense, it is similar to + ``projects`` endpoint 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. @@ -250,29 +250,29 @@ build a URL to a specific function you can use the :func:`~flask.url_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: - ->>> from flask import Flask, url_for ->>> app = Flask(__name__) ->>> @app.route('/') -... def index(): pass -... ->>> @app.route('/login') -... def login(): pass -... ->>> @app.route('/user/') -... def profile(username): pass -... ->>> with app.test_request_context(): -... print url_for('index') -... print url_for('login') -... print url_for('login', next='/') -... print url_for('profile', username='John Doe') -... -/ -/login -/login?next=/ -/user/John%20Doe +some examples:: + + >>> from flask import Flask, url_for + >>> app = Flask(__name__) + >>> @app.route('/') + ... def index(): pass + ... + >>> @app.route('/login') + ... def login(): pass + ... + >>> @app.route('/user/') + ... def profile(username): pass + ... + >>> with app.test_request_context(): + ... print url_for('index') + ... print url_for('login') + ... print url_for('login', next='/') + ... print url_for('profile', username='John Doe') + ... + / + /login + /login?next=/ + /user/John%20Doe (This also uses the :meth:`~flask.Flask.test_request_context` method, explained below. It tells Flask to behave as though it is handling a request, even @@ -288,8 +288,8 @@ There are three good reasons for this: remember to change URLs all over the place. 2. URL building will handle escaping of special characters and Unicode data transparently for you, so you don't have to deal with them. -3. If your application is placed outside the URL root (say, in - ``/myapplication`` instead of ``/``), :func:`~flask.url_for` will handle +3. If your application is placed outside the URL root - say, in + ``/myapplication`` instead of ``/`` - :func:`~flask.url_for` will handle that properly for you. @@ -298,7 +298,7 @@ HTTP Methods HTTP (the protocol web applications are speaking) knows different methods for accessing URLs. By default, a route only answers to ``GET`` requests, but that -can be changed by providing the `methods` argument to the +can be changed by providing the ``methods`` argument to the :meth:`~flask.Flask.route` decorator. Here are some examples:: from flask import request @@ -446,22 +446,22 @@ know how that works, head over to the :ref:`template-inheritance` pattern documentation. Basically template inheritance makes it possible to keep certain elements on each page (like header, navigation and footer). -Automatic escaping is enabled, so if `name` contains HTML it will be escaped +Automatic escaping is enabled, so if ``name`` contains 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 the :class:`~jinja2.Markup` class or by using the ``|safe`` filter in the template. Head over to the Jinja 2 documentation for more examples. -Here is a basic introduction to how the :class:`~jinja2.Markup` class works: +Here is a basic introduction to how the :class:`~jinja2.Markup` class works:: ->>> from flask import Markup ->>> 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' + >>> from flask import Markup + >>> 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' .. versionchanged:: 0.5 @@ -540,7 +540,7 @@ The Request Object The request object is documented in the API section and we will not cover it here in detail (see :class:`~flask.request`). Here is a broad overview of some of the most common operations. First of all you have to import it from -the `flask` module:: +the ``flask`` module:: from flask import request @@ -563,7 +563,7 @@ attributes mentioned above:: # was GET or the credentials were invalid return render_template('login.html', error=error) -What happens if the key does not exist in the `form` attribute? In that +What happens if the key does not exist in the ``form`` attribute? In that case a special :exc:`KeyError` is raised. You can catch it like a standard :exc:`KeyError` but 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 @@ -725,17 +725,15 @@ converting return values into response objects is as follows: 3. 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. The `status` value will override the status code - and `headers` can be a list or dictionary of additional header values. + to be in the tuple. The ``status`` value will override the status code + and ``headers`` can be a list or dictionary of additional header values. 4. 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 the :func:`~flask.make_response` function. -Imagine you have a view like this: - -.. sourcecode:: python +Imagine you have a view like this:: @app.errorhandler(404) def not_found(error): @@ -743,9 +741,7 @@ Imagine you have a view like this: You just need to wrap the return expression with :func:`~flask.make_response` and get the response object to modify it, then -return it: - -.. sourcecode:: python +return it:: @app.errorhandler(404) def not_found(error): @@ -807,13 +803,13 @@ not using the template engine (as in this example). 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: + random generator which can be used to get such a key:: - >>> import os - >>> os.urandom(24) - '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O>> import os + >>> os.urandom(24) + '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O