Aeros Python Documentation¶
Aeros is a production-grade ASGI (Asynchronous Server Gateway Interface) package containing wrappers for widely used Web and API functions.
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 this project in order to supply the most intuitive, yet powerful high-level API possible.
Any collaborative contributions, especially improvements and fixes are appreciated and should be inquired via an issue at the GitLab Repository.
Aeros Repository Links¶
npm Package (comming soon)
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.
API Reference¶
This page contains auto-generated API reference documentation 1.
Aeros
¶
Subpackages¶
Aeros.patches
¶
Aeros.patches.flask_caching
¶Aeros.patches.flask_caching.Cache
¶This class is used to control the cache objects. |
-
class
Aeros.patches.flask_caching.Cache.
Cache
(timeout: int = 60 * 60, threshold: int = 100, *args, **kwargs)[source]¶ Bases:
flask_caching.Cache
This class is used to control the cache objects.
-
cached
(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]¶ Decorator. Use this to cache a function. By default the cache key is view/request.path. You are able to use this decorator with any function by changing the key_prefix. If the token %s is located within the key_prefix then it will replace that with request.path
Example:
# An example view function @cache.cached(timeout=50) def big_foo(): return big_bar_calc() # An example misc function to cache. @cache.cached(key_prefix='MyCachedList') def get_list(): return [random.randrange(0, 1) for i in range(50000)] my_list = get_list()
Note
You MUST have a request context to actually called any functions that are cached.
New in version 0.4: The returned decorated function now has three function attributes assigned to it. These attributes are readable/writable.
- uncached
The original undecorated function
- cache_timeout
The cache timeout value for this function. For a custom value to take affect, this must be set before the function is called.
- make_cache_key
A function used in generating the cache_key used.
- Parameters
timeout – Default None. If set to an integer, will cache for that amount of time. Unit of time is in seconds.
key_prefix –
Default ‘view/%(request.path)s’. Beginning key to . use for the cache key. request.path will be the actual request path, or in cases where the make_cache_key-function is called from other views it will be the expected URL for the view as generated by Flask’s url_for().
New in version 0.3.4: Can optionally be a callable which takes no arguments but returns a string that will be used as the cache_key.
unless – Default None. Cache will always execute the caching facilities unless this callable is true. This will bypass the caching entirely.
forced_update – Default None. If this callable is true, cache value will be updated regardless cache is expired or not. Useful for background renewal of cached functions.
response_filter – Default None. If not None, the callable is invoked after the cached funtion evaluation, and is given one arguement, the response content. If the callable returns False, the content will not be cached. Useful to prevent caching of code 500 responses.
query_string – Default False. When True, the cache key used will be the result of hashing the ordered query string parameters. This avoids creating different caches for the same query just because the parameters were passed in a different order. See _make_cache_key_query_string() for more details.
hash_method – Default hashlib.md5. The hash method used to generate the keys for cached results.
cache_none – Default False. If set to True, add a key exists check when cache.get returns None. This will likely lead to wrongly returned None values in concurrent situations and is not recommended to use.
-
-
class
Aeros.patches.flask_caching.
Cache
(timeout: int = 60 * 60, threshold: int = 100, *args, **kwargs)[source]¶ Bases:
flask_caching.Cache
This class is used to control the cache objects.
-
cached
(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]¶ Decorator. Use this to cache a function. By default the cache key is view/request.path. You are able to use this decorator with any function by changing the key_prefix. If the token %s is located within the key_prefix then it will replace that with request.path
Example:
# An example view function @cache.cached(timeout=50) def big_foo(): return big_bar_calc() # An example misc function to cache. @cache.cached(key_prefix='MyCachedList') def get_list(): return [random.randrange(0, 1) for i in range(50000)] my_list = get_list()
Note
You MUST have a request context to actually called any functions that are cached.
New in version 0.4: The returned decorated function now has three function attributes assigned to it. These attributes are readable/writable.
- uncached
The original undecorated function
- cache_timeout
The cache timeout value for this function. For a custom value to take affect, this must be set before the function is called.
- make_cache_key
A function used in generating the cache_key used.
- Parameters
timeout – Default None. If set to an integer, will cache for that amount of time. Unit of time is in seconds.
key_prefix –
Default ‘view/%(request.path)s’. Beginning key to . use for the cache key. request.path will be the actual request path, or in cases where the make_cache_key-function is called from other views it will be the expected URL for the view as generated by Flask’s url_for().
New in version 0.3.4: Can optionally be a callable which takes no arguments but returns a string that will be used as the cache_key.
unless – Default None. Cache will always execute the caching facilities unless this callable is true. This will bypass the caching entirely.
forced_update – Default None. If this callable is true, cache value will be updated regardless cache is expired or not. Useful for background renewal of cached functions.
response_filter – Default None. If not None, the callable is invoked after the cached funtion evaluation, and is given one arguement, the response content. If the callable returns False, the content will not be cached. Useful to prevent caching of code 500 responses.
query_string – Default False. When True, the cache key used will be the result of hashing the ordered query string parameters. This avoids creating different caches for the same query just because the parameters were passed in a different order. See _make_cache_key_query_string() for more details.
hash_method – Default hashlib.md5. The hash method used to generate the keys for cached results.
cache_none – Default False. If set to True, add a key exists check when cache.get returns None. This will likely lead to wrongly returned None values in concurrent situations and is not recommended to use.
-
Aeros.patches.hypercorn
¶Aeros.patches.hypercorn.Config
¶Aeros.patches.hypercorn.worker
¶
|
|
|
Aeros.patches.quart
¶Aeros.patches.quart.app
¶The web framework class, handles requests and returns responses. |
-
class
Aeros.patches.quart.app.
Quart
(import_name: str, static_url_path: Optional[str] = None, static_folder: Optional[str] = 'static', static_host: Optional[str] = None, host_matching: bool = False, subdomain_matching: bool = False, template_folder: Optional[str] = 'templates', root_path: Optional[str] = None, instance_path: Optional[str] = None, instance_relative_config: bool = False)[source]¶ Bases:
quart.Quart
The web framework class, handles requests and returns responses.
The primary method from a serving viewpoint is
handle_request()
, from an application viewpoint all the other methods are vital.This can be extended in many ways, with most methods designed with this in mind. Additionally any of the classes listed as attributes can be replaced.
-
app_ctx_globals_class
¶ The class to use for the
g
object
-
asgi_http_class
¶ The class to use to handle the ASGI HTTP protocol.
-
asgi_lifespan_class
¶ The class to use to handle the ASGI lifespan protocol.
-
asgi_websocket_class
¶ The class to use to handle the ASGI websocket protocol.
-
config_class
¶ The class to use for the configuration.
-
env
¶ The name of the environment the app is running on.
-
debug
¶ Wrapper around configuration DEBUG value, in many places this will result in more output if True. If unset, debug mode will be activated if environ is set to ‘development’.
-
jinja_environment
¶ The class to use for the jinja environment.
-
jinja_options
¶ The default options to set when creating the jinja environment.
-
json_decoder
¶ The decoder for JSON data.
-
json_encoder
¶ The encoder for JSON data.
-
permanent_session_lifetime
¶ Wrapper around configuration PERMANENT_SESSION_LIFETIME value. Specifies how long the session data should survive.
-
request_class
¶ The class to use for requests.
-
response_class
¶ The class to user for responses.
-
secret_key
¶ Warpper around configuration SECRET_KEY value. The app secret for signing sessions.
Wrapper around configuration SESSION_COOKIE_NAME, use to specify the cookie name for session data.
-
session_interface
¶ The class to use as the session interface.
-
url_map_class
¶ The class to map rules to endpoints.
-
url_rule_class
¶ The class to use for URL rules.
-
websocket_class
¶ The class to use for websockets.
-
asgi_http_class
¶
-
The web framework class, handles requests and returns responses. |
-
class
Aeros.patches.quart.
Quart
(import_name: str, static_url_path: Optional[str] = None, static_folder: Optional[str] = 'static', static_host: Optional[str] = None, host_matching: bool = False, subdomain_matching: bool = False, template_folder: Optional[str] = 'templates', root_path: Optional[str] = None, instance_path: Optional[str] = None, instance_relative_config: bool = False)[source]¶ Bases:
quart.Quart
The web framework class, handles requests and returns responses.
The primary method from a serving viewpoint is
handle_request()
, from an application viewpoint all the other methods are vital.This can be extended in many ways, with most methods designed with this in mind. Additionally any of the classes listed as attributes can be replaced.
-
app_ctx_globals_class
¶ The class to use for the
g
object
-
asgi_http_class
¶ The class to use to handle the ASGI HTTP protocol.
-
asgi_lifespan_class
¶ The class to use to handle the ASGI lifespan protocol.
-
asgi_websocket_class
¶ The class to use to handle the ASGI websocket protocol.
-
config_class
¶ The class to use for the configuration.
-
env
¶ The name of the environment the app is running on.
-
debug
¶ Wrapper around configuration DEBUG value, in many places this will result in more output if True. If unset, debug mode will be activated if environ is set to ‘development’.
-
jinja_environment
¶ The class to use for the jinja environment.
-
jinja_options
¶ The default options to set when creating the jinja environment.
-
json_decoder
¶ The decoder for JSON data.
-
json_encoder
¶ The encoder for JSON data.
-
permanent_session_lifetime
¶ Wrapper around configuration PERMANENT_SESSION_LIFETIME value. Specifies how long the session data should survive.
-
request_class
¶ The class to use for requests.
-
response_class
¶ The class to user for responses.
-
secret_key
¶ Warpper around configuration SECRET_KEY value. The app secret for signing sessions.
Wrapper around configuration SESSION_COOKIE_NAME, use to specify the cookie name for session data.
-
session_interface
¶ The class to use as the session interface.
-
url_map_class
¶ The class to map rules to endpoints.
-
url_rule_class
¶ The class to use for URL rules.
-
websocket_class
¶ The class to use for websockets.
-
asgi_http_class
¶
-
Submodules¶
Aeros.Request
¶
Top module doc string
A helper class that make request handling easier |
-
class
Aeros.Request.
EasyRequest
[source]¶ A helper class that make request handling easier
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.
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 Flask.request.headers.
-
__quart_request
:request¶ The Flask.request. instance that is used in the current scope.
-
__load
(self)¶ loads the content of Flask.request into this instance and returns it.
-
async property
form
(self)¶ The request form data like Flask.request.form.
-
async property
json
(self)¶ The request body data (as JSON) like Flask.request.form.
Be aware that in order for Flask.request.get_json() to return a JSON dictionary, the
Content-Type
header must be set toapplication/json
.
-
-
Aeros.Request.
app
¶
Aeros.WebServer
¶
Main web server instance
This is the main server class which extends a standard Flask class by a bunch of features and major |
|
Overrides a given config’s items if they are specified in the hypercorn args string |
-
Aeros.WebServer.
make_config_from_hypercorn_args
(hypercorn_string: str, config: Config = Config()) → Config[source]¶ Overrides a given config’s items if they are specified in the hypercorn args string
-
class
Aeros.WebServer.
WebServer
(import_name: str, host: str = '0.0.0.0', port: int = 80, include_server_header: bool = True, hypercorn_arg_string: str = '', worker_threads: int = 1, logging_level: Union[int, str] = 'INFO', cache: Cache = Cache(), compression: Compression = Compression(level=2, min_size=10), global_headers: Dict[str, str] = None, *args, **kwargs)[source]¶ Bases:
Aeros.patches.quart.app.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 hypercorn WSGI server as production server. But instead of calling the hypercorn 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() od subprocess.Popen().
-
_get_own_instance_path
(self)[source]¶ Retrieves the file and variable name of this instance to be used in the Hypercorn CLI.
Since hypercorn needs the application’s file and global variable name, 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
Deprecation warning: This method will be removed in future versions. Usage is highly discouraged.
-
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 cached() decorator to the internal Cache() instance. May be used as the normal @cache.cached() decorator.
-
Aeros.caching
¶
This class is used to control the cache objects. |
|
This class is used to control the cache objects. |
|
This class is used to control the cache objects. |
-
class
Aeros.caching.
SimpleCache
(*args, **kwargs)[source]¶ Bases:
Aeros.patches.flask_caching.Cache
This class is used to control the cache objects.
-
class
Aeros.caching.
FilesystemCache
(directory: str, *args, **kwargs)[source]¶ Bases:
Aeros.patches.flask_caching.Cache
This class is used to control the cache objects.
-
class
Aeros.caching.
RedisCache
(host: str, port: int, password: str = '', db: int = 0, *args, **kwargs)[source]¶ Bases:
Aeros.patches.flask_caching.Cache
This class is used to control the cache objects.
Aeros.threading
¶
This thread class extends the pure-python “Thread” class |
Package Contents¶
Classes¶
The web framework class, handles requests and returns responses. |
|
This is the main server class which extends a standard Flask class by a bunch of features and major |
|
A helper class that make request handling easier |
|
This thread class extends the pure-python “Thread” class |
|
This class is used to control the cache objects. |
|
This class is used to control the cache objects. |
|
This class is used to control the cache objects. |
Functions¶
|
Overrides a given config’s items if they are specified in the hypercorn args string |
-
class
Aeros.
Quart
(import_name: str, static_url_path: Optional[str] = None, static_folder: Optional[str] = 'static', static_host: Optional[str] = None, host_matching: bool = False, subdomain_matching: bool = False, template_folder: Optional[str] = 'templates', root_path: Optional[str] = None, instance_path: Optional[str] = None, instance_relative_config: bool = False)[source]¶ Bases:
quart.Quart
The web framework class, handles requests and returns responses.
The primary method from a serving viewpoint is
handle_request()
, from an application viewpoint all the other methods are vital.This can be extended in many ways, with most methods designed with this in mind. Additionally any of the classes listed as attributes can be replaced.
-
app_ctx_globals_class
¶ The class to use for the
g
object
-
asgi_http_class
¶ The class to use to handle the ASGI HTTP protocol.
-
asgi_lifespan_class
¶ The class to use to handle the ASGI lifespan protocol.
-
asgi_websocket_class
¶ The class to use to handle the ASGI websocket protocol.
-
config_class
¶ The class to use for the configuration.
-
env
¶ The name of the environment the app is running on.
-
debug
¶ Wrapper around configuration DEBUG value, in many places this will result in more output if True. If unset, debug mode will be activated if environ is set to ‘development’.
-
jinja_environment
¶ The class to use for the jinja environment.
-
jinja_options
¶ The default options to set when creating the jinja environment.
-
json_decoder
¶ The decoder for JSON data.
-
json_encoder
¶ The encoder for JSON data.
-
permanent_session_lifetime
¶ Wrapper around configuration PERMANENT_SESSION_LIFETIME value. Specifies how long the session data should survive.
-
request_class
¶ The class to use for requests.
-
response_class
¶ The class to user for responses.
-
secret_key
¶ Warpper around configuration SECRET_KEY value. The app secret for signing sessions.
Wrapper around configuration SESSION_COOKIE_NAME, use to specify the cookie name for session data.
-
session_interface
¶ The class to use as the session interface.
-
url_map_class
¶ The class to map rules to endpoints.
-
url_rule_class
¶ The class to use for URL rules.
-
websocket_class
¶ The class to use for websockets.
-
asgi_http_class
¶
-
-
Aeros.
make_config_from_hypercorn_args
(hypercorn_string: str, config: Config = Config()) → Config[source]¶ Overrides a given config’s items if they are specified in the hypercorn args string
-
class
Aeros.
WebServer
(import_name: str, host: str = '0.0.0.0', port: int = 80, include_server_header: bool = True, hypercorn_arg_string: str = '', worker_threads: int = 1, logging_level: Union[int, str] = 'INFO', cache: Cache = Cache(), compression: Compression = Compression(level=2, min_size=10), global_headers: Dict[str, str] = None, *args, **kwargs)[source]¶ Bases:
Aeros.patches.quart.app.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 hypercorn WSGI server as production server. But instead of calling the hypercorn 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() od subprocess.Popen().
-
_get_own_instance_path
(self)[source]¶ Retrieves the file and variable name of this instance to be used in the Hypercorn CLI.
Since hypercorn needs the application’s file and global variable name, 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
Deprecation warning: This method will be removed in future versions. Usage is highly discouraged.
-
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 cached() decorator to the internal Cache() instance. May be used as the normal @cache.cached() decorator.
-
-
class
Aeros.
EasyRequest
[source]¶ A helper class that make request handling easier
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.
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 Flask.request.headers.
-
__quart_request
:request¶ The Flask.request. instance that is used in the current scope.
-
__load
(self)¶ loads the content of Flask.request into this instance and returns it.
-
async property
form
(self)¶ The request form data like Flask.request.form.
-
async property
json
(self)¶ The request body data (as JSON) like Flask.request.form.
Be aware that in order for Flask.request.get_json() to return a JSON dictionary, the
Content-Type
header must be set toapplication/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.
-
__get_id
(self)¶ Get’s the threads PID.
-
-
class
Aeros.
SimpleCache
(*args, **kwargs)[source]¶ Bases:
Aeros.patches.flask_caching.Cache
This class is used to control the cache objects.
-
class
Aeros.
FilesystemCache
(directory: str, *args, **kwargs)[source]¶ Bases:
Aeros.patches.flask_caching.Cache
This class is used to control the cache objects.
-
class
Aeros.
RedisCache
(host: str, port: int, password: str = '', db: int = 0, *args, **kwargs)[source]¶ Bases:
Aeros.patches.flask_caching.Cache
This class is used to control the cache objects.
- 1
Created with sphinx-autoapi