text
stringlengths
81
112k
:class:`float`: Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds. This operates similarly to :meth:`.Client.latency` except it uses the average latency of every shard's latency. To get a list of shard latency, check the :attr:`latencies` property. Returns ``nan`` if there are...
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 HEART...
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...
|coro| Closes the connection to discord. async def close(self): """|coro| Closes the connection to discord. """ if self.is_closed(): return self._closed = True for vc in self.voice_clients: try: await vc.disconnect() ...
|coro| Changes the client's presence. The activity parameter is a :class:`Activity` object (not a string) that represents the activity being done currently. This could also be the slimmed down versions, :class:`Game` and :class:`Streaming`. Example: :: game = disc...
Returns a :class:`list` of :class:`Member` with this role. def members(self): """Returns a :class:`list` of :class:`Member` with this role.""" all_members = self.guild.members if self.is_default(): return all_members role_id = self.id return [member for member in al...
|coro| Edits the role. You must have the :attr:`~Permissions.manage_roles` permission to use this. All fields are optional. Parameters ----------- name: :class:`str` The new role name to change to. permissions: :class:`Permissions` ...
|coro| Deletes the role. You must have the :attr:`~Permissions.manage_roles` permission to use this. Parameters ----------- reason: Optional[:class:`str`] The reason for deleting this role. Shows up on the audit log. Raises -------- ...
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, o...
Register the blueprint to the sanic app. :param app: Instance of :class:`sanic.app.Sanic` class :param options: Options to be used while registering the blueprint into the app. *url_prefix* - URL Prefix to override the blueprint prefix def register(self, app, options): ...
Create a blueprint route from a decorated function. :param uri: endpoint at which the route will be accessible. :param methods: list of acceptable HTTP methods. :param host: IP Address of FQDN for the sanic server to use. :param strict_slashes: Enforce the API urls are requested with a ...
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...
Create a blueprint websocket route from a function. :param handler: function for handling uri requests. Accepts function, or class instance with a view_class method. :param uri: endpoint at which the route will be accessible. :param host: IP Address of FQDN for the sanic...
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) ...
Create a blueprint middleware from a decorated function. :param args: Positional arguments to be used while invoking the middleware :param kwargs: optional keyword args that can be used with the middleware. def middleware(self, *args, **kwargs): """ Create a blu...
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...
Create a blueprint static route from a decorated function. :param uri: endpoint at which the route will be accessible. :param file_or_directory: Static asset. def static(self, uri, file_or_directory, *args, **kwargs): """Create a blueprint static route from a decorated function. :para...
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...
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_decor...
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 ...
Schedule a task to run later, after the loop has started. Different from asyncio.ensure_future in that it does not also return a future, and the actual ensure_future call is delayed until before server start. :param task: future, couroutine or awaitable def add_task(self, task): ...
Decorate a function to be registered as a route :param uri: path of the URL :param methods: list or tuple of methods allowed :param host: :param strict_slashes: :param stream: :param version: :param name: user defined route name for url_for :return: decor...
Decorate a function to be registered as a websocket route :param uri: path of the URL :param subprotocols: optional list of str with supported subprotocols :param host: :return: decorated function def websocket( self, uri, host=None, strict_slashes=None, subprotocols=None, name=...
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 ...
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 ...
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...
Decorate a function to be registered as a handler for exceptions :param exceptions: exceptions :return: decorated function def exception(self, *exceptions): """Decorate a function to be registered as a handler for exceptions :param exceptions: exceptions :return: decorated fun...
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...
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, midd...
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...
Register a blueprint on the application. :param blueprint: Blueprint object or (list, tuple) thereof :param options: option dictionary with blueprint defaults :return: Nothing def blueprint(self, blueprint, **options): """Register a blueprint on the application. :param bluepri...
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_blue...
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...
Run the HTTP Server and listen until keyboard interrupt or term signal. On termination, drain connections before closing. :param host: Address to host on :type host: str :param port: Port to host on :type port: int :param debug: Enables debug output (slows server) ...
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...
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=T...
Returns response object with body in json format. :param body: Response data to be serialized. :param status: Response code. :param headers: Custom Headers. :param kwargs: Remaining arguments that are passed to the json encoder. def json( body, status=200, headers=None, content_type="a...
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...
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 ...
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') ...
Abort execution and cause a 302 redirect (by default). :param to: path or fully qualified URL to redirect to :param headers: optional dict of headers to include in the new request :param status: status code (int) of the new request, defaults to 302 :param content_type: the content type (string) of the ...
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...
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 ...
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: ...
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...
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 ...
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 ...
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(cf...
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 loo...
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...
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): """ Chec...
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...
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._...
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` ...
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 =...
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...
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 ...
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: by...
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...
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...
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 ...
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-R...
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. Whil...
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 environm...
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...
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.item...
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...
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...
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...
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:...
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 ...
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: ...
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) ...
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...
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] ...
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",...
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_en...
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 ...
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": ...
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 """ ...
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 vi...
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_heade...
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: ...
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/...
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 h...
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_cente...
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-Augmentati...
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...
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...
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...
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: Value...
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 co...
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 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...
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 gi...