INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Create a list of blueprints, optionally grouping them under a general URL prefix. :param blueprints: blueprints to be registered as a group :param url_prefix: URL route to be prepended to all sub-prefixes
def group(*blueprints, url_prefix=""): """ Create a list of blueprints, optionally grouping them under a general URL prefix. :param blueprints: blueprints to be registered as a group :param url_prefix: URL route to be prepended to all sub-prefixes """ def chain(...
Add an API URL under the **GET** *HTTP* method :param uri: URL to be tagged to **GET** method of *HTTP* :param host: Host IP or FQDN for the service to use :param strict_slashes: Instruct :class:`sanic.app.Sanic` to check if the request URLs need to terminate with a */* :par...
def get( self, uri, host=None, strict_slashes=None, version=None, name=None ): """ Add an API URL under the **GET** *HTTP* method :param uri: URL to be tagged to **GET** method of *HTTP* :param host: Host IP or FQDN for the service to use :param strict_slashes: Instr...
|coro| Retreives a :class:`Member` from a guild ID, and a member ID. .. note:: This method is an API call. For general usage, consider :meth:`get_member` instead. Parameters ----------- member_id: :class:`int` The member's ID to fetch from. Ra...
async def fetch_member(self, member_id): """|coro| Retreives a :class:`Member` from a guild ID, and a member ID. .. note:: This method is an API call. For general usage, consider :meth:`get_member` instead. Parameters ----------- member_id: :class:`int` ...
Accepts an coroutine `streaming_fn` which can be used to write chunks to a streaming response. Returns a `StreamingHTTPResponse`. Example usage:: @app.route("/") async def index(request): async def streaming_fn(response): await response.write('foo') ...
def stream( streaming_fn, status=200, headers=None, content_type="text/plain; charset=utf-8", ): """Accepts an coroutine `streaming_fn` which can be used to write chunks to a streaming response. Returns a `StreamingHTTPResponse`. Example usage:: @app.route("/") async def in...
Decorator used for adding exceptions to :class:`SanicException`.
def add_status_code(code): """ Decorator used for adding exceptions to :class:`SanicException`. """ def class_decorator(cls): cls.status_code = code _sanic_exceptions[code] = cls return cls return class_decorator
This method provides the app user a mechanism by which an already existing route can be removed from the :class:`Sanic` object :param uri: URL Path to be removed from the app :param clean_cache: Instruct sanic if it needs to clean up the LRU route cache :param host: IP addre...
def remove_route(self, uri, clean_cache=True, host=None): """ This method provides the app user a mechanism by which an already existing route can be removed from the :class:`Sanic` object :param uri: URL Path to be removed from the app :param clean_cache: Instruct sanic if it n...
|coro| Returns a list of all active instant invites from the guild. You must have the :attr:`~Permissions.manage_guild` permission to get this information. Raises ------- Forbidden You do not have proper permissions to get the information. HTTPExcep...
async def invites(self): """|coro| Returns a list of all active instant invites from the guild. You must have the :attr:`~Permissions.manage_guild` permission to get this information. Raises ------- Forbidden You do not have proper permissions to ge...
Create a blueprint websocket route from a decorated function. :param uri: endpoint at which the route will be accessible. :param host: IP Address of FQDN for the sanic server to use. :param strict_slashes: Enforce the API urls are requested with a training */* :param version...
def websocket( self, uri, host=None, strict_slashes=None, version=None, name=None ): """Create a blueprint websocket route from a decorated function. :param uri: endpoint at which the route will be accessible. :param host: IP Address of FQDN for the sanic server to use. :par...
Writes a chunk of data to the streaming response. :param data: bytes-ish data to be written.
async def write(self, data): """Writes a chunk of data to the streaming response. :param data: bytes-ish data to be written. """ if type(data) != bytes: data = self._encode_body(data) self.protocol.push_data(b"%x\r\n%b\r\n" % (len(data), data)) await self.pr...
List[Tuple[:class:`int`, :class:`float`]]: A list of latencies between a HEARTBEAT and a HEARTBEAT_ACK in seconds. This returns a list of tuples with elements ``(shard_id, latency)``.
def latencies(self): """List[Tuple[:class:`int`, :class:`float`]]: A list of latencies between a HEARTBEAT and a HEARTBEAT_ACK in seconds. This returns a list of tuples with elements ``(shard_id, latency)``. """ return [(shard_id, shard.ws.latency) for shard_id, shard in self.shards.ite...
Create a listener from a decorated function. :param event: Event to listen to.
def listener(self, event): """Create a listener from a decorated function. :param event: Event to listen to. """ def decorator(listener): self.listeners[event].append(listener) return listener return decorator
|coro| Retrieves a custom :class:`Emoji` from the guild. .. note:: This method is an API call. For general usage, consider iterating over :attr:`emojis` instead. Parameters ------------- emoji_id: :class:`int` The emoji's ID. Raise...
async def fetch_emoji(self, emoji_id): """|coro| Retrieves a custom :class:`Emoji` from the guild. .. note:: This method is an API call. For general usage, consider iterating over :attr:`emojis` instead. Parameters ------------- emoji_id: :clas...
Register an application level middleware that will be attached to all the API URLs registered under this application. This method is internally invoked by the :func:`middleware` decorator provided at the app level. :param middleware: Callback method to be attached to the mi...
def register_middleware(self, middleware, attach_to="request"): """ Register an application level middleware that will be attached to all the API URLs registered under this application. This method is internally invoked by the :func:`middleware` decorator provided at the app lev...
|coro| Similar to :meth:`prune_members` except instead of actually pruning members, it returns how many members it would prune from the guild had it been called. Parameters ----------- days: :class:`int` The number of days before counting as inactive. ...
async def estimate_pruned_members(self, *, days): """|coro| Similar to :meth:`prune_members` except instead of actually pruning members, it returns how many members it would prune from the guild had it been called. Parameters ----------- days: :class:`int` ...
Return a streaming response object with file data. :param location: Location of file on system. :param chunk_size: The size of each chunk in the stream (in bytes) :param mime_type: Specific mime_type. :param headers: Custom Headers. :param filename: Override filename. :param _range:
async def file_stream( location, status=200, chunk_size=4096, mime_type=None, headers=None, filename=None, _range=None, ): """Return a streaming response object with file data. :param location: Location of file on system. :param chunk_size: The size of each chunk in the stream (...
Take a request from the HTTP Server and return a response object to be sent back The HTTP Server only expects a response object, so exception handling must be done here :param request: HTTP Request object :param write_callback: Synchronous response function to be called with...
async def handle_request(self, request, write_callback, stream_callback): """Take a request from the HTTP Server and return a response object to be sent back The HTTP Server only expects a response object, so exception handling must be done here :param request: HTTP Request object ...
Enable or disable the support for websocket. Websocket is enabled automatically if websocket routes are added to the application.
def enable_websocket(self, enable=True): """Enable or disable the support for websocket. Websocket is enabled automatically if websocket routes are added to the application. """ if not self.websocket_enabled: # if the server is stopped, we want to cancel any ongoing ...
Streams headers, runs the `streaming_fn` callback that writes content to the response body, then finalizes the response body.
async def stream( self, version="1.1", keep_alive=False, keep_alive_timeout=None ): """Streams headers, runs the `streaming_fn` callback that writes content to the response body, then finalizes the response body. """ headers = self.get_headers( version, ...
Decorate and register middleware to be called before a request. Can either be called as *@app.middleware* or *@app.middleware('request')* :param: middleware_or_request: Optional parameter to use for identifying which type of middleware is being registered.
def middleware(self, middleware_or_request): """ Decorate and register middleware to be called before a request. Can either be called as *@app.middleware* or *@app.middleware('request')* :param: middleware_or_request: Optional parameter to use for identifying which t...
A helper method to register a function as a websocket route. :param handler: a callable function or instance of a class that can handle the websocket request :param host: Host IP or FQDN details :param uri: URL path that will be mapped to the websocket ...
def add_websocket_route( self, handler, uri, host=None, strict_slashes=None, subprotocols=None, name=None, ): """ A helper method to register a function as a websocket route. :param handler: a callable function or instance of a class ...
This method enables the process of creating a global exception handler for the current blueprint under question. :param args: List of Python exceptions to be caught by the handler :param kwargs: Additional optional arguments to be passed to the exception handler :return a d...
def exception(self, *args, **kwargs): """ This method enables the process of creating a global exception handler for the current blueprint under question. :param args: List of Python exceptions to be caught by the handler :param kwargs: Additional optional arguments to be passed...
Proxy method provided for invoking the :func:`blueprint` method .. note:: To be deprecated in 1.0. Use :func:`blueprint` instead. :param args: Blueprint object or (list, tuple) thereof :param kwargs: option dictionary with blueprint defaults :return: None
def register_blueprint(self, *args, **kwargs): """ Proxy method provided for invoking the :func:`blueprint` method .. note:: To be deprecated in 1.0. Use :func:`blueprint` instead. :param args: Blueprint object or (list, tuple) thereof :param kwargs: option dictiona...
Asynchronous version of :func:`run`. This method will take care of the operations necessary to invoke the *before_start* events via :func:`trigger_events` method invocation before starting the *sanic* app in Async mode. .. note:: This does not support multiprocessing and is...
async def create_server( self, host: Optional[str] = None, port: Optional[int] = None, debug: bool = False, ssl: Union[dict, SSLContext, None] = None, sock: Optional[socket] = None, protocol: Type[Protocol] = None, backlog: int = 100, stop_event: A...
The Abstract class `MutableSequence` leverages this insert method to perform the `BlueprintGroup.append` operation. :param index: Index to use for removing a new Blueprint item :param item: New `Blueprint` object. :return: None
def insert(self, index: int, item: object) -> None: """ The Abstract class `MutableSequence` leverages this insert method to perform the `BlueprintGroup.append` operation. :param index: Index to use for removing a new Blueprint item :param item: New `Blueprint` object. :...
Register a root to serve files from. The input can either be a file or a directory. This method will enable an easy and simple way to setup the :class:`Route` necessary to serve the static files. :param uri: URL path to be used for serving static content :param file_or_directory: Path f...
def static( self, uri, file_or_directory, pattern=r"/?.+", use_modified_since=True, use_content_range=False, stream_large_files=False, name="static", host=None, strict_slashes=None, content_type=None, ): """ Regi...
Raise an exception based on SanicException. Returns the HTTP response message appropriate for the given status code, unless provided. :param status_code: The HTTP status code to return. :param message: The HTTP response body. Defaults to the messages in response.py for the given status ...
def abort(status_code, message=None): """ Raise an exception based on SanicException. Returns the HTTP response message appropriate for the given status code, unless provided. :param status_code: The HTTP status code to return. :param message: The HTTP response body. Defaults to the messages ...
A decorator that can be used to implement a Middleware plugin to all of the Blueprints that belongs to this specific Blueprint Group. In case of nested Blueprint Groups, the same middleware is applied across each of the Blueprints recursively. :param args: Optional positional Parameter...
def middleware(self, *args, **kwargs): """ A decorator that can be used to implement a Middleware plugin to all of the Blueprints that belongs to this specific Blueprint Group. In case of nested Blueprint Groups, the same middleware is applied across each of the Blueprints recur...
r"""|coro| Requests previously offline members from the guild to be filled up into the :attr:`Guild.members` cache. This function is usually not called. It should only be used if you have the ``fetch_offline_members`` parameter set to ``False``. When the client logs on and conn...
async def request_offline_members(self, *guilds): r"""|coro| Requests previously offline members from the guild to be filled up into the :attr:`Guild.members` cache. This function is usually not called. It should only be used if you have the ``fetch_offline_members`` parameter s...
Helper function used by `run` and `create_server`.
def _helper( self, host=None, port=None, debug=False, ssl=None, sock=None, workers=1, loop=None, protocol=HttpProtocol, backlog=100, stop_event=None, register_sys_signals=True, run_async=False, auto_reload=Fa...
Returns response object with body in text format. :param body: Response data to be encoded. :param status: Response code. :param headers: Custom Headers. :param content_type: the content type (string) of the response
def text( body, status=200, headers=None, content_type="text/plain; charset=utf-8" ): """ Returns response object with body in text format. :param body: Response data to be encoded. :param status: Response code. :param headers: Custom Headers. :param content_type: the content type (string) ...
Fetches and executes an exception handler and returns a response object :param request: Instance of :class:`sanic.request.Request` :param exception: Exception to handle :type request: :class:`sanic.request.Request` :type exception: :class:`sanic.exceptions.SanicException` or ...
def response(self, request, exception): """Fetches and executes an exception handler and returns a response object :param request: Instance of :class:`sanic.request.Request` :param exception: Exception to handle :type request: :class:`sanic.request.Request` :type except...
Provide a default behavior for the objects of :class:`ErrorHandler`. If a developer chooses to extent the :class:`ErrorHandler` they can provide a custom implementation for this method to behave in a way they see fit. :param request: Incoming request :param exception: Exception ...
def default(self, request, exception): """ Provide a default behavior for the objects of :class:`ErrorHandler`. If a developer chooses to extent the :class:`ErrorHandler` they can provide a custom implementation for this method to behave in a way they see fit. :param req...
Creates SSLContext instance for usage in asyncio.create_server. See ssl.SSLSocket.__init__ for more details.
def _create_ssl_context(cfg): """ Creates SSLContext instance for usage in asyncio.create_server. See ssl.SSLSocket.__init__ for more details. """ ctx = ssl.SSLContext(cfg.ssl_version) ctx.load_cert_chain(cfg.certfile, cfg.keyfile) ctx.verify_mode = cfg.cert_reqs ...
Trigger event callbacks (functions or async) :param events: one or more sync or async functions to execute :param loop: event loop
def trigger_events(events, loop): """Trigger event callbacks (functions or async) :param events: one or more sync or async functions to execute :param loop: event loop """ for event in events: result = event(loop) if isawaitable(result): loop.run_until_complete(result)
Start asynchronous HTTP Server on an individual process. :param host: Address to host on :param port: Port to host on :param request_handler: Sanic request handler with middleware :param error_handler: Sanic error handler with middleware :param before_start: function to be executed before the serve...
def serve( host, port, app, request_handler, error_handler, before_start=None, after_start=None, before_stop=None, after_stop=None, debug=False, request_timeout=60, response_timeout=60, keep_alive_timeout=5, ssl=None, sock=None, request_max_size=None, ...
Check if the connection needs to be kept alive based on the params attached to the `_keep_alive` attribute, :attr:`Signal.stopped` and :func:`HttpProtocol.parser.should_keep_alive` :return: ``True`` if connection is to be kept alive ``False`` else
def keep_alive(self): """ Check if the connection needs to be kept alive based on the params attached to the `_keep_alive` attribute, :attr:`Signal.stopped` and :func:`HttpProtocol.parser.should_keep_alive` :return: ``True`` if connection is to be kept alive ``False`` else ...
Check if elapsed time since last response exceeds our configured maximum keep alive timeout value and if so, close the transport pipe and let the response writer handle the error. :return: None
def keep_alive_timeout_callback(self): """ Check if elapsed time since last response exceeds our configured maximum keep alive timeout value and if so, close the transport pipe and let the response writer handle the error. :return: None """ time_elapsed = time() ...
Invoke the request handler defined by the :func:`sanic.app.Sanic.handle_request` method :return: None
def execute_request_handler(self): """ Invoke the request handler defined by the :func:`sanic.app.Sanic.handle_request` method :return: None """ self._response_timeout_handler = self.loop.call_later( self.response_timeout, self.response_timeout_callback ...
Helper method provided to enable the logging of responses in case if the :attr:`HttpProtocol.access_log` is enabled. :param response: Response generated for the current request :type response: :class:`sanic.response.HTTPResponse` or :class:`sanic.response.StreamingHTTPResponse` ...
def log_response(self, response): """ Helper method provided to enable the logging of responses in case if the :attr:`HttpProtocol.access_log` is enabled. :param response: Response generated for the current request :type response: :class:`sanic.response.HTTPResponse` or ...
Writes response content synchronously to the transport.
def write_response(self, response): """ Writes response content synchronously to the transport. """ if self._response_timeout_handler: self._response_timeout_handler.cancel() self._response_timeout_handler = None try: keep_alive = self.keep_ali...
In case if the transport pipes are closed and the sanic app encounters an error while writing data to the transport pipe, we log the error with proper details. :param message: Error message to display :param from_error: If the bail out was invoked while handling an exception...
def bail_out(self, message, from_error=False): """ In case if the transport pipes are closed and the sanic app encounters an error while writing data to the transport pipe, we log the error with proper details. :param message: Error message to display :param from_error: ...
This is called when KeepAlive feature is used, it resets the connection in order for it to be able to handle receiving another request on the same connection.
def cleanup(self): """This is called when KeepAlive feature is used, it resets the connection in order for it to be able to handle receiving another request on the same connection.""" self.parser = None self.request = None self.url = None self.headers = None ...
Parse a request body and returns fields and files :param body: bytes request body :param boundary: bytes multipart boundary :return: fields (RequestParameters), files (RequestParameters)
def parse_multipart_form(body, boundary): """Parse a request body and returns fields and files :param body: bytes request body :param boundary: bytes multipart boundary :return: fields (RequestParameters), files (RequestParameters) """ files = RequestParameters() fields = RequestParameters(...
Stop reading when gets None
async def read(self): """ Stop reading when gets None """ payload = await self._queue.get() self._queue.task_done() return payload
Attempt to return the auth header token. :return: token related to request
def token(self): """Attempt to return the auth header token. :return: token related to request """ prefixes = ("Bearer", "Token") auth_header = self.headers.get("Authorization") if auth_header is not None: for prefix in prefixes: if prefix in...
Method to parse `query_string` using `urllib.parse.parse_qs`. This methods is used by `args` property. Can be used directly if you need to change default parameters. :param keep_blank_values: flag indicating whether blank values in percent-encoded queries should be treated as blank s...
def get_args( self, keep_blank_values: bool = False, strict_parsing: bool = False, encoding: str = "utf-8", errors: str = "replace", ) -> RequestParameters: """ Method to parse `query_string` using `urllib.parse.parse_qs`. This methods is used by `args...
Method to parse `query_string` using `urllib.parse.parse_qsl`. This methods is used by `query_args` property. Can be used directly if you need to change default parameters. :param keep_blank_values: flag indicating whether blank values in percent-encoded queries should be treated as ...
def get_query_args( self, keep_blank_values: bool = False, strict_parsing: bool = False, encoding: str = "utf-8", errors: str = "replace", ) -> list: """ Method to parse `query_string` using `urllib.parse.parse_qsl`. This methods is used by `query_args...
Attempt to return the original client ip based on X-Forwarded-For or X-Real-IP. If HTTP headers are unavailable or untrusted, returns an empty string. :return: original client ip.
def remote_addr(self): """Attempt to return the original client ip based on X-Forwarded-For or X-Real-IP. If HTTP headers are unavailable or untrusted, returns an empty string. :return: original client ip. """ if not hasattr(self, "_remote_addr"): if self.app...
This function was borrowed from distutils.utils. While distutils is part of stdlib, it feels odd to use distutils in main application code. The function was modified to walk its talk and actually return bool and not int.
def strtobool(val): """ This function was borrowed from distutils.utils. While distutils is part of stdlib, it feels odd to use distutils in main application code. The function was modified to walk its talk and actually return bool and not int. """ val = val.lower() if val in ("y", "yes...
Load a configuration from an environment variable pointing to a configuration file. :param variable_name: name of the environment variable :return: bool. ``True`` if able to load config, ``False`` otherwise.
def from_envvar(self, variable_name): """Load a configuration from an environment variable pointing to a configuration file. :param variable_name: name of the environment variable :return: bool. ``True`` if able to load config, ``False`` otherwise. """ config_file = os.e...
Update the values from the given object. Objects are usually either modules or classes. Just the uppercase variables in that object are stored in the config. Example usage:: from yourapplication import default_config app.config.from_object(default_config) You s...
def from_object(self, obj): """Update the values from the given object. Objects are usually either modules or classes. Just the uppercase variables in that object are stored in the config. Example usage:: from yourapplication import default_config app.config.fro...
Looks for prefixed environment variables and applies them to the configuration if present.
def load_environment_vars(self, prefix=SANIC_PREFIX): """ Looks for prefixed environment variables and applies them to the configuration if present. """ for k, v in os.environ.items(): if k.startswith(prefix): _, config_key = k.split(prefix, 1) ...
Parse a parameter string into its constituent name, type, and pattern For example:: parse_parameter_string('<param_one:[A-z]>')` -> ('param_one', str, '[A-z]') :param parameter_string: String to parse :return: tuple containing (parameter_name, p...
def parse_parameter_string(cls, parameter_string): """Parse a parameter string into its constituent name, type, and pattern For example:: parse_parameter_string('<param_one:[A-z]>')` -> ('param_one', str, '[A-z]') :param parameter_string: String to parse ...
Add a handler to the route list :param uri: path to match :param methods: sequence of accepted method names. If none are provided, any method is allowed :param handler: request handler function. When executed, it should provide a response object. :param strict_sl...
def add( self, uri, methods, handler, host=None, strict_slashes=False, version=None, name=None, ): """Add a handler to the route list :param uri: path to match :param methods: sequence of accepted method names. If none are ...
Add a handler to the route list :param uri: path to match :param methods: sequence of accepted method names. If none are provided, any method is allowed :param handler: request handler function. When executed, it should provide a response object. :param name: use...
def _add(self, uri, methods, handler, host=None, name=None): """Add a handler to the route list :param uri: path to match :param methods: sequence of accepted method names. If none are provided, any method is allowed :param handler: request handler function. When...
Check if a URL pattern exists in a list of routes provided based on the comparison of URL pattern and the parameters. :param pattern: URL parameter pattern :param routes_to_check: list of dynamic routes either hashable or unhashable routes. :param parameters: List of :class:...
def check_dynamic_route_exists(pattern, routes_to_check, parameters): """ Check if a URL pattern exists in a list of routes provided based on the comparison of URL pattern and the parameters. :param pattern: URL parameter pattern :param routes_to_check: list of dynamic routes ei...
Find a route in the router based on the specified view name. :param view_name: string of view name to search by :param kwargs: additional params, usually for static files :return: tuple containing (uri, Route)
def find_route_by_view_name(self, view_name, name=None): """Find a route in the router based on the specified view name. :param view_name: string of view name to search by :param kwargs: additional params, usually for static files :return: tuple containing (uri, Route) """ ...
Get a request handler based on the URL of the request, or raises an error :param request: Request object :return: handler, arguments, keyword arguments
def get(self, request): """Get a request handler based on the URL of the request, or raises an error :param request: Request object :return: handler, arguments, keyword arguments """ # No virtual hosts specified; default behavior if not self.hosts: re...
Get a list of supported methods for a url and optional host. :param url: URL string (including host) :return: frozenset of supported methods
def get_supported_methods(self, url): """Get a list of supported methods for a url and optional host. :param url: URL string (including host) :return: frozenset of supported methods """ route = self.routes_all.get(url) # if methods are None then this logic will prevent a...
Get a request handler based on the URL of the request, or raises an error. Internal method for caching. :param url: request URL :param method: request method :return: handler, arguments, keyword arguments
def _get(self, url, method, host): """Get a request handler based on the URL of the request, or raises an error. Internal method for caching. :param url: request URL :param method: request method :return: handler, arguments, keyword arguments """ url = unquote(h...
Handler for request is stream or not. :param request: Request object :return: bool
def is_stream_handler(self, request): """ Handler for request is stream or not. :param request: Request object :return: bool """ try: handler = self.get(request)[0] except (NotFound, MethodNotSupported): return False if hasattr(handler, "vi...
Returns the executable.
def _get_args_for_reloading(): """Returns the executable.""" rv = [sys.executable] main_module = sys.modules["__main__"] mod_spec = getattr(main_module, "__spec__", None) if mod_spec: # Parent exe was launched as a module rather than a script rv.extend(["-m", mod_spec.name]) ...
Create a new process and a subprocess in it with the same arguments as this one.
def restart_with_reloader(): """Create a new process and a subprocess in it with the same arguments as this one. """ cwd = os.getcwd() args = _get_args_for_reloading() new_environ = os.environ.copy() new_environ["SANIC_SERVER_RUNNING"] = "true" cmd = " ".join(args) worker_process = P...
Find and kill child processes of a process (maximum two level). :param pid: PID of parent process (process ID) :return: Nothing
def kill_process_children_unix(pid): """Find and kill child processes of a process (maximum two level). :param pid: PID of parent process (process ID) :return: Nothing """ root_process_path = "/proc/{pid}/task/{pid}/children".format(pid=pid) if not os.path.isfile(root_process_path): ret...
Find and kill child processes of a process. :param pid: PID of parent process (process ID) :return: Nothing
def kill_process_children(pid): """Find and kill child processes of a process. :param pid: PID of parent process (process ID) :return: Nothing """ if sys.platform == "darwin": kill_process_children_osx(pid) elif sys.platform == "linux": kill_process_children_unix(pid) else: ...
Watch project files, restart worker process if a change happened. :param sleep_interval: interval in second. :return: Nothing
def watchdog(sleep_interval): """Watch project files, restart worker process if a change happened. :param sleep_interval: interval in second. :return: Nothing """ mtimes = {} worker_process = restart_with_reloader() signal.signal( signal.SIGTERM, lambda *args: kill_program_completly...
Return view function for use with the routing system, that dispatches request to appropriate handler method.
def as_view(cls, *class_args, **class_kwargs): """Return view function for use with the routing system, that dispatches request to appropriate handler method. """ def view(*args, **kwargs): self = view.view_class(*class_args, **class_kwargs) return self.dispatch_...
Use session object to perform 'get' request on url
async def bounded_fetch(session, url): """ Use session object to perform 'get' request on url """ async with sem, session.get(url) as response: return await response.json()
Removes all the entity headers present in the headers given. According to RFC 2616 Section 10.3.5, Content-Location and Expires are allowed as for the "strong cache validator". https://tools.ietf.org/html/rfc2616#section-10.3.5 returns the headers without the entity headers
def remove_entity_headers(headers, allowed=("content-location", "expires")): """ Removes all the entity headers present in the headers given. According to RFC 2616 Section 10.3.5, Content-Location and Expires are allowed as for the "strong cache validator". https://tools.ietf.org/html/rfc2616#se...
Preserve shape of the image.
def preserve_shape(func): """Preserve shape of the image.""" @wraps(func) def wrapped_function(img, *args, **kwargs): shape = img.shape result = func(img, *args, **kwargs) result = result.reshape(shape) return result return wrapped_function
Preserve dummy channel dim.
def preserve_channel_dim(func): """Preserve dummy channel dim.""" @wraps(func) def wrapped_function(img, *args, **kwargs): shape = img.shape result = func(img, *args, **kwargs) if len(shape) == 3 and shape[-1] == 1 and len(result.shape) == 2: result = np.expand_dims(resul...
Bleaches out pixels, mitation snow. From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library Args: img: snow_point: brightness_coeff: Returns:
def add_snow(img, snow_point, brightness_coeff): """Bleaches out pixels, mitation snow. From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library Args: img: snow_point: brightness_coeff: Returns: """ non_rgb_warning(img) input_dtype = img.dtype ...
Add sun flare. From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library Args: img (np.array): flare_center_x (float): flare_center_y (float): src_radius: src_color (int, int, int): circles (list): Returns:
def add_sun_flare(img, flare_center_x, flare_center_y, src_radius, src_color, circles): """Add sun flare. From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library Args: img (np.array): flare_center_x (float): flare_center_y (float): src_radius: src_c...
Add fog to the image. From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library Args: img (np.array): fog_coef (float): alpha_coef (float): haze_list (list): Returns:
def add_fog(img, fog_coef, alpha_coef, haze_list): """Add fog to the image. From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library Args: img (np.array): fog_coef (float): alpha_coef (float): haze_list (list): Returns: """ non_rgb_warning(img) ...
Add shadows to the image. From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library Args: img (np.array): vertices_list (list): Returns:
def add_shadow(img, vertices_list): """Add shadows to the image. From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library Args: img (np.array): vertices_list (list): Returns: """ non_rgb_warning(img) input_dtype = img.dtype needs_float = False if ...
Barrel / pincushion distortion. Unconventional augment. Reference: | https://stackoverflow.com/questions/6199636/formulas-for-barrel-pincushion-distortion | https://stackoverflow.com/questions/10364201/image-transformation-in-opencv | https://stackoverflow.com/questions/2477774/correctin...
def optical_distortion(img, k=0, dx=0, dy=0, interpolation=cv2.INTER_LINEAR, border_mode=cv2.BORDER_REFLECT_101, value=None): """Barrel / pincushion distortion. Unconventional augment. Reference: | https://stackoverflow.com/questions/6199636/formulas-for-barrel-pincushion-distor...
Reference: http://pythology.blogspot.sg/2014/03/interpolation-on-regular-distorted-grid.html
def grid_distortion(img, num_steps=10, xsteps=[], ysteps=[], interpolation=cv2.INTER_LINEAR, border_mode=cv2.BORDER_REFLECT_101, value=None): """ Reference: http://pythology.blogspot.sg/2014/03/interpolation-on-regular-distorted-grid.html """ height, width = img.shape[:2] ...
Elastic deformation of images as described in [Simard2003]_ (with modifications). Based on https://gist.github.com/erniejunior/601cdf56d2b424757de5 .. [Simard2003] Simard, Steinkraus and Platt, "Best Practices for Convolutional Neural Networks applied to Visual Document Analysis", in Proc. of...
def elastic_transform(image, alpha, sigma, alpha_affine, interpolation=cv2.INTER_LINEAR, border_mode=cv2.BORDER_REFLECT_101, value=None, random_state=None, approximate=False): """Elastic deformation of images as described in [Simard2003]_ (with modifications). Based on https://gist.github....
Flip a bounding box vertically around the x-axis.
def bbox_vflip(bbox, rows, cols): """Flip a bounding box vertically around the x-axis.""" x_min, y_min, x_max, y_max = bbox return [x_min, 1 - y_max, x_max, 1 - y_min]
Flip a bounding box horizontally around the y-axis.
def bbox_hflip(bbox, rows, cols): """Flip a bounding box horizontally around the y-axis.""" x_min, y_min, x_max, y_max = bbox return [1 - x_max, y_min, 1 - x_min, y_max]
Flip a bounding box either vertically, horizontally or both depending on the value of `d`. Raises: ValueError: if value of `d` is not -1, 0 or 1.
def bbox_flip(bbox, d, rows, cols): """Flip a bounding box either vertically, horizontally or both depending on the value of `d`. Raises: ValueError: if value of `d` is not -1, 0 or 1. """ if d == 0: bbox = bbox_vflip(bbox, rows, cols) elif d == 1: bbox = bbox_hflip(bbox, r...
Crop a bounding box using the provided coordinates of bottom-left and top-right corners in pixels and the required height and width of the crop.
def crop_bbox_by_coords(bbox, crop_coords, crop_height, crop_width, rows, cols): """Crop a bounding box using the provided coordinates of bottom-left and top-right corners in pixels and the required height and width of the crop. """ bbox = denormalize_bbox(bbox, rows, cols) x_min, y_min, x_max, y_ma...
Rotates a bounding box by 90 degrees CCW (see np.rot90) Args: bbox (tuple): A tuple (x_min, y_min, x_max, y_max). factor (int): Number of CCW rotations. Must be in range [0;3] See np.rot90. rows (int): Image rows. cols (int): Image cols.
def bbox_rot90(bbox, factor, rows, cols): """Rotates a bounding box by 90 degrees CCW (see np.rot90) Args: bbox (tuple): A tuple (x_min, y_min, x_max, y_max). factor (int): Number of CCW rotations. Must be in range [0;3] See np.rot90. rows (int): Image rows. cols (int): Image co...
Rotates a bounding box by angle degrees Args: bbox (tuple): A tuple (x_min, y_min, x_max, y_max). angle (int): Angle of rotation in degrees rows (int): Image rows. cols (int): Image cols. interpolation (int): interpolation method. return a tuple (x_min, y_min, x_max...
def bbox_rotate(bbox, angle, rows, cols, interpolation): """Rotates a bounding box by angle degrees Args: bbox (tuple): A tuple (x_min, y_min, x_max, y_max). angle (int): Angle of rotation in degrees rows (int): Image rows. cols (int): Image cols. interpolation (int): in...
Transposes a bounding box along given axis. Args: bbox (tuple): A tuple (x_min, y_min, x_max, y_max). axis (int): 0 - main axis, 1 - secondary axis. rows (int): Image rows. cols (int): Image cols.
def bbox_transpose(bbox, axis, rows, cols): """Transposes a bounding box along given axis. Args: bbox (tuple): A tuple (x_min, y_min, x_max, y_max). axis (int): 0 - main axis, 1 - secondary axis. rows (int): Image rows. cols (int): Image cols. """ x_min, y_min, x_max, y_...
Flip a keypoint vertically around the x-axis.
def keypoint_vflip(kp, rows, cols): """Flip a keypoint vertically around the x-axis.""" x, y, angle, scale = kp c = math.cos(angle) s = math.sin(angle) angle = math.atan2(-s, c) return [x, (rows - 1) - y, angle, scale]
Flip a keypoint either vertically, horizontally or both depending on the value of `d`. Raises: ValueError: if value of `d` is not -1, 0 or 1.
def keypoint_flip(bbox, d, rows, cols): """Flip a keypoint either vertically, horizontally or both depending on the value of `d`. Raises: ValueError: if value of `d` is not -1, 0 or 1. """ if d == 0: bbox = keypoint_vflip(bbox, rows, cols) elif d == 1: bbox = keypoint_hflip...
Rotates a keypoint by 90 degrees CCW (see np.rot90) Args: keypoint (tuple): A tuple (x, y, angle, scale). factor (int): Number of CCW rotations. Must be in range [0;3] See np.rot90. rows (int): Image rows. cols (int): Image cols.
def keypoint_rot90(keypoint, factor, rows, cols, **params): """Rotates a keypoint by 90 degrees CCW (see np.rot90) Args: keypoint (tuple): A tuple (x, y, angle, scale). factor (int): Number of CCW rotations. Must be in range [0;3] See np.rot90. rows (int): Image rows. cols (int)...
Scales a keypoint by scale_x and scale_y.
def keypoint_scale(keypoint, scale_x, scale_y, **params): """Scales a keypoint by scale_x and scale_y.""" x, y, a, s = keypoint return [x * scale_x, y * scale_y, a, s * max(scale_x, scale_y)]
Crop a keypoint using the provided coordinates of bottom-left and top-right corners in pixels and the required height and width of the crop.
def crop_keypoint_by_coords(keypoint, crop_coords, crop_height, crop_width, rows, cols): """Crop a keypoint using the provided coordinates of bottom-left and top-right corners in pixels and the required height and width of the crop. """ x, y, a, s = keypoint x1, y1, x2, y2 = crop_coords cropped_...
Unified rounding in all python versions.
def py3round(number): """Unified rounding in all python versions.""" if abs(round(number) - number) == 0.5: return int(2.0 * round(number / 2.0)) return int(round(number))
Args: factor (int): number of times the input will be rotated by 90 degrees.
def apply(self, img, factor=0, **params): """ Args: factor (int): number of times the input will be rotated by 90 degrees. """ return np.ascontiguousarray(np.rot90(img, factor))
Normalize coordinates of a bounding box. Divide x-coordinates by image width and y-coordinates by image height.
def normalize_bbox(bbox, rows, cols): """Normalize coordinates of a bounding box. Divide x-coordinates by image width and y-coordinates by image height. """ if rows == 0: raise ValueError('Argument rows cannot be zero') if cols == 0: raise ValueError('Argument cols cannot be zero') ...
Denormalize coordinates of a bounding box. Multiply x-coordinates by image width and y-coordinates by image height. This is an inverse operation for :func:`~albumentations.augmentations.bbox.normalize_bbox`.
def denormalize_bbox(bbox, rows, cols): """Denormalize coordinates of a bounding box. Multiply x-coordinates by image width and y-coordinates by image height. This is an inverse operation for :func:`~albumentations.augmentations.bbox.normalize_bbox`. """ if rows == 0: raise ValueError('Argument ...
Normalize a list of bounding boxes.
def normalize_bboxes(bboxes, rows, cols): """Normalize a list of bounding boxes.""" return [normalize_bbox(bbox, rows, cols) for bbox in bboxes]
Denormalize a list of bounding boxes.
def denormalize_bboxes(bboxes, rows, cols): """Denormalize a list of bounding boxes.""" return [denormalize_bbox(bbox, rows, cols) for bbox in bboxes]
Calculate the area of a bounding box in pixels.
def calculate_bbox_area(bbox, rows, cols): """Calculate the area of a bounding box in pixels.""" bbox = denormalize_bbox(bbox, rows, cols) x_min, y_min, x_max, y_max = bbox[:4] area = (x_max - x_min) * (y_max - y_min) return area
Filter bounding boxes and return only those boxes whose visibility after transformation is above the threshold and minimal area of bounding box in pixels is more then min_area. Args: original_shape (tuple): original image shape bboxes (list): original bounding boxes transformed_shape(tu...
def filter_bboxes_by_visibility(original_shape, bboxes, transformed_shape, transformed_bboxes, threshold=0., min_area=0.): """Filter bounding boxes and return only those boxes whose visibility after transformation is above the threshold and minimal area of bounding box in pixels ...
Convert a bounding box from a format specified in `source_format` to the format used by albumentations: normalized coordinates of bottom-left and top-right corners of the bounding box in a form of `[x_min, y_min, x_max, y_max]` e.g. `[0.15, 0.27, 0.67, 0.5]`. Args: bbox (list): bounding box ...
def convert_bbox_to_albumentations(bbox, source_format, rows, cols, check_validity=False): """Convert a bounding box from a format specified in `source_format` to the format used by albumentations: normalized coordinates of bottom-left and top-right corners of the bounding box in a form of `[x_min, y_min, x...
Convert a bounding box from the format used by albumentations to a format, specified in `target_format`. Args: bbox (list): bounding box with coordinates in the format used by albumentations target_format (str): required format of the output bounding box. Should be 'coco' or 'pascal_voc'. r...
def convert_bbox_from_albumentations(bbox, target_format, rows, cols, check_validity=False): """Convert a bounding box from the format used by albumentations to a format, specified in `target_format`. Args: bbox (list): bounding box with coordinates in the format used by albumentations target_f...