Flask endpoint что это
What is an ‘endpoint’ in Flask?
What exactly is meant by an «endpoint»?
4 Answers 4
How Flask Routing Works
The entire idea of Flask (and the underlying Werkzeug library) is to map URL paths to some logic that you will run (typically, the «view function»). Your basic view is defined like this:
Note that the function you referred to (add_url_rule) achieves the same goal, just without using the decorator notation. Therefore, the following is the same:
Let’s say your website is located at ‘www.example.org’ and uses the above view. The user enters the following URL into their browser:
The job of Flask is to take this URL, figure out what the user wants to do, and pass it on to one of your many python functions for handling. It takes the path:
. and matches it to the list of routes. In our case, we defined this path to go to the give_greeting function.
However, while this is the typical way that you might go about creating a view, it actually abstracts some extra info from you. Behind the scenes, Flask did not make the leap directly from URL to the view function that should handle this request. It does not simply say.
Actually, it there is another step, where it maps the URL to an endpoint:
Basically, the «endpoint» is an identifier that is used in determining what logical unit of your code should handle the request. Normally, an endpoint is just the name of a view function. However, you can actually change the endpoint, as is done in the following example.
Now, when Flask routes the request, the logic looks like this:
How You Use the Endpoint
This is advantageous, as now we can change the URLs of our application without needing to change the line where we reference that resource.
Why not just always use the name of the view function?
One question that might come up is the following: «Why do we need this extra layer?» Why map a path to an endpoint, then an endpoint to a view function? Why not just skip that middle step?
The reason is because it is more powerful this way. For example, Flask Blueprints allow you to split your application into various parts. I might have all of my admin-side resources in a blueprint called «admin», and all of my user-level resources in an endpoint called «user».
Blueprints allow you to separate these into namespaces. For example.
Note that in both blueprints, the ‘/greeting’ route is a function called «greeting». If I wanted to refer to the admin «greeting» function, I couldn’t just say «greeting» because there is also a user «greeting» function. Endpoints allow for a sort of namespacing by having you specify the name of the blueprint as part of the endpoint. So, I could do the following.
Класс Request() модуля flask в Python.
Объект запроса приложения Flask.
Синтаксис:
Параметры:
Возвращаемое значение:
Описание:
Класс Request() модуля flask создает объект запроса при каждом обращении к URL приложения, который, в свою очередь, запоминает совпадающую конечную точку endpoint и аргументы, передаваемые в функцию-представление.
Класс flask.Request является подклассом werkzeug.wrappers.Request и предоставляет все атрибуты, определенные Werkzeug, плюс несколько специфичных для Flask.
Объект запроса Request приложения Flask.
Request.accept_charsets :
Request.accept_encodings :
Свойство Request.accept_encodings ведет себя как Request.accept_charsets
Request.accept_languages :
Свойство Request.accept_languages ведет себя как Request.accept_charsets
Request.accept_mimetypes :
Свойство Request.accept_mimetypes ведет себя как Request.accept_charsets
Request.access_control_request_headers :
Атрибут Request.access_control_request_headers отправляет запрос предварительной проверки, для выяснения, какие заголовки будут отправлены с запросом перекрестного происхождения.
Request.access_control_request_method :
Атрибут Request.access_control_request_method отправляет запрос предварительной проверки, для выяснения, какой метод будет использоваться для запроса перекрестного происхождения.
Request.access_route :
Request.application(f) :
Request.args :
По умолчанию из этой функции возвращается значение ImmutableMultiDict (неизменяемый словарь). Возвращаемый тип можно изменить, установив для параметра Request.parameterstorageclass другой тип. Это может потребоваться, если важен порядок данных формы.
Request.authorization :
Свойство Request.authorization представляет заголовок авторизации, отправленный клиентом, в виде объекта werkzeug.datastructures.Authorization в распарсенном виде.
Request.base_url :
Request.blueprint :
Возвращаемое значение не обязательно совпадает с именем, с которым была создана схема. Возможно, она была вложена или зарегистрирована под другим именем.
Request.blueprints :
Свойство Request.blueprints возвращает зарегистрированные имена текущей схемы blueprint вверх к родительским схемам.
Новое в версии 2.0.1.
Request.cache_control :
Request.close() :
Метод Request.close() закрывает связанные ресурсы этого объекта запроса. Метод явно закрывает все дескрипторы файлов.
Request.content_encoding :
Request.content_length :
Request.content_md5 :
Примечание: MIC хорош для обнаружения случайной модификации тела объекта при передаче, но не является защитой от злонамеренных атак.
Request.content_type :
Request.cookies :
Request.data: bytes :
Request.date :
Изменено в версии 2.0: объект datetime.datetime учитывает часовой пояс.
Request.dict_storage_class :
Request.endpoint :
Свойство Request.endpoint представляет собой конечную точку, соответствующую URL-адресу запроса.
Request.endpoint в сочетании с Request.view_args может использоваться для восстановления того же URL-адреса или измененного URL-адреса.
Request.environ :
Атрибут Request.environ возвращает словарь переменных среды WSGI сервера, которые содержат HTTP-заголовки и информацию с сервера WSGI.
Request.files :
Request.form :
Возвращаемый тип можно изменить, задав для параметра Request.parameter_storage_class другой тип. Изменение типа может быть необходимо, если важен порядок возвращаемых данных в форме.
Request.form_data_parser_class :
Request.from_values(*args, **kwargs) :
Этот метод полезен для небольших скриптов, когда нужно имитировать запрос с URL-адреса. Не используйте этот метод для модульного тестирования, существует полнофункциональный клиентский объект ( Client ), который позволяет создавать составные запросы, поддерживает файлы cookie и т. д.
Request.full_path :
Свойство Request.full_path представляет собой запрошенный URL путь, включая строку запроса..
Request.get_data(cache=True, as_text=False, parse_form_data=False) :
Request.get_json(force=False, silent=False, cache=True) :
Метод Request.get_json() возвращает распарсенные/разобранные данные JSON.
Request.headers :
Атрибут Request.headers представляет собой словарь с заголовками, полученные вместе с запросом.
Request.host :
Request.host_url :
Свойство Request.host_url возвращает только схему URL-адреса и хост.
Request.if_match :
Request.if_modified_since :
Изменено в версии 2.0: объект datetime.datetime учитывает часовой пояс.
Request.if_none_match :
Request.if_range :
Изменено в версии 2.0: werkzeug.datastructures.IfRange.date учитывает часовой пояс.
Request.if_unmodified_since :
Изменено в версии 2.0: объект datetime.datetime учитывает часовой пояс.
Request.input_stream :
Атрибут Request.input_stream возвращает входной поток WSGI.
Request.is_json :
Свойство Request.is_json проверяет, что тип mimetype указывает на данные JSON: application/json или `application/*+json.
Request.is_multiprocess :
Атрибут Request.is_multiprocess логическое значение, которое верно, если приложение обслуживается WSGI сервером, если он порождает несколько процессов.
Request.is_multithread :
Атрибут Request.is_multithread логическое значение, которое верно, если приложение обслуживается многопоточным WSGI сервером.
Request.is_run_once :
Атрибут Request.is_run_once логическое значение, которое верно, если приложение будет выполняться только один раз за время существования процесса.
Такое поведение относится, например, к CGI, но не гарантируется, что выполнение произойдет только один раз..
Request.is_secure: bool :
Request.json :
Вызывает метод Request.get_json() с аргументами по умолчанию.
Request.list_storage_class :
Request.make_form_data_parser() :
Метод Request.make_form_data_parser() создает анализатор данных HTML-формы в виде экземпляра класса Request.form_data_parser_class с некоторыми параметрами.
Request.max_content_length :
Request.max_forwards :
Request.method :
Request.mimetype :
Request.mimetype_params :
Request.on_json_loading_failed(e) :
Request.origin :
Атрибут Request.origin возвращает хост, с которого исходил запрос.
Для указания разрешенных источников запроса необходимо установить в ответ сервера Response.access_control_allow_origin разрешенные источники.
Request.parameter_storage_class :
Request.path :
Request.pragma :
Request.query_string :
Request.range :
Request.referrer :
Request.remote_addr :
Атрибут Request.remote_addr возвращает ip-адрес клиента, отправляющего запрос.
Request.remote_user :
Атрибут Request.remote_user содержит имя пользователя, под которым пользователь прошел аутентификацию, если сервер поддерживает аутентификацию пользователя и сценарий защищен.
Request.root_path :
Request.root_url :
Свойство Request.root_url возвращает схему URL-адреса, хост и корневой путь. Это корень, из которого осуществляется доступ к приложению.
Request.routing_exception :
Атрибут Request.routing_exception возвращает исключение, которое будет вызвано или было вызвано как часть обработки запроса, если сопоставление URL-адреса не удалось. Обычно это исключение NotFound или что-то подобное.
Request.scheme :
Request.script_root :
Request.server :
Request.shallow :
Request.stream :
Поток Request.stream возвращает данные только один раз.
Request.url :
Свойство Request.url возвращает полный URL-адрес запроса со схемой, хостом, корневым путем, путем и строкой запроса.
Request.url_charset :
Свойство Request.url_charset возвращает кодировку, используемую для URL-адресов.
Request.url_root :
Request.url_rule :
Атрибут Request.url_rule возвращает правило внутреннего URL-адреса, соответствующее запросу.
Атрибут может быть полезен для проверки того, какие методы разрешены для URL-адреса из обработчика до/после ( request.url_rule.methods ) и т. д. Хотя, если HTTP-метод запроса был недопустимым для правила URL-адреса, то действительный список доступен в routing_exception.valid_methods (атрибут исключения Werkzeug MethodNotAllowed ), потому что запрос никогда не был внутренне привязан.
Request.user_agent :
Request.user_agent_class :
Request.values :
Request.view_args :
Request.want_form_data_parsed: bool :
Пишем API на Python (с Flask и RapidAPI)
Если вы читаете эту статью, вероятно, вы уже знакомы с возможностями, которые открываются при использовании API (Application Programming Interface).
Добавив в свое приложение один из многих открытых API, вы можете расширить функциональность этого приложения либо же дополнить его нужными данными. Но что, если вы разработали уникальную функцию, которой хотите поделиться с коммьюнити?
Ответ прост: нужно создать собственный API.
Несмотря на то, что это поначалу кажется сложной задачей, на самом деле всё просто. Мы расскажем, как это сделать с помощью Python.
Что нужно для начала работы
Для разработки API необходимы:
Рекомендуем бесплатный интенсив по программированию для начинающих:
Разработка telegram-бота на C# — 26–28 августа. Бесплатный интенсив, который позволяет разобраться в том, как работают боты-помощники, в особенностях работы с API Telegram и прочих нюансах. Трое лучших участников получат от Skillbox 30 000 рублей.
Перед тем как начать
Мы собираемся разработать RESTful API с базовой CRUID-функциональностью.
Чтобы полностью понять задачу, давайте разберемся с двумя терминами, упомянутыми выше.
REST API (Representational State Transfer) — это API, которое использует HTTP-запросы для обмена данными.
REST API должны соответствовать определенным критериям:
CRUD — концепция программирования, которая описывает четыре базовых действия (create, read, update и delete).
В REST API типы запросов и методы запроса отвечают за такие действия, как post, get, put, delete.
Теперь, когда мы разобрались с базовыми терминами, можно приступить к созданию API.
Разработка
Давайте создадим репозиторий цитат об искусственном интеллекте. ИИ — одна из наиболее активно развивающихся технологий сегодня, а Python — популярный инструмент для работы с ИИ.
С этим API разработчик Python сможет быстро получать информацию об ИИ и вдохновляться новыми достижениями. Если у разработчика есть ценные мысли по этой теме, он сможет добавлять их в репозиторий.
Начнем с импорта необходимых модулей и настройки Flask:
В этом сниппете Flask, Api и Resource — классы, которые нам нужны.
Reqparse — это интерфейс парсинга запросов Flask-RESTful… Также понадобится модуль random для отображения случайной цитаты.
Теперь мы создадим репозиторий цитат об ИИ.
Каждая запись репо будет содержать:
Теперь нужно создать ресурсный класс Quote, который будет определять операции эндпоинтов нашего API. Внутри класса нужно заявить четыре метода: get, post, put, delete.
Начнем с метода GET
Он дает возможность получить определенную цитату путем указания ее ID или же случайную цитату, если ID не указан.
Метод GET возвращает случайную цитату, если ID содержит дефолтное значение, т.е. при вызове метода ID не был задан.
Если он задан, то метод ищет среди цитат и находит ту, которая содержит заданный ID. Если же ничего не найдено, выводится сообщение “Quote not found, 404”.
Помните: метод возвращает HTTP-статус 200 в случае успешного запроса и 404, если запись не найдена.
Теперь давайте создадим POST-метод для добавления новой цитаты в репозиторий
Он будет получать идентификатор каждой новой цитаты при вводе. Кроме того, POST будет использовать reqparse для парсинга параметров, которые будут идти в теле запроса (автор и текст цитаты).
В коде выше POST-метод принял ID цитаты. Затем, используя reqparse, он получил автора и цитату из запроса, сохранив их в словаре params.
Если цитата с указанным ID уже существует, то метод выводит соответствующее сообщение и код 400.
Если цитата с указанным ID еще не была создана, метод создает новую запись с указанным ID и автором, а также другими параметрами. Затем он добавляет запись в список ai_quotes и возвращает запись с новой цитатой вместе с кодом 201.
Теперь создаем PUT-метод для изменения существующей цитаты в репозитории
PUT-метод, аналогично предыдущему примеру, берет ID и input и парсит параметры цитаты, используя reqparse.
Если цитата с указанным ID существует, метод обновит ее с новыми параметрами, а затем выведет обновленную цитату с кодом 200. Если цитаты с указанным ID еще нет, будет создана новая запись с кодом 201.
Наконец, давайте создадим DELETE-метод для удаления цитаты, которая уже не вдохновляет
Этот метод получает ID цитаты при вводе и обновляет список ai_quotes, используя общий список.
Теперь, когда мы создали все методы, всё, что нам нужно, — просто добавить resource к API, задать путь и запустить Flask.
Наш REST API Service готов!
Далее мы можем сохранить код в файл app.py, запустив его в консоли при помощи команды:
Если все хорошо, то мы получим нечто вроде этого:
* Debug mode: on
* Running on 127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: XXXXXXX
После того как API создан, его нужно протестировать.
Сделать это можно при помощи консольной утилиты curl или клиента Insomnia REST либо же опубликовав API на Rapid API.
RapidAPI — самый большой в мире маркетплейс с более чем 10 000 API (и около 1 млн разработчиков).
RapidAPI не только предоставляет единый интерфейс для работы со сторонними API, но и даtт возможность быстро и без проблем опубликовать ваш собственный API.
Для того чтобы сделать это, сначала нужно опубликовать его на каком-нибудь сервере в сети. В нашем случае воспользуемся Heroku. Работа с ним не должна вызвать никаких сложностей, (узнать о нём больше можно здесь).
Как опубликовать ваш API на Heroku
1. Устанавливаем Heroku.
Первым делом нужно зарегистрироваться и установить Heroku Command Line Interface (CLI). Это работает на Ubuntu 16+.
2. Добавляем необходимые файлы.
Теперь нужно добавить файлы для публикации в папку в нашем приложении:
Procfile будет содержать:
web: gunicorn app:app
Теперь, когда созданы файлы, давайте инициализируем git-репо и закоммитим:
3. Создаем новое Heroku-приложение.
Отправляем master branch в удаленный репо Heroku:
Теперь можно начать, открыв API Service при помощи команд:
Как добавить ваш Python API в маркетплейс RapidAPI
После того как API-сервис опубликован на Heroku, можно добавить его к Rapid API. Здесь подробная документация по этой теме.
1. Создаем аккаунт RapidAPI.
Регистрируем бесплатную учетную запись — это можно сделать при помощи Facebook, Google, GitHub.
2. Добавляем API в панель управления.
3. Далее вводим общую информацию о своем API.
4. После нажатия “Add API” появляется новая страничка, где можно ввести информацию о нашем API.
5. Теперь можно либо вручную ввести эндпоинты API, либо загрузить swagger-file при помощи OpenAPI.
Ну а теперь нужно задать эндпоинты нашего API на странице Endpoints. В нашем случае эндпоинты соответствуют концепции CRUD (get, post, put, delete).
Далее нужно создать эндпоинт GET AI Quote, который выводит случайную цитату (в том случае, если ID дефолтный) или цитату для указанного ID.
Для создания эндпоинта нужно нажать кнопку “Create Endpoint”.
Повторяем этот процесс для всех других эндпоинтов API. На этом всё! Поздравляю, вы опубликовали ваш API!
Если все хорошо, страничка API будет выглядеть как-то так:
Заключение
В этой статье мы изучили процесс создания собственного RESTful API Service на Python, вместе с процессом публикации API в облаке Heroku и добавлением его в каталог RapidAPI.
Но в тестовом варианте были показаны только базовые принципы разработки API — такие нюансы, как безопасность, отказоустойчивость и масштабируемость, не рассматривались.
При разработке реального API все это нужно учитывать.
API (перевод на начальной стадии)¶
Эта часть документации содержит описание всех интерфейсов Flask. В тех местах, где Flask зависит от внешних библиотек, мы документируем самое важное прямо здесь, а также снабжаем вас ссылкой на оригинальную документацию.
Объект приложения¶
The flask object implements a WSGI application and acts as the central object. It is passed the name of the module or package of the application. Once it is created it will act as a central registry for the view functions, the URL rules, template configuration and much more.
Usually you create a Flask instance in your main module or in the __init__.py file of your package like this:
About the First Parameter
The idea of the first parameter is to give Flask an idea what belongs to your application. This name is used to find resources on the file system, can be used by extensions to improve debugging information and a lot more.
So it’s important what you provide there. If you are using a single module, __name__ is always the correct value. If you however are using a package, it’s usually recommended to hardcode the name of your package there.
For example if your application is defined in yourapplication/app.py you should create it with one of the two versions below:
Добавлено в версии 0.8: The instance_path and instance_relative_config parameters were added.
Register a custom template filter. Works exactly like the template_filter() decorator.
| Параметры: | name – the optional name of the filter, otherwise the function name will be used. |
|---|
add_template_global ( f, name=None ) ¶
Register a custom template global function. Works exactly like the template_global() decorator.
Добавлено в версии 0.10.
| Параметры: | name – the optional name of the global function, otherwise the function name will be used. |
|---|
add_template_test ( f, name=None ) ¶
Register a custom template test. Works exactly like the template_test() decorator.
Добавлено в версии 0.10.
| Параметры: | name – the optional name of the test, otherwise the function name will be used. |
|---|
add_url_rule ( rule, endpoint=None, view_func=None, **options ) ¶
Connects a URL rule. Works exactly like the route() decorator. If a view_func is provided it will be registered with the endpoint.
Basically this example:
Is equivalent to the following:
If the view_func is not provided you will need to connect the endpoint to a view function like so:
Internally route() invokes add_url_rule() so if you want to customize the behavior via subclassing you only need to change this method.
Изменено в версии 0.2: view_func parameter added.
Изменено в версии 0.6: OPTIONS is added automatically as method.
Register a function to be run after each request. Your function must take one parameter, a response_class object and return a new response object or the same (see process_response() ).
As of Flask 0.7 this function might not be executed at the end of the request in case an unhandled exception occurred.
A dictionary with lists of functions that should be called after each request. The key of the dictionary is the name of the blueprint this function is active for, None for all requests. This can for example be used to open database connections or getting hold of the currently logged in user. To register a function here, use the after_request() decorator.
Binds the application only. For as long as the application is bound to the current context the flask.current_app points to that application. An application context is automatically created when a request context is pushed if necessary.
Добавлено в версии 0.9.
псевдоним класса flask.ctx._AppCtxGlobals
Tries to locate the instance path if it was not provided to the constructor of the application class. It will basically calculate the path to a folder named instance next to your main file or the package.
Добавлено в версии 0.8.
Registers a function to be run before the first request to this instance of the application.
Добавлено в версии 0.8.
A lists of functions that should be called at the beginning of the first request to this instance. To register a function here, use the before_first_request() decorator.
Добавлено в версии 0.8.
Registers a function to run before each request.
A dictionary with lists of functions that should be called at the beginning of the request. The key of the dictionary is the name of the blueprint this function is active for, None for all requests. This can for example be used to open database connections or getting hold of the currently logged in user. To register a function here, use the before_request() decorator.
all the attached blueprints in a dictionary by name. Blueprints can be attached multiple times so this dictionary does not tell you how often they got attached.
Добавлено в версии 0.7.
Registers a template context processor function.
Creates the loader for the Jinja2 environment. Can be used to override just the loader and keeping the rest unchanged. It’s discouraged to override this function. Instead one should override the jinja_loader() function instead.
The global loader dispatches between the loaders of the application and the individual blueprints.
Добавлено в версии 0.7.
Добавлено в версии 0.5.
Creates a URL adapter for the given request. The URL adapter is created at a point where the request context is not yet set up so the request is passed explicitly.
Добавлено в версии 0.6.
Изменено в версии 0.9: This can now also be called without a request object when the URL adapter is created for the application context.
The debug flag. Set this to True to enable debugging of the application. In debug mode the debugger will kick in when an unhandled exception occurs and the integrated server will automatically reload the application if changes in the code are detected.
The logging format used for the debug logger. This is only used when the application is in debug mode, otherwise the attached logging handler does the formatting.
Добавлено в версии 0.3.
Default configuration parameters.
Called when an application context is popped. This works pretty much the same as do_teardown_request() but for the application context.
Добавлено в версии 0.9.
Called after the actual request dispatching and will call every as teardown_request() decorated function. This is not actually called by the Flask object itself but is always triggered when the request context is popped. That way we have a tighter control over certain resources under testing environments.
Изменено в версии 0.9: Added the exc argument. Previously this was always using the current exception information.
Enable the deprecated module support? This is active by default in 0.7 but will be changed to False in 0.8. With Flask 1.0 modules will be removed in favor of Blueprints
A decorator to register a function as an endpoint. Example:
| Параметры: | endpoint – the name of the endpoint |
|---|
error_handler_spec = None¶
A dictionary of all registered error handlers. The key is None for error handlers active on the application, otherwise the key is the name of the blueprint. Each key points to another dictionary where they key is the status code of the http exception. The special key None points to a list of tuples where the first item is the class for the instance check and the second the error handler function.
To register a error handler, use the errorhandler() decorator.
A decorator that is used to register a function give a given error code. Example:
You can also register handlers for arbitrary exceptions:
You can also register a function as error handler without using the errorhandler() decorator. The following example is equivalent to the one above:
Setting error handlers via assignments to error_handler_spec however is discouraged as it requires fiddling with nested dictionaries and the special case for arbitrary exception types.
The first None refers to the active blueprint. If the error handler should be application wide None shall be used.
Добавлено в версии 0.7: One can now additionally also register custom exception types that do not necessarily have to be a subclass of the HTTPException class.
| Параметры: | code – the code as integer for the handler |
|---|
extensions = None¶
a place where extensions can store application specific state. For example this is where an extension could store database engines and similar things. For backwards compatibility extensions should register themselves like this:
Добавлено в версии 0.7.
Dispatches the request and on top of that performs request pre and postprocessing as well as HTTP exception catching and error handling.
Добавлено в версии 0.7.
Provides default cache_timeout for the send_file() functions.
Добавлено в версии 0.9.
This attribute is set to True if the application started handling the first request.
Добавлено в версии 0.8.
Default exception handling that kicks in when an exception occurs that is not caught. In debug mode the exception will be re-raised immediately, otherwise it is logged and the handler for a 500 internal server error is used. If no such handler exists, a default 500 internal server error message is displayed.
Добавлено в версии 0.3.
Handles an HTTP exception. By default this will invoke the registered error handlers and fall back to returning the exception as response.
Добавлено в версии 0.3.
This method is called whenever an exception occurs that should be handled. A special case are HTTPException s which are forwarded by this function to the handle_http_exception() method. This function will either return a response value or reraise the exception with the same traceback.
Добавлено в версии 0.7.
Добавлено в версии 0.5.
Deprecated. Used to initialize the Jinja2 globals.
Добавлено в версии 0.5.
Изменено в версии 0.7: This method is deprecated with 0.7. Override create_jinja_environment() instead.
Injects the URL defaults for the given endpoint directly into the values dictionary passed. This is used internally and automatically called on URL building.
Добавлено в версии 0.7.
Holds the path to the instance folder.
Добавлено в версии 0.8.
The Jinja2 environment used to load templates.
The Jinja loader for this package bound object.
Добавлено в версии 0.5.
Options that are passed directly to the Jinja2 environment.
Добавлено в версии 0.8.
A logging.Logger object for this application. The default configuration is to log to stderr if the application is in debug mode. This logger can be used to (surprise) log messages. Here some examples:
Добавлено в версии 0.3.
The name of the logger to use. By default the logger name is the package name passed to the constructor.
Добавлено в версии 0.4.
Used to create the config attribute by the Flask constructor. The instance_relative parameter is passed in from the constructor of Flask (there named instance_relative_config ) and indicates if the config should be relative to the instance path or the root path of the application.
Добавлено в версии 0.8.
This method is called to create the default OPTIONS response. This can be changed through subclassing to change the default behavior of OPTIONS responses.
Добавлено в версии 0.7.
Добавлено в версии 0.7.
The following types are allowed for rv :
| response_class | the object is returned unchanged |
| str | a response object is created with the string as body |
| unicode | a response object is created with the string encoded to utf-8 as body |
| a WSGI function | the function is called as WSGI application and buffered as response object |
| tuple | A tuple in the form (response, status, headers) where response is any of the types defined here, status is a string or an integer and headers is a list of a dictionary with header values. |
| Параметры: | rv – the return value from the view function |
|---|
Изменено в версии 0.9: Previously a tuple was interpreted as the arguments for the response object.
The name of the application. This is usually the import name with the difference that it’s guessed from the run file if the import name is main. This name is used as a display name when Flask needs the name of the application. It can be set and overridden to change the value.
Добавлено в версии 0.8.
Opens a resource from the application’s resource folder. To see how this works, consider the following folder structure:
If you want to open the schema.sql file you would do the following:
A timedelta which is used to set the expiration date of a permanent session. The default is 31 days which makes a permanent session survive for roughly one month.
This attribute can also be configured from the config with the PERMANENT_SESSION_LIFETIME configuration key. Defaults to timedelta(days=31)
Called before the actual request dispatching and will call every as before_request() decorated function. If any of these function returns a value it’s handled as if it was the return value from the view and further request handling is stopped.
This also triggers the url_value_processor() functions before the actual before_request() functions are called.
Returns the value of the PRESERVE_CONTEXT_ON_EXCEPTION configuration value in case it’s set, otherwise a sensible default is returned.
Добавлено в версии 0.7.
Can be overridden in order to modify the response object before it’s sent to the WSGI server. By default this will call all the after_request() decorated functions.
Изменено в версии 0.5: As of Flask 0.5 the functions registered for after request execution are called in reverse order of registration.
Returns the value of the PROPAGATE_EXCEPTIONS configuration value in case it’s set, otherwise a sensible default is returned.
Добавлено в версии 0.7.
Registers a blueprint on the application.
Добавлено в версии 0.7.
Alternative error attach function to the errorhandler() decorator that is more straightforward to use for non decorator usage.
Добавлено в версии 0.7.
Registers a module with this application. The keyword argument of this function are the same as the ones for the constructor of the Module class and will override the values of the module if provided.
Изменено в версии 0.7: The module system was deprecated in favor for the blueprint system.
псевдоним класса flask.wrappers.Request
Creates a RequestContext from the given environment and binds it to the current context. This must be used in combination with the with statement because the request is only bound to the current context for the duration of the with block.
The object returned can also be used without the with statement which is useful for working in the shell. The example above is doing exactly the same as this code:
Изменено в версии 0.3: Added support for non-with statement usage and with statement is now passed the ctx object.
| Параметры: | environ – a WSGI environment |
|---|
response_class ¶
псевдоним класса flask.wrappers.Response
A decorator that is used to register a view function for a given URL rule. This does the same thing as add_url_rule() but is intended for decorator usage:
Runs the application on a local development server. If the debug flag is set the server will automatically reload for code changes and show a debugger in case an exception happened.
If you want to run the application in debug mode, but disable the code execution on the interactive debugger, you can pass use_evalex=False as parameter. This will keep the debugger’s traceback screen active, but disable code execution.
Изменено в версии 0.10: The default port is now picked from the SERVER_NAME variable.
If a secret key is set, cryptographic components can use this to sign cookies and other things. Set this to a complex random value when you want to use the secure cookie for instance.
Returns True if autoescaping should be active for the given template name.
Добавлено в версии 0.5.
Function used internally to send static files from the static folder to the browser.
Добавлено в версии 0.5.
The secure cookie uses this for the name of the session cookie.
This attribute can also be configured from the config with the SESSION_COOKIE_NAME configuration key. Defaults to ‘session’
the session interface to use. By default an instance of SecureCookieSessionInterface is used here.
Добавлено в версии 0.8.
This is called to figure out if an error should be ignored or not as far as the teardown system is concerned. If this function returns True then the teardown handlers will not be passed the error.
Добавлено в версии 0.10.
Registers a function to be called when the application context ends. These functions are typically also called when the request context is popped.
When ctx.pop() is executed in the above example, the teardown functions are called just before the app context moves from the stack of active contexts. This becomes relevant if you are using such constructs in tests.
Since a request context typically also manages an application context it would also be called when you pop a request context.
When a teardown function was called because of an exception it will be passed an error object.
Добавлено в версии 0.9.
A list of functions that are called when the application context is destroyed. Since the application context is also torn down if the request ends this is the place to store code that disconnects from databases.
Добавлено в версии 0.9.
Register a function to be run at the end of each request, regardless of whether there was an exception or not. These functions are executed when the request context is popped, even if not an actual request was performed.
When ctx.pop() is executed in the above example, the teardown functions are called just before the request context moves from the stack of active contexts. This becomes relevant if you are using such constructs in tests.
Generally teardown functions must take every necessary step to avoid that they will fail. If they do execute code that might fail they will have to surround the execution of these code by try/except statements and log occurring errors.
When a teardown function was called because of a exception it will be passed an error object.
In debug mode Flask will not tear down a request on an exception immediately. Instead if will keep it alive so that the interactive debugger can still access it. This behavior can be controlled by the PRESERVE_CONTEXT_ON_EXCEPTION configuration variable.
A dictionary with lists of functions that are called after each request, even if an exception has occurred. The key of the dictionary is the name of the blueprint this function is active for, None for all requests. These functions are not allowed to modify the request, and their return values are ignored. If an exception occurred while processing the request, it gets passed to each teardown_request function. To register a function here, use the teardown_request() decorator.
Добавлено в версии 0.7.
A dictionary with list of functions that are called without argument to populate the template context. The key of the dictionary is the name of the blueprint this function is active for, None for all requests. Each returns a dictionary that the template context is updated with. To register a function here, use the context_processor() decorator.
A decorator that is used to register custom template filter. You can specify a name for the filter, otherwise the function name will be used. Example:
| Параметры: | name – the optional name of the filter, otherwise the function name will be used. |
|---|
template_global ( name=None ) ¶
A decorator that is used to register a custom template global function. You can specify a name for the global function, otherwise the function name will be used. Example:
Добавлено в версии 0.10.
| Параметры: | name – the optional name of the global function, otherwise the function name will be used. |
|---|
template_test ( name=None ) ¶
A decorator that is used to register custom template test. You can specify a name for the test, otherwise the function name will be used. Example:
Добавлено в версии 0.10.
| Параметры: | name – the optional name of the test, otherwise the function name will be used. |
|---|
test_client ( use_cookies=True ) ¶
Note that if you are testing for assertions or exceptions in your application code, you must set app.testing = True in order for the exceptions to propagate to the test client. Otherwise, the exception will be handled by the application (not visible to the test client) and the only indication of an AssertionError or other exception will be a 500 status code response to the test client. See the testing attribute. For example:
The test client can be used in a with block to defer the closing down of the context until the end of the with block. This is useful if you want to access the context locals for testing:
See FlaskClient for more information.
Изменено в версии 0.4: added support for with block usage for the client.
Добавлено в версии 0.7: The use_cookies parameter was added as well as the ability to override the client to be used by setting the test_client_class attribute.
the test client that is used with when test_client is used.
Добавлено в версии 0.7.
Creates a WSGI environment from the given values (see werkzeug.test.EnvironBuilder() for more information, this function accepts the same arguments).
The testing flag. Set this to True to enable the test mode of Flask extensions (and in the future probably also Flask itself). For example this might activate unittest helpers that have an additional runtime cost which should not be enabled by default.
If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the default it’s implicitly enabled.
This is called for all HTTP exceptions raised by a view function. If it returns True for any exception the error handler for this exception is not called and it shows up as regular exception in the traceback. This is helpful for debugging implicitly raised HTTP exceptions.
Добавлено в версии 0.8.
Update the template context with some commonly used variables. This injects request, session, config and g into the template context as well as everything template context processors want to inject. Note that the as of Flask 0.6, the original values in the context will not be overridden if a context processor decides to return a value with the same key.
| Параметры: | context – the context as a dictionary that is updated in place to add extra variables. |
|---|
url_build_error_handlers = None¶
Добавлено в версии 0.9.
A dictionary with lists of functions that can be used as URL value preprocessors. The key None here is used for application wide callbacks, otherwise the key is the name of the blueprint. Each of these functions has the chance to modify the dictionary of URL values before they are used as the keyword arguments of the view function. For each function registered this one should also provide a url_defaults() function that adds the parameters automatically again that were removed that way.
Добавлено в версии 0.7.
Callback function for URL defaults for all view functions of the application. It’s called with the endpoint and values and should update the values passed in place.
The Map for this instance. You can use this to change the routing converters after the class was created but before any routes are connected. Example:
Registers a function as URL value preprocessor for all view functions of the application. It’s called before the view functions are called and can modify the url values provided.
A dictionary with lists of functions that can be used as URL value processor functions. Whenever a URL is built these functions are called to modify the dictionary of values in place. The key None here is used for application wide callbacks, otherwise the key is the name of the blueprint. Each of these functions has the chance to modify the dictionary
Добавлено в версии 0.7.
Enable this if you want to use the X-Sendfile feature. Keep in mind that the server has to support this. This only affects files sent with the send_file() method.
Добавлено в версии 0.2.
A dictionary of all view functions registered. The keys will be function names which are also used to generate URLs and the values are the function objects themselves. To register a view function, use the route() decorator.
wsgi_app ( environ, start_response ) ¶
The actual WSGI application. This is not implemented in __call__ so that middlewares can be applied without losing a reference to the class. So instead of doing this:
It’s a better idea to do this instead:
Then you still have the original application object around and can continue to call methods on it.
Объекты blueprint¶
Represents a blueprint. A blueprint is an object that records functions that will be called with the BlueprintSetupState later to register functions or other things on the main application. See Модульные приложения Flask с использованием blueprint’ов for more information.
Добавлено в версии 0.7.
Register a custom template filter, available application wide. Like Flask.add_template_filter() but for a blueprint. Works exactly like the app_template_filter() decorator.
| Параметры: | name – the optional name of the filter, otherwise the function name will be used. |
|---|
add_app_template_global ( f, name=None ) ¶
Register a custom template global, available application wide. Like Flask.add_template_global() but for a blueprint. Works exactly like the app_template_global() decorator.
Добавлено в версии 0.10.
| Параметры: | name – the optional name of the global, otherwise the function name will be used. |
|---|
add_app_template_test ( f, name=None ) ¶
Register a custom template test, available application wide. Like Flask.add_template_test() but for a blueprint. Works exactly like the app_template_test() decorator.
Добавлено в версии 0.10.
| Параметры: | name – the optional name of the test, otherwise the function name will be used. |
|---|
add_url_rule ( rule, endpoint=None, view_func=None, **options ) ¶
Like Flask.add_url_rule() but for a blueprint. The endpoint for the url_for() function is prefixed with the name of the blueprint.
Like Flask.after_request() but for a blueprint. Such a function is executed after each request, even if outside of the blueprint.
Like Flask.after_request() but for a blueprint. This function is only executed after each request that is handled by a function of that blueprint.
Like Flask.context_processor() but for a blueprint. Such a function is executed each request, even if outside of the blueprint.
Like Flask.errorhandler() but for a blueprint. This handler is used for all requests, even if outside of the blueprint.
Register a custom template filter, available application wide. Like Flask.template_filter() but for a blueprint.
| Параметры: | name – the optional name of the filter, otherwise the function name will be used. |
|---|
app_template_global ( name=None ) ¶
Register a custom template global, available application wide. Like Flask.template_global() but for a blueprint.
Добавлено в версии 0.10.
| Параметры: | name – the optional name of the global, otherwise the function name will be used. |
|---|
app_template_test ( name=None ) ¶
Register a custom template test, available application wide. Like Flask.template_test() but for a blueprint.
Добавлено в версии 0.10.
| Параметры: | name – the optional name of the test, otherwise the function name will be used. |
|---|
app_url_defaults ( f ) ¶
Same as url_defaults() but application wide.
Same as url_value_preprocessor() but application wide.
Like Flask.before_request() but for a blueprint. This function is only executed before each request that is handled by a function of that blueprint.
Like Flask.context_processor() but for a blueprint. This function is only executed for requests handled by a blueprint.
Registers an error handler that becomes active for this blueprint only. Please be aware that routing does not happen local to a blueprint so an error handler for 404 usually is not handled by a blueprint unless it is caused inside a view function. Another special case is the 500 internal server error which is always looked up from the application.
Otherwise works as the errorhandler() decorator of the Flask object.
Provides default cache_timeout for the send_file() functions.
Добавлено в версии 0.9.
Добавлено в версии 0.5.
The Jinja loader for this package bound object.
Добавлено в версии 0.5.
Creates an instance of BlueprintSetupState() object that is later passed to the register callback functions. Subclasses can override this to return a subclass of the setup state.
open_resource ( resource, mode=’rb’ ) ¶
Opens a resource from the application’s resource folder. To see how this works, consider the following folder structure:
If you want to open the schema.sql file you would do the following:
Registers a function that is called when the blueprint is registered on the application. This function is called with the state as argument as returned by the make_setup_state() method.
Works like record() but wraps the function in another function that will ensure the function is only called once. If the blueprint is registered a second time on the application, the function passed is not called.
register ( app, options, first_registration=False ) ¶
Called by Flask.register_blueprint() to register a blueprint on the application. This can be overridden to customize the register behavior. Keyword arguments from register_blueprint() are directly forwarded to this method in the options dictionary.
Like Flask.route() but for a blueprint. The endpoint for the url_for() function is prefixed with the name of the blueprint.
Function used internally to send static files from the static folder to the browser.
Добавлено в версии 0.5.
Like Flask.teardown_request() but for a blueprint. Such a function is executed when tearing down each request, even if outside of the blueprint.
Like Flask.teardown_request() but for a blueprint. This function is only executed when tearing down requests handled by a function of that blueprint. Teardown request functions are executed when the request context is popped, even when no actual request was performed.
Callback function for URL defaults for this blueprint. It’s called with the endpoint and values and should update the values passed in place.
Registers a function as URL value preprocessor for this blueprint. It’s called before the view functions are called and can modify the url values provided.
Данные входящих запросов¶
The request object used by default in Flask. Remembers the matched endpoint and view arguments.
The request object is a Request subclass and provides all of the attributes Werkzeug defines plus a few Flask specific ones.
MultiDict с разобранным содержимым строки запроса. (Это та часть URL, которая следует после знака вопроса).
dict с содержимым всех переменных браузера, переданных с запросом.
Заголовки поступившего запроса в виде словаря, как объекта.
Содержит данные поступившего запроса в виде строки в том случае, когда Flask не может обработать такой mimetype.
path ¶ script_root ¶ url ¶ base_url ¶ url_root ¶
Предоставляет различные способы представления текущего URL. Представим, что ваше приложение соответствует следующему URL:
А запросы пользователя поступают на такой URL:
В таком случае значения вышеупомянутых атрибутов станут вот такими:
| path | /page.html |
| script_root | /myapplication |
| base_url | http://www.example.com/myapplication/page.html |
| url | http://www.example.com/myapplication/page.html?x=y |
| url_root | http://www.example.com/myapplication/ |
is_xhr ¶
The name of the current blueprint
get_json ( force=False, silent=False, cache=True ) ¶
Parses the incoming JSON request data and returns it. If parsing fails the on_json_loading_failed() method on the request object will be invoked. By default this function will only load the json data if the mimetype is application/json but this can be overriden by the force parameter.
The get_json() method should be used instead.
Read-only view of the MAX_CONTENT_LENGTH config key.
The name of the current module if the request was dispatched to an actual module. This is deprecated functionality, use blueprints instead.
Called if decoding of the JSON data failed. The return value of this method is used by get_json() when an error occurred. The default implementation just raises a BadRequest exception.
Изменено в версии 0.10: Removed buggy previous behavior of generating a random JSON response. If you want that behavior back you can trivially add it by subclassing.
Добавлено в версии 0.8.
if matching the URL failed, this is the exception that will be raised / was raised as part of the request handling. This is usually a NotFound exception or something similar.
the internal URL rule that matched the request. This can be useful to inspect which methods are allowed for the URL from a before/after handler ( request.url_rule.methods ) etc.
Добавлено в версии 0.6.
class flask. request ¶
Объекты ответа¶
The response object that is used by default in Flask. Works like the response object from Werkzeug but is set to have an HTML mimetype by default. Quite often you don’t have to create this object yourself because make_response() will take care of that for you.
If you want to replace the response object used you can subclass this and set response_class to your subclass.
Строка со статусом ответа.
Статус ответа в виде целого числа.
The mimetype (content type without charset etc.)
Sets a cookie. The parameters are the same as in the cookie Morsel object in the Python standard library but it accepts unicode data, too.
Сессии¶
Если вы установили Flask.secret_key вы можете использовать сессии во Flask приложении. Сессия в основном используется для того, что бы запоминать информацию между запросами. Во Flask это реализовано при помощи подписанных cookies. Таким образом, пользователь может посмотреть на содержимое сессии, но не может изменить его пока он не знает секретный ключ, поэтому убедитесь, что ключ сложный и неопределяемый.
Для доступа к текущей сессии вы можете использовать объект session :
class flask. session ¶
Объект сессии работает почти как обычный словарь, с той разницей, что он следит за изменениями.
Следующие атрибуты интресны:
True если объект сессии был изменен. Имейте ввиду, что изменения изменяемых структур данных не отмечаются автоматически, в этой ситуации вы должны явно установить значение атрибута в True самостоятельно. Вот пример:
Если установлен в True то сессия будет жить permanent_session_lifetime секунд. По умолчанию 31 день. Если установлен в False (по умолчанию), сессия будет удалена как только пользователь закроет окно браузера.
Интерфейс сессий¶
Добавлено в версии 0.8.
Итерфейс сессий предоставляет простой способ замены имплементации сессий Flask.
class flask.sessions. SessionInterface ¶
If open_session() returns None Flask will call into make_null_session() to create a session that acts as replacement if the session support cannot work because some requirement is not fulfilled. The default NullSession class that is created will complain that the secret key was not set.
To replace the session interface on an application all you have to do is to assign flask.Flask.session_interface :
Добавлено в версии 0.8.
Helpful helper method that returns the cookie domain that should be used for the session cookie if session cookies are used.
Returns True if the session cookie should be httponly. This currently just returns the value of the SESSION_COOKIE_HTTPONLY config var.
Returns True if the cookie should be secure. This currently just returns the value of the SESSION_COOKIE_SECURE setting.
get_expiration_time ( app, session ) ¶
A helper method that returns an expiration date for the session or None if the session is linked to the browser session. The default implementation returns now + the permanent session lifetime configured on the application.
Checks if a given object is a null session. Null sessions are not asked to be saved.
This checks if the object is an instance of null_session_class by default.
Creates a null session which acts as a replacement object if the real session support could not be loaded due to a configuration error. This mainly aids the user experience because the job of the null session is to still support lookup without complaining but modifications are answered with a helpful error message of what failed.
This creates an instance of null_session_class by default.
make_null_session() will look here for the class that should be created when a null session is requested. Likewise the is_null_session() method will perform a typecheck against this type.
A flag that indicates if the session interface is pickle based. This can be used by flask extensions to make a decision in regards to how to deal with the session object.
Добавлено в версии 0.10.
This is called for actual sessions returned by open_session() at the end of the request. This is still called during a request context so if you absolutely need access to the request you can do that.
class flask.sessions. SecureCookieSessionInterface ¶
The default session interface that stores sessions in signed cookies through the itsdangerous module.
the hash function to use for the signature. The default is sha1
the name of the itsdangerous supported key derivation. The default is hmac.
the salt that should be applied on top of the secret key for the signing of cookie based sessions.
This is called for actual sessions returned by open_session() at the end of the request. This is still called during a request context so if you absolutely need access to the request you can do that.
A python serializer for the payload. The default is a compact JSON derived serializer with support for some extra Python types such as datetime objects or tuples.
class flask.sessions. SecureCookieSession ( initial=None ) ¶
Baseclass for sessions based on signed cookies.
class flask.sessions. NullSession ( initial=None ) ¶
Class used to generate nicer error messages if sessions are not available. Will still allow read-only access to the empty session but fail on setting.
class flask.sessions. SessionMixin ¶
Expands a basic dictionary with an accessors that are expected by Flask extensions and users for the session.
some session backends can tell you if a session is new, but that is not necessarily guaranteed. Use with caution. The default mixin implementation just hardcodes False in.
this reflects the ‘_permanent’ key in the dict.
A customized JSON serializer that supports a few extra types that we take for granted when serializing (tuples, markup objects, datetime).
Этот объект предоставляет методы сериализации и десериализации похожие на simplejson, но так же конвертирует некоторые встроенные объекты Python, которые обычно появляются в сессиях. На данный момент следующие расширенные значения поддерживаются в JSON при дампе:
Ключ конфигурации PERMANENT_SESSION_LIFETIME может так же быть числом начиная с версии Flask 0.8. Вы можете использовать атрибут permanent_session_lifetime в приложении с автоматической конвертацией результата в число.
Тестовый клиент¶
Basic usage is outlined in the Тестирование приложений Flask chapter.
When used in combination with a with statement this opens a session transaction. This can be used to modify the session that the test client uses. Once the with block is left the session is stored back.
Internally this is implemented by going through a temporary test request context and since session handling could depend on request variables this function accepts the same arguments as test_request_context() which are directly passed through.
Глобальные переменные¶
Просто храните здесь все что хотите. Например соединение с базой данных или пользователя, который сейчас авторизирован.
Начиная с Flask 0.10 это хранится в контексте приложения и не зависит от контекста запроса, что делает их доступными уже в момент создани контекста приложения, но еще до создания запроса. Это особенно полезно когда используется подход Подделка ресурсов и контекста для тестирования.
Дополнительно с версии 0.10 вы можете использовать метод get() для получения значения атрибута или None (или второго аргумента метода get() ) если значение отсутствует. Эти две строки эквивалентны:
Так же допускается использование оператора in на этом объекте для проверки на существование ключа в объекте.
Полезные функции и классы¶
If you have code that wants to test if a request context is there or not this function can be used. For instance, you may want to take advantage of request information if the request object is available, but fail silently if it is unavailable.
Alternatively you can also just test any of the context bound objects (such as request or g for truthness):
Добавлено в версии 0.7.
A helper function that decorates a function to retain the current request context. This is useful when working with greenlets. The moment the function is decorated a copy of the request context is created and then pushed when the function is called.
Добавлено в версии 0.10.
Works like has_request_context() but for the application context. You can also just do a boolean check on the current_app object instead.
Добавлено в версии 0.9.
Generates a URL to the given endpoint with the method provided.
This will reference the index function local to the current blueprint:
Добавлено в версии 0.10: The _scheme parameter was added.
Добавлено в версии 0.9: The _anchor and _method parameters were added.
| Параметры: | code – код ответа HTTP. |
|---|
flask. redirect ( location, code=302, Response=None ) ¶
Returns a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, and 307. 300 is not supported because it’s not a real redirect and 304 because it’s the answer for a request with a request with defined If-Modified-Since headers.
Добавлено в версии 0.6: The location can now be a unicode string that is encoded using the iri_to_uri() function.
Добавлено в версии 0.10: The class used for the Response object can now be passed in.
Sometimes it is necessary to set additional headers in a view. Because views do not have to return response objects but can return a value that is converted into a response object by Flask itself, it becomes tricky to add headers to it. This function can be called instead of using a return and you will get a response object which you can use to attach headers.
If view looked like this and you want to add a new header:
You can now do something like this:
This function accepts the very same arguments you can return from a view function. This for example creates a response with a 404 error code:
The other use case of this function is to force the return value of a view function into a response which is helpful with view decorators:
Internally this function does the following things:
Добавлено в версии 0.6.
Executes a function after this request. This is useful to modify response objects. The function is passed the response object and has to return the same or a new one.
This is more useful if a function other than the view function wants to modify a response. For instance think of a decorator that wants to add some headers without converting the return value into a response object.
Добавлено в версии 0.9.
By default it will try to guess the mimetype for you, but you can also explicitly provide one. For extra security you probably want to send certain files as attachment (HTML for instance). The mimetype guessing requires a filename or an attachment_filename to be provided.
Please never pass filenames to this function from user sources without checking them first. Something like this is usually sufficient to avoid security problems:
Добавлено в версии 0.2.
Изменено в версии 0.7: mimetype guessing and etag support for file objects was deprecated because it was unreliable. Pass a filename if you are able to, otherwise attach an etag yourself. This functionality will be removed in Flask 1.0
Изменено в версии 0.9: cache_timeout pulls its default from application config, when None.
Sending files and Performance
It is strongly recommended to activate either X-Sendfile support in your webserver or (if no authentication happens) to tell the webserver to serve files for the given path on its own without calling into the web application for improved performance.
Добавлено в версии 0.5.
flask. escape ( s ) → markup¶
class flask. Markup ¶
A string that is ready to be safely inserted into an HTML or XML document, either because it was escaped or because it was marked safe.
Passing an object to the constructor converts it to text and wraps it to mark it safe without escaping. To escape the text, use the escape() class method instead.
This implements the __html__() interface that some frameworks use. Passing an object that implements __html__() will wrap the output of that method, marking it safe.
This is a subclass of the text type ( str in Python 3, unicode in Python 2). It has the same methods as that type, but all methods escape their arguments and return a Markup instance.
Escape a string. Calls escape() and ensures that for subclasses the correct type is returned.
unescape() the markup, remove tags, and normalize whitespace to single spaces.
Convert escaped markup back into a text string. This replaces HTML entities with the characters they represent.
Передача сообщений¶
Изменено в версии 0.3: category parameter added.
Изменено в версии 0.3: with_categories parameter added.
Изменено в версии 0.9: category_filter parameter added.
Поддержка JSON¶
Для начала попробуем следующее:
Вместо этого можно просто сделать так:
В качестве примера использования прочитайте документацию к json в стандартной библиотеке. Следующие расширения по умолчанию добавлены в стандартный JSON модуль:
Функция htmlsafe_dumps() этого json модуля также доступна через вызов фильтра |tojson в Jinja2. Заметьте, что внутри script тегов данные экранируются, так что убедитесь, что вы отключили экранирование с |safe если вы хотите исопльзовать внутри script теги:
Автосортировка ключей JSON
Переменная конфигурации JSON_SORT_KEYS ( Обработка конфигурации Flask ) может быть установлена в false для предотвращения автосортировки ключей в Flask. По умолчанию сортировка включена и вне контекста приложения сортировка так же включена.
Заметьте, что отключение сортировки ключей может вызвать проблемы при кэшировании результата.
Creates a Response with the JSON representation of the given arguments with an application/json mimetype. The arguments to this function are the same as to the dict constructor.
This will send a JSON response like this to the browser:
This function’s response will be pretty printed if it was not requested with X-Requested-With: XMLHttpRequest to simplify debugging unless the JSONIFY_PRETTYPRINT_REGULAR config parameter is set to false.
Добавлено в версии 0.2.
Serialize obj to a JSON formatted str by using the application’s configured encoder ( json_encoder ) if there is an application on the stack.
This function can return unicode strings or ascii-only bytestrings by default which coerce into unicode strings automatically. That behavior by default is controlled by the JSON_AS_ASCII configuration variable and can be overriden by the simplejson ensure_ascii parameter.
Like dumps() but writes into a file object.
Unserialize a JSON object from a string s by using the application’s configured decoder ( json_decoder ) if there is an application on the stack.
Like loads() but reads from a file object.
class flask.json. JSONEncoder ( *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None ) ¶
The default Flask JSON encoder. This one extends the default simplejson encoder by also supporting datetime objects, UUID as well as Markup objects which are serialized as RFC 822 datetime strings (same as the HTTP date format). In order to support more data types override the default() method.
For example, to support arbitrary iterators, you could implement default like this:
Отрисовка шаблонов¶
Renders a template from the template folder with the given context.
Renders a template from the given template source string with the given context.
Loads a macro (or variable) a template exports. This can be used to invoke a macro from within Python code. If you for example have a template named _cider.html with the following contents:
You can access this from Python code like this:
Добавлено в версии 0.2.
Конфигурация¶
Works exactly like a dict but provides ways to fill it from files or special dictionaries. There are two common patterns to populate the config.
Either you can fill the config from a config file:
Or alternatively you can define the configuration options in the module that calls from_object() or provide an import path to a module that should be loaded. It is also possible to tell it to use the same module and with that provide the configuration values just before the call:
In both cases (loading from any Python file or loading from modules), only uppercase keys are added to the config. This makes it possible to use lowercase values in the config file for temporary values that are not added to the config or to define the config keys in the same file that implements the application.
Probably the most interesting way to load configurations is from an environment variable pointing to a file:
In this case before launching the application you have to set this environment variable to the file you want to use. On Linux and OS X use the export statement:
On windows use set instead.
Loads a configuration from an environment variable pointing to a configuration file. This is basically just a shortcut with nicer error messages for this line of code:
bool. True if able to load config, False otherwise.
Updates the values from the given object. An object can be of one of the following two types:
Objects are usually either modules or classes.
Just the uppercase variables in that object are stored in the config. Example usage:
You should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with from_pyfile() and ideally from a location not within the package because the package might be installed system wide.
| Параметры: | obj – an import name or object |
|---|
from_pyfile ( filename, silent=False ) ¶
Updates the values in the config from a Python file. This function behaves as if the file was imported as module with the from_object() function.
Добавлено в версии 0.7: silent parameter.
Расширения¶
Этот модуль отвечает за перенаправление импорта к расширениям Flask. Он был добавлен в версии 0.8 как канонический путь для импорта расширений Flask и дает нам возможность создавать расширяемые и распространяемые дополнения.
Если вы хотите использовать расширение с именем “Flask-Foo” вы должны импортировать его из ext как указано:
Добавлено в версии 0.8.
Потоки¶
Request contexts disappear when the response is started on the server. This is done for efficiency reasons and to make it less likely to encounter memory leaks with badly written WSGI middlewares. The downside is that if you are using streamed responses, the generator cannot access request bound information any more.
This function however can help you keep the context around for longer:
Alternatively it can also be used around a specific generator:
Добавлено в версии 0.9.
Внутренние дополнения¶
The request context contains all request relevant information. It is created at the beginning of the request and pushed to the _request_ctx_stack and removed at the end of it. It will create the URL adapter and request object for the WSGI environment provided.
Do not attempt to use this class directly, instead use test_request_context() and request_context() to create this object.
When the request context is popped, it will evaluate all the functions registered on the application for teardown execution ( teardown_request() ).
The request context is automatically popped at the end of the request for you. In debug mode the request context is kept around if exceptions happen so that interactive debuggers have a chance to introspect the data. With 0.4 this can also be forced for requests that did not fail and outside of DEBUG mode. By setting ‘flask._preserve_context’ to True on the WSGI environment the context will not pop itself at the end of the request. This is used by the test_client() for example to implement the deferred cleanup functionality.
You might find this helpful for unittests where you need the information from the context local around for a little longer. Make sure to properly pop() the stack yourself in that situation, otherwise your unittests will leak memory.
Creates a copy of this request context with the same request object. This can be used to move a request context to a different greenlet. Because the actual request object is the same this cannot be used to move a request context to a different thread unless access to the request object is locked.
Добавлено в версии 0.10.
Can be overridden by a subclass to hook into the matching of the request.
Pops the request context and unbinds it by doing that. This will also trigger the execution of functions registered by the teardown_request() decorator.
Изменено в версии 0.9: Added the exc argument.
Binds the request context to the current context.
Внутренний класс LocalStack используется для имплементации всех локальных контекстных объектов используемых в Flask. Это документированный инстанс и может быть использован в коде расширений или приложений но использовать его не рекомендуется.
Следующие атрибуты всегда доступны на каждом слое стэка:
The application context binds an application object implicitly to the current thread or greenlet, similar to how the RequestContext binds request information. The application context is also implicitly created if a request context is created but the application is not on top of the individual application context.
Pops the app context.
Binds the app context to the current context.
Работает аналогично контексту запроса только привязан к приложению. Используется в основном расширениями для хранения данных.
Добавлено в версии 0.9.
Temporary holder object for registering a blueprint with the application. An instance of this class is created by the make_setup_state() method and later passed to all register callback functions.
add_url_rule ( rule, endpoint=None, view_func=None, **options ) ¶
A helper method to register a rule (and optionally a view function) to the application. The endpoint is automatically prefixed with the blueprint’s name.
a reference to the current application
a reference to the blueprint that created this setup state.
as blueprints can be registered multiple times with the application and not everything wants to be registered multiple times on it, this attribute can be used to figure out if the blueprint was registered in the past already.
a dictionary with all options that were passed to the register_blueprint() method.
The subdomain that the blueprint should be active for, None otherwise.
A dictionary with URL defaults that is added to each and every URL that was defined with the blueprint.
The prefix that should be used for all URLs defined on the blueprint.
Сигналы¶
Добавлено в версии 0.6.
True if the signaling system is available. This is the case when blinker is installed.
This signal is sent when a template was successfully rendered. The signal is invoked with the instance of the template as template and the context as dictionary (named context ).
This signal is sent when the application is tearing down the request. This is always called, even if an error happened. An exc keyword argument is passed with the exception that caused the teardown.
Изменено в версии 0.9: The exc parameter was added.
This signal is sent when the application is tearing down the application context. This is always called, even if an error happened. An exc keyword argument is passed with the exception that caused the teardown. The sender is the application.
This signal is sent when an application context is pushed. The sender is the application.
Добавлено в версии 0.10.
This signal is sent when an application context is popped. The sender is the application. This usually falls in line with the appcontext_tearing_down signal.
Добавлено в версии 0.10.
Добавлено в версии 0.10.
An alias for blinker.base.Namespace if blinker is available, otherwise a dummy class that creates fake signals. This class is available for Flask extensions that want to provide the same fallback system as Flask itself.
Creates a new signal for this namespace if blinker is available, otherwise returns a fake signal that has a send method that will do nothing but will fail with a RuntimeError for all other operations, including connecting.
Class-Based Views¶
Добавлено в версии 0.7.
Alternative way to use view functions. A subclass has to implement dispatch_request() which is called with the view arguments from the URL routing system. If methods is provided the methods do not have to be passed to the add_url_rule() method explicitly:
When you want to decorate a pluggable view you will have to either do that when the view function is created (by wrapping the return value of as_view() ) or you can use the decorators attribute:
The decorators stored in the decorators list are applied one after another when the view function is created. Note that you can not use the class based decorators since those would decorate the view class and not the generated view function!
classmethod as_view ( name, *class_args, **class_kwargs ) ¶
Converts the class into an actual view function that can be used with the routing system. Internally this generates a function on the fly which will instantiate the View on each request and call the dispatch_request() method on it.
The arguments passed to as_view() are forwarded to the constructor of the class.
The canonical way to decorate class-based views is to decorate the return value of as_view(). However since this moves parts of the logic from the class declaration to the place where it’s hooked into the routing system.
You can place one or more decorators in this list and whenever the view function is created the result is automatically decorated.
Добавлено в версии 0.8.
Subclasses have to override this method to implement the actual view function code. This method is called with all the arguments from the URL rule.
A for which methods this pluggable view can handle.
class flask.views. MethodView ¶
Like a regular class-based view but that dispatches requests to particular methods. For instance if you implement a method called get() it means you will response to ‘GET’ requests and the dispatch_request() implementation will automatically forward your request to that. Also options is set for you automatically:
Subclasses have to override this method to implement the actual view function code. This method is called with all the arguments from the URL rule.
URL Route Registrations¶
Generally there are three ways to define rules for the routing system:
Variable parts are passed to the view function as keyword arguments.
The following converters are available:
| string | accepts any text without a slash (the default) |
| int | accepts integers |
| float | like int but for floating point values |
| path | like the default but also accepts slashes |
Here are some examples:
An important detail to keep in mind is how Flask deals with trailing slashes. The idea is to keep each URL unique so the following rules apply:
This is consistent with how web servers deal with static files. This also makes it possible to use relative link targets safely.
You can also define multiple rules for the same function. They have to be unique however. Defaults can also be specified. Here for example is a definition for a URL that accepts an optional page:
Here are the parameters that route() and add_url_rule() accept. The only difference is that with the route parameter the view function is defined with the decorator instead of the view_func parameter.
View Function Options¶
For internal usage the view functions can have some attributes attached to customize behavior the view function would normally not have control over. The following attributes can be provided optionally to either override some defaults to add_url_rule() or general behavior:
Добавлено в версии 0.8: The provide_automatic_options functionality was added.

