Aeros Python Documentation¶
Aeros is a production-grade ASGI (Asynchronous Server Gateway Interface) package containing wrappers for widely used Web and API functions.
Have a look at the Getting Started section!
Contributors wanted
Please keep in mind that this package including all source code and documentation is developed and maintained by a single person. I am investing a large amount of time into maintaining projects like this in order to supply the most intuitive, yet powerful and high-level API as possible.
Any collaborative contributions, especially improvements and fixes are appreciated and should be inquired via an issue at the GitHub Repository.
Aeros Repository Links¶
About Aeros¶
Aeros is a production-grade ASGI (Asynchronous Server Gateway Interface) package containing wrappers for widely used Web and API functions. It combines all the benefits from Quart and Hypercorn, while maintaining the in-Python API, making it easy to create an application that can be run from custom code, not by shell. Additionally, Aeros adds powerful wrappers, that make complex features easy to code and implement.
In the end, it is meant to provide an API for web applications that is as intuitive as possible.
Features¶
High-performance web server
Async request handling
Supports multi-threading
Production-grade ASGI (async WSGI)
Can be run in a separate thread
Easy Framework based on Flask/Quart
Native HTTP features
Native server-side caching
Native gzip compression
Custom global headers (like CORS etc.)
EasyRequest handler (improvement of Flask.request)
Full In-Python code API
Aeros over Flask and Quart?¶
While Flask is one of the most popular and frequently used frameworks, it doesn’t come with a full WSGI server. Therefore, you will need an additional module like Waitress or Gunicorn. Quart shares the same features as Flask, but you can get more performance out of it, since it supports asynchronous request handling. But as for Flask, you will need a WSGI (an ASGI in this case) to deploy your Quart app into production. The most popular ASGI at the moment is called Hypercorn and is installed together with Quart.
But Hypercorn does only support deployment from console. Meaning, you will have to invoke
a start command like: hypercorn <file>:<app_variable_name>
to start your server. This
makes it hard to deploy a multi-thread web server and requires a ton of efford to debug
and control and monitor the web server instance of your application.
Logging¶
By default, all output will be written to stdout, except tracebacks, which will be written to stderr.
You can adjust the logging behaviour by using keywords on Webserver.run() as described in the following example code snippet:
from Aeros import WebServer app = WebServer(__name__) @app.route("/") async def just_say_hello(): return "Hi, I am your new backend :)" app.run( log_level=DEBUG, # set your desired logging level access_log_to_std=True, # Set False if you don't want the access log in stdout access_log_file='access.log', # Specify if you want to log access to a file traceback=True # Set False if you do not want tracebacks written to stderr )Available since version 2.0.0
The behaviour described above is available for versions >= 2.0.0.
Getting Started¶
Know what to ask
Aeros uses methods from the quart module, which itself copies the syntax of flask.
You may treat an Aeros.WebServer
instance just like a quart.Quart
instance.
Most of the Flask documentation also applies to Quart and therefore to Aeros. Use it!
Prerequisites¶
install the Aeros module to your Python interpreter of choice:
pip install -U Aeros
open up your favourite IDE and create a new project
The bare minimum¶
The following code block sets-up a very basic web server that can be accessed via HTTP for example by your browser:
from Aeros import WebServer app = WebServer(__name__) @app.route("/") async def just_say_hello(): return "Hi, I am your new backend :)" app.run()
You should now be able to access localhost in your browser and get a response.
Adding endpoints¶
If you wish to host multiple “pages”, you can just add another function and decorate it with the
@app.route()
decorator:
from Aeros import WebServer
app = WebServer(__name__)
@app.route("/")
async def just_say_hello():
return "Hi, I am your new backend :)"
@app.route("/goodbye")
async def say_bye():
return "Good bye, friend :("
app.run()
Implementing logic¶
When implementing logic to answer your requests, you need to pay close attention as to what you
are executing. Since Aeros runs asynchronous, one needs to await certain operations. This is the
case for asynchronous operations like render_template()
which renders an HTML page. But since
Aeros has to look up the contents from your hard disk first, we have to wait 1 or 2 milliseconds
before it can send the answer. That’s why we write await
in front of it.
from Aeros import WebServer
from quart import render_template
app = WebServer(__name__)
@app.route("/")
async def homepage():
return await render_template('index.html')
app.run()
Warning
Make sure to always import methods from the quart
module, not flask
, since Flask runs synchronous
and therefore does not work with an asynchronous web server. Fore more information, see
What’s async programming
API Reference¶
This page contains auto-generated API reference documentation 1.
Aeros
¶
Subpackages¶
Aeros.caching
¶
This module contains features for server-side and client-side caching.
Aeros.caching.client
¶This module contains features for client-side caching using the Cache-Control header.
An enum to replace the cache option strings with variables for auto-complete in most IDEs. |
|
This class manipulates the Cache-Control header in all responses sent from an endpoint |
-
class
Aeros.caching.client.
CacheTypes
¶ Bases:
enum.Enum
An enum to replace the cache option strings with variables for auto-complete in most IDEs.
-
NO_CACHE
= no-cache¶
-
NO_STORE
= no-store¶
-
PUBLIC
= public¶
-
PRIVATE
= private¶
-
-
class
Aeros.caching.client.
CacheControl
(cache_type: Aeros.caching.client.CacheTypes, max_age: int = None, immutable: bool = False, no_transform: bool = False, stale_while_revalidate: int = None, stale_if_error: bool = False, cache_on_status: list = [200])¶ This class manipulates the Cache-Control header in all responses sent from an endpoint decorated with this class.
Hint
If you need conditional caching rules you may still use response from quart to manipulate the Cache-Control header to your needs.
-
__call__
(self, f: callable) → callable¶
-
Aeros.caching.server
¶This module contains features for server-side caching by wrapping the flask_caching module.
The most basic cache that requires no set-up and no arguments. |
|
Stores cached responses on the file system, |
|
An alias for FileSystemCache |
|
A Redis client to store responses on an external Redis server. |
-
class
Aeros.caching.server.
SimpleCache
(app: Optional[Flask] = None, with_jinja2_ext: bool = True, config=None)¶ Bases:
flask_caching.Cache
The most basic cache that requires no set-up and no arguments.
-
class
Aeros.caching.server.
FileSystemCache
(app: Optional[Flask] = None, with_jinja2_ext: bool = True, config=None)¶ Bases:
flask_caching.Cache
Stores cached responses on the file system, good for huge caches that don’t fit into memory.
-
class
Aeros.caching.server.
FilesystemCache
¶ An alias for FileSystemCache
Warning
This class is deprecated! Use FileSystemCache instead.
-
class
Aeros.caching.server.
RedisCache
(app: Optional[Flask] = None, with_jinja2_ext: bool = True, config=None)¶ Bases:
flask_caching.Cache
A Redis client to store responses on an external Redis server.
The most basic cache that requires no set-up and no arguments. |
|
Stores cached responses on the file system, |
|
An alias for FileSystemCache |
|
A Redis client to store responses on an external Redis server. |
|
This class manipulates the Cache-Control header in all responses sent from an endpoint |
|
An enum to replace the cache option strings with variables for auto-complete in most IDEs. |
-
class
Aeros.caching.
SimpleCache
(app: Optional[Flask] = None, with_jinja2_ext: bool = True, config=None)[source]¶ Bases:
flask_caching.Cache
The most basic cache that requires no set-up and no arguments.
-
class
Aeros.caching.
FileSystemCache
(app: Optional[Flask] = None, with_jinja2_ext: bool = True, config=None)¶ Bases:
flask_caching.Cache
Stores cached responses on the file system, good for huge caches that don’t fit into memory.
-
class
Aeros.caching.
FilesystemCache
[source]¶ An alias for FileSystemCache
Warning
This class is deprecated! Use FileSystemCache instead.
-
class
Aeros.caching.
RedisCache
(app: Optional[Flask] = None, with_jinja2_ext: bool = True, config=None)[source]¶ Bases:
flask_caching.Cache
A Redis client to store responses on an external Redis server.
-
class
Aeros.caching.
CacheControl
(cache_type: Aeros.caching.client.CacheTypes, max_age: int = None, immutable: bool = False, no_transform: bool = False, stale_while_revalidate: int = None, stale_if_error: bool = False, cache_on_status: list = [200])¶ This class manipulates the Cache-Control header in all responses sent from an endpoint decorated with this class.
Hint
If you need conditional caching rules you may still use response from quart to manipulate the Cache-Control header to your needs.
-
__call__
(self, f: callable) → callable¶
-
Submodules¶
Aeros.Request
¶
This module contains the wrapper for Quart.request that can be used inside web methods
A helper class that makes request handling more uniform. |
-
class
Aeros.Request.
EasyRequest
[source]¶ A helper class that makes request handling more uniform.
All attributes are assessable via the same syntax, while with Flask.request or quart.request, you will have slightly different syntax when retrieving different request attributes, which can be very irritating and take much time debugging your code for missing parentheses or an await statement.
Hint
You only need to await attributes that need calculation, for example evaluating the request body, like .json or .form.
headers = EasyRequest.headers params = EasyRequest.params form = await EasyRequest.form # requires time for calculation json = await EasyRequest.json # requires time for calculation
-
params
:dict¶ The URL parameters like Flask.request.params.
-
headers
:dict¶ The request headers like quart.request.headers.
The request cookies like quart.request.cookies.
-
__quart_request
:request¶ The quart.request. instance that is used in the current scope.
-
__load
(self)¶ Loads the content of quart.request into this instance and returns it.
-
__call__
(self, f)[source]¶ Decorates an endpoint function to use the EasyRequest with, which makes EasyRequest available in that endpoint method.
-
async property
form
(self)¶ The request form data like quart.request.form.
-
async property
json
(self)¶ The request body data (as JSON) like quart.request.form.
Be aware that in order for quart.request.get_json() to return a JSON dictionary, the Content-Type header must be set to application/json.
-
-
Aeros.Request.
app
¶
Aeros.WebServer
¶
This module contains the main web server class
This is the main server class which extends a standard Flask class by a bunch of features and major |
-
class
Aeros.WebServer.
WebServer
(import_name: str, host: str = '0.0.0.0', port: int = 80, include_server_header: bool = True, logging_level: int = INFO, cache: Aeros.caching.server.Cache = None, compression: Aeros.compression.Base = None, global_headers: dict = {}, *args, **kwargs)[source]¶ Bases:
quart.Quart
This is the main server class which extends a standard Flask class by a bunch of features and major performance improvements. It extends the quart class, which by itself is already an enhanced version of the Flask class. This class however allows production-grade deployment using the uvicorn ASGI server as production server. But instead of calling the uvicorn command via the console, it can be started directly from the Python code itself, making it easier to integrate in higher-level scripts and applications without calling os.system() or subprocess.Popen().
-
__log_format_std
= [%(asctime)s] %(levelname)s: %(message)s¶
-
cache
(self, timeout=None, key_prefix='view/%s', unless=None, forced_update=None, response_filter=None, query_string=False, hash_method=hashlib.md5, cache_none=False)[source]¶ A simple wrapper that forwards the cached() decorator to the internal Cache() instance. May be used as the normal @cache.cached() decorator.
-
clear_cache
(self)¶ Clears the WebServer instance cache. Use with caution!
-
_get_own_instance_path
(self) → str[source]¶ Retrieves the file and variable name of this instance to be used in the uvicorn CLI.
Since uvicorn needs the application’s file and global variable name for multicore execution, an instance needs to know it’s own origin file and name. But since this class is not defined in the same file as it is called or defined from, this method searches for the correct module/file and evaluates it’s instance name.
Warning
This method is a beta feature. Use with caution (good testing).
-
run_server
(self, host: str = None, port: int = None, log_level: int = None, access_log_file: str = None, access_log_to_std: bool = True, traceback: bool = True, soft_limit: int = 32, hard_limit: int = 42, **kwargs) → None[source]¶ Generates the necessary config and runs the server instance. Possible keyword arguments are the same as supported by the uvicorn.run() method as they are passed into Config(app, **kwargs). This method also configures features like caching and compression that are not default in Quart or Flask and unique to Aeros or require third-party modules to be configured.
-
run
(self, *args, **kwargs)¶ Run this application.
This is best used for development only, see Hypercorn for production servers.
- Parameters
host – Hostname to listen on. By default this is loopback only, use 0.0.0.0 to have the server listen externally.
port – Port number to listen on.
debug – If set enable (or disable) debug mode and debug output.
use_reloader – Automatically reload on code changes.
loop – Asyncio loop to create the server in, if None, take default one. If specified it is the caller’s responsibility to close and cleanup the loop.
ca_certs – Path to the SSL CA certificate file.
certfile – Path to the SSL certificate file.
keyfile – Path to the SSL key file.
-
route
(self, *args, **kwargs)¶ Add a route to the application.
This is designed to be used as a decorator, if used to decorate a synchronous function, the function will be wrapped in
run_sync()
and run in a thread executor (with the wrapped function returned). An example usage,@app.route('/') async def route(): ...
- Parameters
rule – The path to route on, should start with a
/
.methods – List of HTTP verbs the function routes.
endpoint – Optional endpoint name, if not present the function name is used.
defaults –
A dictionary of variables to provide automatically, use to provide a simpler default path for a route, e.g. to allow for
/book
rather than/book/0
,@app.route('/book', defaults={'page': 0}) @app.route('/book/<int:page>') def book(page): ...
host – The full host name for this route (should include subdomain if needed) - cannot be used with subdomain.
subdomain – A subdomain for this specific route.
provide_automatic_options – Optionally False to prevent OPTION handling.
strict_slashes – Strictly match the trailing slash present in the path. Will redirect a leaf (no slash) to a branch (with slash).
-
Aeros.compression
¶
The compression module includes classes for compression algorithms implemented by quart_compress. These are compatible with the async coroutine framework that Aeros uses and will compress the web server’s responses before sending it to the client.
The base class that implements the wrapper for quart_compress.Compress. |
|
This class should be used to implement a Gzip compression to your Aeros web server. |
|
This class should be used to implement a Br compression to your Aeros web server. |
|
The former class that represented compression for Aeros. Falls back to Gzip. |
-
class
Aeros.compression.
Base
(level: int = 2, min_size: int = 500, mimetypes: List = None)¶ The base class that implements the wrapper for quart_compress.Compress.
-
algorithm
= gzip¶
-
init_app
(self, app: quart.Quart)¶ Initializes the Compress instance with the give WebServer/Quart application instance
- Parameters
app (Quart) – The web server instance to use the caching functionality with
-
-
class
Aeros.compression.
Gzip
(level: int = 2, min_size: int = 500, mimetypes: List = None)¶ Bases:
Aeros.compression.Base
This class should be used to implement a Gzip compression to your Aeros web server.
-
algorithm
= gzip¶
-
-
class
Aeros.compression.
Br
(level: int = 2, min_size: int = 500, mimetypes: List = None)¶ Bases:
Aeros.compression.Base
This class should be used to implement a Br compression to your Aeros web server.
-
algorithm
= br¶
-
Aeros.misc
¶
The misc module contains useful helper functions and decorators to simplify development and make the resulting code much more readable and clean.
Aeros.thread
¶
This module contains threading helper classes and functions used to coordinate applications with multi-thread support.
This thread class extends the pure-python “Thread” class |
-
class
Aeros.thread.
AdvancedThread
(*args, **kwargs)¶ Bases:
threading.Thread
This thread class extends the pure-python “Thread” class by a stop() function to terminate the thread’s run() method.
Warning
The stop feature is still experimental and needs extensive testing.
-
__get_id
(self)¶ Get’s the threads PID.
-
stop
(self)¶ Sends a kill signal to the given thread
-
Package Contents¶
Classes¶
This is the main server class which extends a standard Flask class by a bunch of features and major |
|
A helper class that makes request handling more uniform. |
|
This thread class extends the pure-python “Thread” class |
|
This class should be used to implement a Gzip compression to your Aeros web server. |
|
This class should be used to implement a Br compression to your Aeros web server. |
|
The most basic cache that requires no set-up and no arguments. |
|
Stores cached responses on the file system, |
|
An alias for FileSystemCache |
|
A Redis client to store responses on an external Redis server. |
|
This class manipulates the Cache-Control header in all responses sent from an endpoint |
|
An enum to replace the cache option strings with variables for auto-complete in most IDEs. |
-
class
Aeros.
WebServer
(import_name: str, host: str = '0.0.0.0', port: int = 80, include_server_header: bool = True, logging_level: int = INFO, cache: Aeros.caching.server.Cache = None, compression: Aeros.compression.Base = None, global_headers: dict = {}, *args, **kwargs)[source]¶ Bases:
quart.Quart
This is the main server class which extends a standard Flask class by a bunch of features and major performance improvements. It extends the quart class, which by itself is already an enhanced version of the Flask class. This class however allows production-grade deployment using the uvicorn ASGI server as production server. But instead of calling the uvicorn command via the console, it can be started directly from the Python code itself, making it easier to integrate in higher-level scripts and applications without calling os.system() or subprocess.Popen().
-
__log_format_std
= [%(asctime)s] %(levelname)s: %(message)s¶
-
cache
(self, timeout=None, key_prefix='view/%s', unless=None, forced_update=None, response_filter=None, query_string=False, hash_method=hashlib.md5, cache_none=False)[source]¶ A simple wrapper that forwards the cached() decorator to the internal Cache() instance. May be used as the normal @cache.cached() decorator.
-
clear_cache
(self)¶ Clears the WebServer instance cache. Use with caution!
-
_get_own_instance_path
(self) → str[source]¶ Retrieves the file and variable name of this instance to be used in the uvicorn CLI.
Since uvicorn needs the application’s file and global variable name for multicore execution, an instance needs to know it’s own origin file and name. But since this class is not defined in the same file as it is called or defined from, this method searches for the correct module/file and evaluates it’s instance name.
Warning
This method is a beta feature. Use with caution (good testing).
-
run_server
(self, host: str = None, port: int = None, log_level: int = None, access_log_file: str = None, access_log_to_std: bool = True, traceback: bool = True, soft_limit: int = 32, hard_limit: int = 42, **kwargs) → None[source]¶ Generates the necessary config and runs the server instance. Possible keyword arguments are the same as supported by the uvicorn.run() method as they are passed into Config(app, **kwargs). This method also configures features like caching and compression that are not default in Quart or Flask and unique to Aeros or require third-party modules to be configured.
-
run
(self, *args, **kwargs)¶ Run this application.
This is best used for development only, see Hypercorn for production servers.
- Parameters
host – Hostname to listen on. By default this is loopback only, use 0.0.0.0 to have the server listen externally.
port – Port number to listen on.
debug – If set enable (or disable) debug mode and debug output.
use_reloader – Automatically reload on code changes.
loop – Asyncio loop to create the server in, if None, take default one. If specified it is the caller’s responsibility to close and cleanup the loop.
ca_certs – Path to the SSL CA certificate file.
certfile – Path to the SSL certificate file.
keyfile – Path to the SSL key file.
-
route
(self, *args, **kwargs)¶ Add a route to the application.
This is designed to be used as a decorator, if used to decorate a synchronous function, the function will be wrapped in
run_sync()
and run in a thread executor (with the wrapped function returned). An example usage,@app.route('/') async def route(): ...
- Parameters
rule – The path to route on, should start with a
/
.methods – List of HTTP verbs the function routes.
endpoint – Optional endpoint name, if not present the function name is used.
defaults –
A dictionary of variables to provide automatically, use to provide a simpler default path for a route, e.g. to allow for
/book
rather than/book/0
,@app.route('/book', defaults={'page': 0}) @app.route('/book/<int:page>') def book(page): ...
host – The full host name for this route (should include subdomain if needed) - cannot be used with subdomain.
subdomain – A subdomain for this specific route.
provide_automatic_options – Optionally False to prevent OPTION handling.
strict_slashes – Strictly match the trailing slash present in the path. Will redirect a leaf (no slash) to a branch (with slash).
-
-
class
Aeros.
EasyRequest
[source]¶ A helper class that makes request handling more uniform.
All attributes are assessable via the same syntax, while with Flask.request or quart.request, you will have slightly different syntax when retrieving different request attributes, which can be very irritating and take much time debugging your code for missing parentheses or an await statement.
Hint
You only need to await attributes that need calculation, for example evaluating the request body, like .json or .form.
headers = EasyRequest.headers params = EasyRequest.params form = await EasyRequest.form # requires time for calculation json = await EasyRequest.json # requires time for calculation
-
params
:dict¶ The URL parameters like Flask.request.params.
-
headers
:dict¶ The request headers like quart.request.headers.
The request cookies like quart.request.cookies.
-
__quart_request
:request¶ The quart.request. instance that is used in the current scope.
-
__load
(self)¶ Loads the content of quart.request into this instance and returns it.
-
__call__
(self, f)[source]¶ Decorates an endpoint function to use the EasyRequest with, which makes EasyRequest available in that endpoint method.
-
async property
form
(self)¶ The request form data like quart.request.form.
-
async property
json
(self)¶ The request body data (as JSON) like quart.request.form.
Be aware that in order for quart.request.get_json() to return a JSON dictionary, the Content-Type header must be set to application/json.
-
-
class
Aeros.
AdvancedThread
(*args, **kwargs)[source]¶ Bases:
threading.Thread
This thread class extends the pure-python “Thread” class by a stop() function to terminate the thread’s run() method.
Warning
The stop feature is still experimental and needs extensive testing.
-
__get_id
(self)¶ Get’s the threads PID.
-
-
class
Aeros.
Gzip
(level: int = 2, min_size: int = 500, mimetypes: List = None)¶ Bases:
Aeros.compression.Base
This class should be used to implement a Gzip compression to your Aeros web server.
-
algorithm
= gzip¶
-
-
class
Aeros.
Br
(level: int = 2, min_size: int = 500, mimetypes: List = None)¶ Bases:
Aeros.compression.Base
This class should be used to implement a Br compression to your Aeros web server.
-
algorithm
= br¶
-
-
class
Aeros.
SimpleCache
(app: Optional[Flask] = None, with_jinja2_ext: bool = True, config=None)[source]¶ Bases:
flask_caching.Cache
The most basic cache that requires no set-up and no arguments.
-
class
Aeros.
FileSystemCache
(app: Optional[Flask] = None, with_jinja2_ext: bool = True, config=None)¶ Bases:
flask_caching.Cache
Stores cached responses on the file system, good for huge caches that don’t fit into memory.
-
class
Aeros.
FilesystemCache
[source]¶ An alias for FileSystemCache
Warning
This class is deprecated! Use FileSystemCache instead.
-
class
Aeros.
RedisCache
(app: Optional[Flask] = None, with_jinja2_ext: bool = True, config=None)[source]¶ Bases:
flask_caching.Cache
A Redis client to store responses on an external Redis server.
-
class
Aeros.
CacheControl
(cache_type: Aeros.caching.client.CacheTypes, max_age: int = None, immutable: bool = False, no_transform: bool = False, stale_while_revalidate: int = None, stale_if_error: bool = False, cache_on_status: list = [200])¶ This class manipulates the Cache-Control header in all responses sent from an endpoint decorated with this class.
Hint
If you need conditional caching rules you may still use response from quart to manipulate the Cache-Control header to your needs.
-
__call__
(self, f: callable) → callable¶
-
- 1
Created with sphinx-autoapi