falcon python что это
Falcon
A Big Thank You to Our Project Patrons
Falcon is a blazing fast, minimalist Python web API framework for building robust app backends and microservices. The framework works great with both asyncio (ASGI) and gevent/meinheld (WSGI).
Reliable
LinkedIn, Paypal, Wargaming, GOVCERT.LU, and many others rely on Falcon to power mission-critical services. Falcon focuses on stability, correctness, and performance at scale.
RESTful
The Falcon web framework encourages the REST architectural style. Resource classes implement HTTP method handlers that resolve requests and perform state transitions.
Complementary
Falcon complements more general Python web frameworks by providing extra reliability, flexibility, and performance wherever you need it.
Extensible
A number of Falcon add-ons, templates, and complementary packages are available for use in your projects. We’ve listed several of these on the Falcon wiki as a starting point, but you may also wish to search PyPI for additional resources.
Compatible
Thanks to ASGI and WSGI, Falcon runs on a large variety of web servers and platforms. Falcon works great with CPython 3.5+. Or try PyPy for an extra speed boost!
Design
We designed Falcon to support the demanding needs of large-scale microservices and responsive app backends. Falcon complements more general Python web frameworks by providing extra performance, reliability, and flexibility wherever you need it.
Reliable. We go to great lengths to avoid introducing breaking changes, and when we do they are fully documented and only introduced (in the spirit of SemVer) with a major version increment. The code is rigorously tested with numerous inputs and we require 100% coverage at all times. Falcon has no dependencies outside the standard library, helping minimize your app’s attack surface while avoiding transitive bugs and breaking changes.
Debuggable. Falcon eschews magic. It’s easy to tell which inputs lead to which outputs. Unhandled exceptions are never encapsulated or masked. Potentially surprising behaviors, such as automatic request body parsing, are well-documented and disabled by default. Finally, when it comes to the framework itself, we take care to keep logic paths simple and understandable. All this makes it easier to reason about the code and to debug edge cases in large-scale deployments.
Fast. Same hardware, more requests. Falcon turns around requests significantly faster than other popular Python frameworks like Django and Flask. For an extra speed boost, Falcon compiles itself with Cython when available, and also works well with PyPy. Considering a move to another programming language? Benchmark with Falcon+PyPy first!
Flexible. Falcon leaves a lot of decisions and implementation details to you, the API developer. This gives you a lot of freedom to customize and tune your implementation. It also helps you understand your apps at a deeper level, making them easier to tune, debug, and refactor over the long run. Falcon’s minimalist design provides space for Python community members to independently innovate on Falcon add-ons and complementary packages.
Perfection is finally attained not when there is no longer anything to add, but when there is no longer anything to take away.
Antoine de Saint-Exupéry
Features
Don’t lower your expectations to meet your performance. Raise your level of performance to meet your expectations. Expect the best of yourself, and then do what is necessary to make it a reality.
Benchmarks
To give you a feel for Falcon’s performance, we’ve included the results of running a simple benchmark across several popular Python web frameworks.
Please note, however, that this benchmark is by no means comprehensive; it is only meant to provide a rough performance comparison between the given frameworks, and to demonstrate the baseline per-request overhead each framework incurs on an application.
As with any benchmark, you should take these numbers with a grain of salt. You should always run your own tests against your specific use case to discover what best suits your needs.
Scenario. The benchmark acts as a WSGI server and performs a GET request directly on each framework’s PEP-3333 app. Requests are not sent over the network, since the performance of a given network or web server is not related to the performance of the WSGI frameworks themselves. Regardless, each app parses a route template with a single embedded parameter, reads a query parameter and a header from the request data, sets an x-header on the response, and finally returns a 10 KiB body, randomly generated.
Method. 50,000 iterations were executed per trial (100,000 for the PyPy tests), and the best time was recorded for each framework over 20 trials. The order in which the frameworks were tested was randomized for each trial. Also, garbage collection was enabled as it would be in a production environment, and a full collection was forcefully triggered before each trial. Finally, results were calculated using the Decimal class, and rounded to the nearest whole number.
Platform. Benchmarks were executed by running the corresponding Docker images on a Google Compute Engine instance (Intel Skylake, 1vCPU, 2 GB RAM), running Ubuntu 18.04 with all system packages updated to their latest versions as of May 2019. The frameworks were tested on several different versions of Python.
CPython 3.7.3
PyPy3 7.0.0
Extended Test
Falcon was also benchmarked under CPython 3.7 with a more realistic scenario, in which the routing table had multiple entries, the query string contained percent-encoded characters, and several complex response headers were set in the response. Note that even when Falcon is doing more work, it still is able to outperform other frameworks, which are only doing the bare minimum to construct a response.
In order to be great, you just have to care. You have to care about your world, community, and equality.
Community
Falcon is an Apache-licensed community project, built and supported by stylish volunteers from around the world.
Check out the Falcon talks, podcasts, and blog posts wiki page to learn more about the project, and to add your own resources.
A number of Falcon add-ons, templates, and complementary packages are available for use in your projects. We’ve listed several of these on the Falcon wiki as a starting point, but you may also wish to search PyPI for additional resources.
The Falconry community on Gitter is a great place to ask questions and share your ideas. You can find us in falconry/user. We also have a falconry/dev room for discussing the design and development of the framework itself.
Per our Code of Conduct, we expect everyone who participates in community discussions to act professionally. Please lead by example in encouraging constructive discussions. Each individual in the community is responsible for creating a positive, constructive, and productive culture.
Kurt Griffiths (kgriffs on GH, Gitter, and Twitter) is the original creator and primary maintainer of the Falcon framework. Kurt is generously assisted by members of the core project team, including John Vrbanac (jmvrbanac on GH and Gitter, and jvrbanac on Twitter), Vytautas Liuolia (vytas7 on GH and Gitter), and Nick Zaccardi (nZac on GH and Gitter).
We are all inventors, each sailing out on a voyage of discovery, guided each by a private chart, of which there is no duplicate. The world is all gates, all opportunities.
Ralph Waldo Emerson
Become a Patron
Falcon is an Apache-licensed community project, and is free to use. However, the large amount of time and effort needed to maintain the project and develop new features is not sustainable without the generous financial support of community members like you.
Please consider helping us secure the future of the Falcon framework with a one-time or recurring donation.
Your donation comes with some great perks, such as having your name listed in the BACKERS.md file, having your logo displayed on this website and in the docs, awesome T-shirts and glow-in-the-dark buttons, plus access to prioritized support from Falcon’s core maintainers.
Project donations help subsidize the cost for Falcon’s core maintainers team to maintain ecosystem projects and to engage with the community at PyCon and other venues.
Развёртывание приложений Falcon с помощью Gunicorn и Nginx в Ubuntu 16.04
Falcon – это микрофреймворк Python для создания веб-приложений. Он отлично подходит для сборки API согласно архитектуре REST. Это высокопроизводительный фреймворк, который позволяет создавать приложения с наименьшим ущербом для скорости разработки.
Данное руководство поможет собрать и развернуть веб-приложение Falcon. Falcon является фреймворком WSGI, потому для работы веб-приложения потребуется Gunicorn, сервер приложений WSGI. Веб-сервер Nginx можно использовать в качестве обратного прокси-сервера, который будет обрабатывать входящие запросы и передавать их серверу Gunicorn.
Требования
Все дополнительные инструкции можно найти здесь.
1: Создание виртуальной среды Python
Приложение Falcon нужно изолировать от других файлов Python. Для этого используется виртуальная среда (virtual environment). Чтобы создать такую среду, нужно установить инструмент virtualenv.
Примечание: Falcon может работать в Python 2.х и в Python 3.х. В данном руководстве используется Python 3.5.
sudo apt-get install virtualenv
Теперь нужно создать и открыть родительский каталог проекта:
mkdir falcon_app
cd falcon_app
Создайте виртуальную среду для хранения файлов проекта:
Это создаст локальную копию Python и pip в каталоге venv. Флаг –p позволяет указать версию Python, которую нужно использовать в среде.
Вы увидите такой результат:
Already using interpreter /usr/bin/python3
Using base prefix ‘/usr’
New python executable in /home/8host/falcon_app/venv/bin/python3
Also creating executable in /home/8host/falcon_app/venv/bin/python
Installing setuptools, pkg_resources, pip, wheel. done.
Теперь включите виртуальную среду:
Примечание: Чтобы отключить виртуальную среду и вернуться в стандартную оболочку, введите:
2: Установка Falcon и Gunicorn
Теперь нужно установить пакеты falcon и Gunicorn. Все это можно установить с помощью пакетного менеджера pip.
Falcon можно установить двумя способами. Вы можете установить бинарный файл Falcon с помощью команды pip install falcon. Но в сочетании с Cython фреймворк Falcon может увеличить свою производительность. Чтобы установить Cython, сообщить об этом Falcon и собрать пакет с помощью компилятора С, введите:
pip install gunicorn
3: Создание простого приложения Falcon
Для работы вам понадобится приложение Falcon. Напишите простое веб-приложение. Создайте файл main.py в каталоге falcon_app.
Добавьте в файл следующий код, чтобы создать простое приложение Falcon, которое будет выводить на экран какое-нибудь текстовое сообщение:
import falcon
class TestResource(object):
def on_get(self, req, res):
«»»Handles all GET requests.»»»
res.status = falcon.HTTP_200 # Статус по умолчанию
res.body = (‘This is me, Falcon, serving a resource!’)
# Создание объекта приложения Falcon
app = falcon.API()
# Добавление класса TestResource
test_resource = TestResource()
# Определение маршрута
app.add_route(‘/test’, test_resource)
Этот файл объявляет класс TestResource. Этот класс содержит метод on_get, который определяет ответ, который будет отправлен. После этого создаются экземпляры Falcon API и TestResource. В завершение нужно указать маршрут /test к API и приложить объект test_resource.
При отправке GET-запроса на URL-адрес /test запускается метод on_get() класса TestResource. Состояние и тело ответа указываются в переменных res.status и res.body соответственно.
4: Обслуживание приложения Falcon с помощью Gunicorn
Прежде чем приступить к настройке производства и Nginx, нужно убедиться, что сервер приложений Gunicorn может обслужить созданное только что приложение.
Откройте каталог falcon_app и запустите сервер Gunicorn:
Эта команда запустит Gunicorn и начнёт обслуживать веб-приложение на 0.0.0.0 и порте 5000, о чём вы можете узнать из вывода:
[2016-11-14 16:33:41 +0000] [9428] [INFO] Starting gunicorn 19.6.0
[2016-11-14 16:33:41 +0000] [9428] [INFO] Listening at: http://0.0.0.0:5000 (9428)
[2016-11-14 16:33:41 +0000] [9428] [INFO] Using worker: sync
[2016-11-14 16:33:41 +0000] [9431] [INFO] Booting worker with pid: 9431
Вы можете использовать любой свободный порт выше 1024.
Опция main:app вызывает объект приложения app из файла main.py.
С помощью опции –reload сервер Gunicorn может отслеживать изменения кода без перезагрузки.
Чтобы проверить работу приложения, откройте веб-браузер и посетите страницу:
На экране появится сообщение:
This is me, Falcon, serving a resource!
Остановите сервер Gunicorn с помощью CTRL+C.
5: Настройка обратного прокси-сервера Nginx
Теперь приложение готово. Настройте Nginx как обратный прокси-сервер, чтобы сервер Gunicorn не обслуживал все запросы напрямую.
При использовании обратного прокси все запросы сначала попадут на Nginx, откуда они будут переданы на Gunicorn.
sudo apt-get install nginx
Создайте конфигурационный файл falcon_app.conf в каталоге /etc/nginx/sites-available, в котором будут храниться настройки обратного прокси-сервера Nginx.
sudo nano /etc/nginx/sites-available/falcon_app.conf
Добавьте в файл такие настройки:
server <
listen 80;
server_name your_server_ip_or_domain;
location / <
include proxy_params;
proxy_pass http://localhost:5000;
>
>
Nginx будет прослушивать порт 80 и проксировать все запросы HTTP на http://localhost:5000, который будет прослушиваться сервером Gunicorn.
Включите этот файл с помощью символьной ссылки:
Отключите стандартные настройки Nginx, удалив символьную ссылку из каталога /etc/nginx/sites-enabled.
sudo rm /etc/nginx/sites-enabled/default
Проверьте ошибки в конфигурационных файлах Nginx:
Если ошибок нет, вы увидите:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
Если команда обнаружила ошибки, исправьте их и повторите проверку.
Перезапустите Nginx, чтобы обновить настройки:
sudo systemctl restart nginx
Снова запустите сервер Gunicorn, но вместо 0.0.0.0 укажите localhost (чтобы заблокировать общий доступ к Gunicorn):
Откройте порт 80 в брандмауэре:
Примечание: Если вы используете https, разблокируйте в ufw порт 443.
Вы должны увидеть то же сообщение, что и в предыдущий раз:
This is me, Falcon, serving a resource!
Обратите внимание: в этот раз не нужно указывать номер порта в ссылке, поскольку теперь все запросы обслуживает Nginx, который прослушивает стандартный HTTP-порт 80.
Чтобы остановить приложение, нажмите CTRL+C.
6: Управление Gunicorn с помощью Systemd
Теперь нужно настроить автозапуск приложения.
В случае перезагрузки сервера сервер Gunicorn должен запускаться самостоятельно.
sudo nano /etc/systemd/system/falcon_app.service
Для начала добавьте раздел [Unit], который определяет метаданные и зависимости приложения. Внесите в него описание сервиса.
[Unit] Description=Gunicorn instance to serve the falcon application
After=network.target
Затем нужно добавить раздел [Service]. В нем нужно указать пользователя и группу, с помощью которых будет запущен сервис. Передайте текущему пользователю права на процесс и соответствующие файлы. Также права должна иметь группа www-data, тогда веб-сервер Nginx сможет взаимодействовать с процессом Gunicorn.
Также нужно указать виртуальную среду Python, рабочий каталог приложения и команду, с помощью которой будет запущено приложение.
Команду для запуска Gunicorn нужно присвоить переменной ExecStart. Флаг –workers определяет количество рабочих процессов Gunicorn. Согласно документации Gunicorn, рабочих процессов должно быть 2n+1, где n – количество ядер CPU. То есть, если сервер имеет одно ядро CPU, нужно настроить 3 рабочих процесса.
Переменные ExecReload и ExecStop отвечают за запуск и остановку сервиса.
В завершение нужно добавить раздел [Install], который определяет, к чему должен подключиться сервис во время автозапуска.
Директива WantedBy создаёт каталог multi-user.target в /etc/systemd/system, а в нём создаёт символическую ссылку на этот файл. При отключении сервиса ссылка будет удалена.
Сохраните и закройте файл. Запустите сервис:
sudo systemctl start falcon_app
Включите сервис, чтобы настроить автозапуск Gunicorn.
sudo systemctl enable falcon_app
Снова направьте браузер на http://your_server_ip/test и просмотрите приложение. Серверы Nginx и Gunicorn работают в фоновом режиме. Чтобы обновить приложение Falcon, перезапустите сервис falcon_app:
sudo systemctl restart falcon_app
Заключение
Теперь вы умеете разворачивать веб-приложения Falcon и обслуживать их с помощью сервера приложений Gunicorn, создавать виртуальную среду Python, настраивать обратный прокси-сервер Nginx и писать Unit-файлы.
falcon 3.0.1
pip install falcon Copy PIP instructions
Released: May 10, 2021
An unladen web framework for building APIs and app backends.
Navigation
Project links
Statistics
View statistics for this project via Libraries.io, or by using our public dataset on Google BigQuery
License: Apache Software License (Apache 2.0)
Tags wsgi, web, api, framework, rest, http, cloud
Requires: Python >=3.5
Maintainers
Classifiers
Project description
The Falcon Web Framework
Falcon is a reliable, high-performance Python web framework for building large-scale app backends and microservices. It encourages the REST architectural style, and tries to do as little as possible while remaining highly effective.
Falcon apps work with any WSGI or ASGI server, and run like a champ under CPython 3.5+ and PyPy 3.5+ (3.6+ required for ASGI).
Quick Links
What People are Saying
“We have been using Falcon as a replacement for [framework] and we simply love the performance (three times faster) and code base size (easily half of our original [framework] code).”
“Falcon looks great so far. I hacked together a quick test for a tiny server of mine and was
40% faster with only 20 minutes of work.”
“Falcon is rock solid and it’s fast.”
“I’m loving #falconframework! Super clean and simple, I finally have the speed and flexibility I need!”
“I feel like I’m just talking HTTP at last, with nothing in the middle. Falcon seems like the requests of backend.”
“The source code for Falcon is so good, I almost prefer it to documentation. It basically can’t be wrong.”
Features
Falcon tries to do as little as possible while remaining highly effective.
Support Falcon Development
Has Falcon helped you make an awesome app? Show your support today with a one-time donation or by becoming a patron. Supporters get cool gear, an opportunity to promote their brand to Python developers, and prioritized support.
How is Falcon Different?
Perfection is finally attained not when there is no longer anything to add, but when there is no longer anything to take away.
We designed Falcon to support the demanding needs of large-scale microservices and responsive app backends. Falcon complements more general Python web frameworks by providing bare-metal performance, reliability, and flexibility wherever you need it.
Reliable. We go to great lengths to avoid introducing breaking changes, and when we do they are fully documented and only introduced (in the spirit of SemVer) with a major version increment. The code is rigorously tested with numerous inputs and we require 100% coverage at all times. Falcon has no dependencies outside the standard library, helping minimize your app’s attack surface while avoiding transitive bugs and breaking changes.
Debuggable. Falcon eschews magic. It’s easy to tell which inputs lead to which outputs. Unhandled exceptions are never encapsulated or masked. Potentially surprising behaviors, such as automatic request body parsing, are well-documented and disabled by default. Finally, when it comes to the framework itself, we take care to keep logic paths simple and understandable. All this makes it easier to reason about the code and to debug edge cases in large-scale deployments.
Fast. Same hardware, more requests. Falcon turns around requests significantly faster than other popular Python frameworks like Django and Flask. For an extra speed boost, Falcon compiles itself with Cython when available, and also works well with PyPy. Considering a move to another programming language? Benchmark with Falcon+PyPy first!
Flexible. Falcon leaves a lot of decisions and implementation details to you, the API developer. This gives you a lot of freedom to customize and tune your implementation. It also helps you understand your apps at a deeper level, making them easier to tune, debug, and refactor over the long run. Falcon’s minimalist design provides space for Python community members to independently innovate on Falcon add-ons and complementary packages.
Who’s Using Falcon?
Falcon is used around the world by a growing number of organizations, including:
If you are using the Falcon framework for a community or commercial project, please consider adding your information to our wiki under Who’s Using Falcon?
Community
A number of Falcon add-ons, templates, and complementary packages are available for use in your projects. We’ve listed several of these on the Falcon wiki as a starting point, but you may also wish to search PyPI for additional resources.
The Falconry community on Gitter is a great place to ask questions and share your ideas. You can find us in falconry/user. We also have a falconry/dev room for discussing the design and development of the framework itself.
Per our Code of Conduct, we expect everyone who participates in community discussions to act professionally, and lead by example in encouraging constructive discussions. Each individual in the community is responsible for creating a positive, constructive, and productive culture.
Installation
PyPy is the fastest way to run your Falcon app. PyPy3.5+ is supported as of PyPy v5.10.
Or, to install the latest beta or release candidate, if any:
CPython
Falcon also fully supports CPython 3.5+.
The latest stable version of Falcon can be installed directly from PyPI:
Or, to install the latest beta or release candidate, if any:
In order to provide an extra speed boost, Falcon can compile itself with Cython. Wheels containing pre-compiled binaries are available from PyPI for several common platforms. However, if a wheel for your platform of choice is not available, you can choose to stick with the source distribution, or use the instructions below to cythonize Falcon for your environment.
The following commands tell pip to install Cython, and then to invoke Falcon’s setup.py, which will in turn detect the presence of Cython and then compile (AKA cythonize) the Falcon framework with the system’s default C compiler.
Note that --no-build-isolation is necessary to override pip’s default PEP 517 behavior that can cause Cython not to be found in the build environment.
Installing on OS X
Xcode Command Line Tools are required to compile Cython. Install them with this command:
The Clang compiler treats unrecognized command-line options as errors, for example:
You might also see warnings about unused functions. You can work around these issues by setting additional Clang C compiler flags as follows:
Dependencies
Falcon does not require the installation of any other packages, although if Cython has been installed into the environment, it will be used to optimize the framework as explained above.
WSGI Server
Falcon speaks WSGI (or ASGI; see also below). In order to serve a Falcon app, you will need a WSGI server. Gunicorn and uWSGI are some of the more popular ones out there, but anything that can load a WSGI app will do.
ASGI Server
In order to serve a Falcon ASGI app, you will need an ASGI server. Uvicorn is a popular choice:
Source Code
Falcon lives on GitHub, making the code easy to browse, download, fork, etc. Pull requests are always welcome! Also, please remember to star the project if it makes you happy. 🙂
Once you have cloned the repo or downloaded a tarball from GitHub, you can install Falcon like this:
Or, if you want to edit the code, first fork the main repo, clone the fork to your desktop, and then run the following to install it using symbolic linking, so that when you change your code, the changes will be automagically available to your app without having to reinstall the package:
You can manually test changes to the Falcon framework by switching to the directory of the cloned repo and then running pytest:
Or, to run the default set of tests:
See also the tox.ini file for a full list of available environments.
Read the Docs
The docstrings in the Falcon code base are quite extensive, and we recommend keeping a REPL running while learning the framework so that you can query the various modules and classes as you have questions.
You can build the same docs locally as follows:
Once the docs have been built, you can view them by opening the following index page in your browser. On OS X it’s as simple as:
Getting Started
Here is a simple, contrived example showing how to create a Falcon-based WSGI app (the ASGI version is included further down):
You can run the above example directly using the included wsgiref server:
Then, in another terminal:
The ASGI version of the example is similar:
You can run the ASGI version with uvicorn or any other ASGI server:
A More Complex Example (WSGI)
Here is a more involved example that demonstrates reading headers and query parameters, handling errors, and working with request and response bodies. Note that this example assumes that the requests package has been installed.
Again this code uses wsgiref, but you can also run the above example using any WSGI server, such as uWSGI or Gunicorn. For example:
On Windows you can run Gunicorn and uWSGI via WSL, or you might try Waitress:
To test this example, open another terminal and run:
You can also view the the application configuration from the CLI via the falcon-inspect-app script that is bundled with the framework:
A More Complex Example (ASGI)
Here’s the ASGI version of the app from above. Note that it uses the httpx package in lieu of requests.
You can run the ASGI version with any ASGI server, such as uvicorn:
Contributing
Thanks for your interest in the project! We welcome pull requests from developers of all skill levels. To get started, simply fork the master branch on GitHub to your personal account and then clone the fork into your development environment.
If you would like to contribute but don’t already have something in mind, we invite you to take a look at the issues listed under our next milestone. If you see one you’d like to work on, please leave a quick comment so that we don’t end up with duplicated effort. Thanks in advance!
Please note that all contributors and maintainers of this project are subject to our Code of Conduct.
Before submitting a pull request, please ensure you have added/updated the appropriate tests (and that all existing tests still pass with your changes), and that your coding style follows PEP 8 and doesn’t cause pyflakes to complain.
Commit messages should be formatted using AngularJS conventions.
Comments follow Google’s style guide, with the additional requirement of prefixing inline comments using your GitHub nick and an appropriate prefix:
The core Falcon project maintainers are:
Please don’t hesitate to reach out if you have any questions, or just need a little help getting started. You can find us in falconry/dev on Gitter.
Legal
Copyright 2013-2020 by Individual and corporate contributors as noted in the individual source files.
Falcon image courtesy of John O’Neill.
Licensed under the Apache License, Version 2.0 (the “License”); you may not use any portion of the Falcon framework except in compliance with the License. Contributors agree to license their work under the same License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Project details
Project links
Statistics
View statistics for this project via Libraries.io, or by using our public dataset on Google BigQuery
License: Apache Software License (Apache 2.0)
Tags wsgi, web, api, framework, rest, http, cloud
Requires: Python >=3.5
Maintainers
Classifiers
Download files
Download the file for your platform. If you’re not sure which to choose, learn more about installing packages.