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 no shards ready. def latency(self): """: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 no shards ready. """ if not self.shards: return float('nan') return sum(latency for _, latency in self.latencies) / len(self.shards)
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.items()]
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 connects to the websocket, Discord does not provide the library with offline members if the number of members in the guild is larger than 250. You can check if a guild is large if :attr:`Guild.large` is ``True``. Parameters ----------- \*guilds: :class:`Guild` An argument list of guilds to request offline members for. Raises ------- InvalidArgument If any guild is unavailable or not large in the collection. 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 set to ``False``. When the client logs on and connects to the websocket, Discord does not provide the library with offline members if the number of members in the guild is larger than 250. You can check if a guild is large if :attr:`Guild.large` is ``True``. Parameters ----------- \*guilds: :class:`Guild` An argument list of guilds to request offline members for. Raises ------- InvalidArgument If any guild is unavailable or not large in the collection. """ if any(not g.large or g.unavailable for g in guilds): raise InvalidArgument('An unavailable or non-large guild was passed.') _guilds = sorted(guilds, key=lambda g: g.shard_id) for shard_id, sub_guilds in itertools.groupby(_guilds, key=lambda g: g.shard_id): sub_guilds = list(sub_guilds) await self._connection.request_offline_members(sub_guilds, shard_id=shard_id)
|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() except Exception: pass to_close = [shard.ws.close() for shard in self.shards.values()] if to_close: await asyncio.wait(to_close, loop=self.loop) await self.http.close()
|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 = discord.Game("with the API") await client.change_presence(status=discord.Status.idle, activity=game) Parameters ---------- activity: Optional[Union[:class:`Game`, :class:`Streaming`, :class:`Activity`]] The activity being done. ``None`` if no currently active activity is done. status: Optional[:class:`Status`] Indicates what status to change to. If None, then :attr:`Status.online` is used. afk: :class:`bool` Indicates if you are going AFK. This allows the discord client to know how to handle push notifications better for you in case you are actually idle and not lying. shard_id: Optional[:class:`int`] The shard_id to change the presence to. If not specified or ``None``, then it will change the presence of every shard the bot can see. Raises ------ InvalidArgument If the ``activity`` parameter is not of proper type. async def change_presence(self, *, activity=None, status=None, afk=False, shard_id=None): """|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 = discord.Game("with the API") await client.change_presence(status=discord.Status.idle, activity=game) Parameters ---------- activity: Optional[Union[:class:`Game`, :class:`Streaming`, :class:`Activity`]] The activity being done. ``None`` if no currently active activity is done. status: Optional[:class:`Status`] Indicates what status to change to. If None, then :attr:`Status.online` is used. afk: :class:`bool` Indicates if you are going AFK. This allows the discord client to know how to handle push notifications better for you in case you are actually idle and not lying. shard_id: Optional[:class:`int`] The shard_id to change the presence to. If not specified or ``None``, then it will change the presence of every shard the bot can see. Raises ------ InvalidArgument If the ``activity`` parameter is not of proper type. """ if status is None: status = 'online' status_enum = Status.online elif status is Status.offline: status = 'invisible' status_enum = Status.offline else: status_enum = status status = str(status) if shard_id is None: for shard in self.shards.values(): await shard.ws.change_presence(activity=activity, status=status, afk=afk) guilds = self._connection.guilds else: shard = self.shards[shard_id] await shard.ws.change_presence(activity=activity, status=status, afk=afk) guilds = [g for g in self._connection.guilds if g.shard_id == shard_id] for guild in guilds: me = guild.me if me is None: continue me.activities = (activity,) me.status = status_enum
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 all_members if member._roles.has(role_id)]
|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` The new permissions to change to. colour: :class:`Colour` The new colour to change to. (aliased to color as well) hoist: :class:`bool` Indicates if the role should be shown separately in the member list. mentionable: :class:`bool` Indicates if the role should be mentionable by others. position: :class:`int` The new role's position. This must be below your top role's position or it will fail. reason: Optional[:class:`str`] The reason for editing this role. Shows up on the audit log. Raises ------- Forbidden You do not have permissions to change the role. HTTPException Editing the role failed. InvalidArgument An invalid position was given or the default role was asked to be moved. async def edit(self, *, reason=None, **fields): """|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` The new permissions to change to. colour: :class:`Colour` The new colour to change to. (aliased to color as well) hoist: :class:`bool` Indicates if the role should be shown separately in the member list. mentionable: :class:`bool` Indicates if the role should be mentionable by others. position: :class:`int` The new role's position. This must be below your top role's position or it will fail. reason: Optional[:class:`str`] The reason for editing this role. Shows up on the audit log. Raises ------- Forbidden You do not have permissions to change the role. HTTPException Editing the role failed. InvalidArgument An invalid position was given or the default role was asked to be moved. """ position = fields.get('position') if position is not None: await self._move(position, reason=reason) self.position = position try: colour = fields['colour'] except KeyError: colour = fields.get('color', self.colour) payload = { 'name': fields.get('name', self.name), 'permissions': fields.get('permissions', self.permissions).value, 'color': colour.value, 'hoist': fields.get('hoist', self.hoist), 'mentionable': fields.get('mentionable', self.mentionable) } data = await self._state.http.edit_role(self.guild.id, self.id, reason=reason, **payload) self._update(data)
|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 -------- Forbidden You do not have permissions to delete the role. HTTPException Deleting the role failed. async def delete(self, *, reason=None): """|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 -------- Forbidden You do not have permissions to delete the role. HTTPException Deleting the role failed. """ await self._state.http.delete_role(self.guild.id, self.id, reason=reason)
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(nested): """itertools.chain() but leaves strings untouched""" for i in nested: if isinstance(i, (list, tuple)): yield from chain(i) elif isinstance(i, BlueprintGroup): yield from i.blueprints else: yield i bps = BlueprintGroup(url_prefix=url_prefix) for bp in chain(blueprints): if bp.url_prefix is None: bp.url_prefix = "" bp.url_prefix = url_prefix + bp.url_prefix bps.append(bp) return bps
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): """ 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 """ url_prefix = options.get("url_prefix", self.url_prefix) # Routes for future in self.routes: # attach the blueprint name to the handler so that it can be # prefixed properly in the router future.handler.__blueprintname__ = self.name # Prepend the blueprint URI prefix if available uri = url_prefix + future.uri if url_prefix else future.uri version = future.version or self.version app.route( uri=uri[1:] if uri.startswith("//") else uri, methods=future.methods, host=future.host or self.host, strict_slashes=future.strict_slashes, stream=future.stream, version=version, name=future.name, )(future.handler) for future in self.websocket_routes: # attach the blueprint name to the handler so that it can be # prefixed properly in the router future.handler.__blueprintname__ = self.name # Prepend the blueprint URI prefix if available uri = url_prefix + future.uri if url_prefix else future.uri app.websocket( uri=uri, host=future.host or self.host, strict_slashes=future.strict_slashes, name=future.name, )(future.handler) # Middleware for future in self.middlewares: if future.args or future.kwargs: app.register_middleware( future.middleware, *future.args, **future.kwargs ) else: app.register_middleware(future.middleware) # Exceptions for future in self.exceptions: app.exception(*future.args, **future.kwargs)(future.handler) # Static Files for future in self.statics: # Prepend the blueprint URI prefix if available uri = url_prefix + future.uri if url_prefix else future.uri app.static( uri, future.file_or_directory, *future.args, **future.kwargs ) # Event listeners for event, listeners in self.listeners.items(): for listener in listeners: app.listener(event)(listener)
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 training */* :param stream: If the route should provide a streaming support :param version: Blueprint Version :param name: Unique name to identify the Route :return a decorated method that when invoked will return an object of type :class:`FutureRoute` def route( self, uri, methods=frozenset({"GET"}), host=None, strict_slashes=None, stream=False, version=None, name=None, ): """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 training */* :param stream: If the route should provide a streaming support :param version: Blueprint Version :param name: Unique name to identify the Route :return a decorated method that when invoked will return an object of type :class:`FutureRoute` """ if strict_slashes is None: strict_slashes = self.strict_slashes def decorator(handler): route = FutureRoute( handler, uri, methods, host, strict_slashes, stream, version, name, ) self.routes.append(route) return handler return decorator
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: Blueprint Version :param name: Unique name to identify the Websocket Route 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. :param strict_slashes: Enforce the API urls are requested with a training */* :param version: Blueprint Version :param name: Unique name to identify the Websocket Route """ if strict_slashes is None: strict_slashes = self.strict_slashes def decorator(handler): route = FutureRoute( handler, uri, [], host, strict_slashes, False, version, name ) self.websocket_routes.append(route) return handler return decorator
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 server to use. :param version: Blueprint Version :param name: Unique name to identify the Websocket Route :return: function or class instance def add_websocket_route( self, handler, uri, host=None, version=None, name=None ): """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 server to use. :param version: Blueprint Version :param name: Unique name to identify the Websocket Route :return: function or class instance """ self.websocket(uri=uri, host=host, version=version, name=name)(handler) return handler
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
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 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 register_middleware(_middleware): future_middleware = FutureMiddleware(_middleware, args, kwargs) self.middlewares.append(future_middleware) return _middleware # Detect which way this was called, @middleware or @middleware('AT') if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): middleware = args[0] args = [] return register_middleware(middleware) else: if kwargs.get("bp_group") and callable(args[0]): middleware = args[0] args = args[1:] kwargs.pop("bp_group") return register_middleware(middleware) else: return register_middleware
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 decorated method to handle global exceptions for any route registered under this blueprint. 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 to the exception handler :return a decorated method to handle global exceptions for any route registered under this blueprint. """ def decorator(handler): exception = FutureException(handler, args, kwargs) self.exceptions.append(exception) return handler return decorator
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. :param uri: endpoint at which the route will be accessible. :param file_or_directory: Static asset. """ name = kwargs.pop("name", "static") if not name.startswith(self.name + "."): name = "{}.{}".format(self.name, name) kwargs.update(name=name) strict_slashes = kwargs.get("strict_slashes") if strict_slashes is None and self.strict_slashes is not None: kwargs.update(strict_slashes=self.strict_slashes) static = FutureStatic(uri, file_or_directory, args, kwargs) self.statics.append(static)
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 */* :param version: API Version :param name: Unique name that can be used to identify the Route :return: Object decorated with :func:`route` method 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: Instruct :class:`sanic.app.Sanic` to check if the request URLs need to terminate with a */* :param version: API Version :param name: Unique name that can be used to identify the Route :return: Object decorated with :func:`route` method """ return self.route( uri, methods=frozenset({"GET"}), host=host, strict_slashes=strict_slashes, version=version, name=name, )
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
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 code. 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 in response.py for the given status code. """ if message is None: message = STATUS_CODES.get(status_code) # These are stored as bytes in the STATUS_CODES dict message = message.decode("utf8") sanic_exception = _sanic_exceptions.get(status_code, SanicException) raise sanic_exception(message=message, status_code=status_code)
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): """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 """ try: if callable(task): try: self.loop.create_task(task(self)) except TypeError: self.loop.create_task(task()) else: self.loop.create_task(task) except SanicException: @self.listener("before_server_start") def run(app, loop): if callable(task): try: loop.create_task(task(self)) except TypeError: loop.create_task(task()) else: loop.create_task(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: decorated function def route( self, uri, methods=frozenset({"GET"}), host=None, strict_slashes=None, stream=False, version=None, name=None, ): """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: decorated function """ # Fix case where the user did not prefix the URL with a / # and will probably get confused as to why it's not working if not uri.startswith("/"): uri = "/" + uri if stream: self.is_request_stream = True if strict_slashes is None: strict_slashes = self.strict_slashes def response(handler): args = list(signature(handler).parameters.keys()) if not args: raise ValueError( "Required parameter `request` missing " "in the {0}() route?".format(handler.__name__) ) if stream: handler.is_stream = stream self.router.add( uri=uri, methods=methods, handler=handler, host=host, strict_slashes=strict_slashes, version=version, name=name, ) return handler return response
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=None ): """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 """ self.enable_websocket() # Fix case where the user did not prefix the URL with a / # and will probably get confused as to why it's not working if not uri.startswith("/"): uri = "/" + uri if strict_slashes is None: strict_slashes = self.strict_slashes def response(handler): async def websocket_handler(request, *args, **kwargs): request.app = self if not getattr(handler, "__blueprintname__", False): request.endpoint = handler.__name__ else: request.endpoint = ( getattr(handler, "__blueprintname__", "") + handler.__name__ ) try: protocol = request.transport.get_protocol() except AttributeError: # On Python3.5 the Transport classes in asyncio do not # have a get_protocol() method as in uvloop protocol = request.transport._protocol ws = await protocol.websocket_handshake(request, subprotocols) # schedule the application handler # its future is kept in self.websocket_tasks in case it # needs to be cancelled due to the server being stopped fut = ensure_future(handler(request, ws, *args, **kwargs)) self.websocket_tasks.add(fut) try: await fut except (CancelledError, ConnectionClosed): pass finally: self.websocket_tasks.remove(fut) await ws.close() self.router.add( uri=uri, handler=websocket_handler, methods=frozenset({"GET"}), host=host, strict_slashes=strict_slashes, name=name, ) return handler return response
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 handler :param strict_slashes: If the API endpoint needs to terminate with a "/" or not :param subprotocols: Subprotocols to be used with websocket handshake :param name: A unique name assigned to the URL so that it can be used with :func:`url_for` :return: Objected decorated by :func:`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 that can handle the websocket request :param host: Host IP or FQDN details :param uri: URL path that will be mapped to the websocket handler :param strict_slashes: If the API endpoint needs to terminate with a "/" or not :param subprotocols: Subprotocols to be used with websocket handshake :param name: A unique name assigned to the URL so that it can be used with :func:`url_for` :return: Objected decorated by :func:`websocket` """ if strict_slashes is None: strict_slashes = self.strict_slashes return self.websocket( uri, host=host, strict_slashes=strict_slashes, subprotocols=subprotocols, name=name, )(handler)
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 # websocket tasks, to allow the server to exit promptly @self.listener("before_server_stop") def cancel_websocket_tasks(app, loop): for task in self.websocket_tasks: task.cancel() self.websocket_enabled = enable
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 address or FQDN specific to the host :return: None 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 needs to clean up the LRU route cache :param host: IP address or FQDN specific to the host :return: None """ self.router.remove(uri, clean_cache, host)
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 function """ def response(handler): for exception in exceptions: if isinstance(exception, (tuple, list)): for e in exception: self.error_handler.add(e, handler) else: self.error_handler.add(exception, handler) return handler return response
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 middleware :param attach_to: The state at which the middleware needs to be invoked in the lifecycle of an *HTTP Request*. **request** - Invoke before the request is processed **response** - Invoke before the response is returned back :return: decorated method 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 level. :param middleware: Callback method to be attached to the middleware :param attach_to: The state at which the middleware needs to be invoked in the lifecycle of an *HTTP Request*. **request** - Invoke before the request is processed **response** - Invoke before the response is returned back :return: decorated method """ if attach_to == "request": if middleware not in self.request_middleware: self.request_middleware.append(middleware) if attach_to == "response": if middleware not in self.response_middleware: self.response_middleware.appendleft(middleware) return middleware
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 type of middleware is being registered. """ # Detect which way this was called, @middleware or @middleware('AT') if callable(middleware_or_request): return self.register_middleware(middleware_or_request) else: return partial( self.register_middleware, attach_to=middleware_or_request )
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 for the Static file/directory with static files :param pattern: Regex Pattern identifying the valid static files :param use_modified_since: If true, send file modified time, and return not modified if the browser's matches the server's :param use_content_range: If true, process header for range requests and sends the file part that is requested :param stream_large_files: If true, use the :func:`StreamingHTTPResponse.file_stream` handler rather than the :func:`HTTPResponse.file` handler to send the file. If this is an integer, this represents the threshold size to switch to :func:`StreamingHTTPResponse.file_stream` :param name: user defined name used for url_for :param host: Host IP or FQDN for the service to use :param strict_slashes: Instruct :class:`Sanic` to check if the request URLs need to terminate with a */* :param content_type: user defined content type for header :return: None 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, ): """ 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 for the Static file/directory with static files :param pattern: Regex Pattern identifying the valid static files :param use_modified_since: If true, send file modified time, and return not modified if the browser's matches the server's :param use_content_range: If true, process header for range requests and sends the file part that is requested :param stream_large_files: If true, use the :func:`StreamingHTTPResponse.file_stream` handler rather than the :func:`HTTPResponse.file` handler to send the file. If this is an integer, this represents the threshold size to switch to :func:`StreamingHTTPResponse.file_stream` :param name: user defined name used for url_for :param host: Host IP or FQDN for the service to use :param strict_slashes: Instruct :class:`Sanic` to check if the request URLs need to terminate with a */* :param content_type: user defined content type for header :return: None """ static_register( self, uri, file_or_directory, pattern, use_modified_since, use_content_range, stream_large_files, name, host, strict_slashes, content_type, )
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 blueprint: Blueprint object or (list, tuple) thereof :param options: option dictionary with blueprint defaults :return: Nothing """ if isinstance(blueprint, (list, tuple, BlueprintGroup)): for item in blueprint: self.blueprint(item, **options) return if blueprint.name in self.blueprints: assert self.blueprints[blueprint.name] is blueprint, ( 'A blueprint with the name "%s" is already registered. ' "Blueprint names must be unique." % (blueprint.name,) ) else: self.blueprints[blueprint.name] = blueprint self._blueprint_order.append(blueprint) blueprint.register(self, options)
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 dictionary with blueprint defaults :return: None """ if self.debug: warnings.simplefilter("default") warnings.warn( "Use of register_blueprint will be deprecated in " "version 1.0. Please use the blueprint method" " instead", DeprecationWarning, ) return self.blueprint(*args, **kwargs)
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 the response as the only argument :param stream_callback: Coroutine that handles streaming a StreamingHTTPResponse if produced by the handler. :return: Nothing 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 :param write_callback: Synchronous response function to be called with the response as the only argument :param stream_callback: Coroutine that handles streaming a StreamingHTTPResponse if produced by the handler. :return: Nothing """ # Define `response` var here to remove warnings about # allocation before assignment below. response = None cancelled = False try: # -------------------------------------------- # # Request Middleware # -------------------------------------------- # response = await self._run_request_middleware(request) # No middleware results if not response: # -------------------------------------------- # # Execute Handler # -------------------------------------------- # # Fetch handler from router handler, args, kwargs, uri = self.router.get(request) request.uri_template = uri if handler is None: raise ServerError( ( "'None' was returned while requesting a " "handler from the router" ) ) else: if not getattr(handler, "__blueprintname__", False): request.endpoint = self._build_endpoint_name( handler.__name__ ) else: request.endpoint = self._build_endpoint_name( getattr(handler, "__blueprintname__", ""), handler.__name__, ) # Run response handler response = handler(request, *args, **kwargs) if isawaitable(response): response = await response except CancelledError: # If response handler times out, the server handles the error # and cancels the handle_request job. # In this case, the transport is already closed and we cannot # issue a response. response = None cancelled = True except Exception as e: # -------------------------------------------- # # Response Generation Failed # -------------------------------------------- # try: response = self.error_handler.response(request, e) if isawaitable(response): response = await response except Exception as e: if isinstance(e, SanicException): response = self.error_handler.default( request=request, exception=e ) elif self.debug: response = HTTPResponse( "Error while handling error: {}\nStack: {}".format( e, format_exc() ), status=500, ) else: response = HTTPResponse( "An error occurred while handling an error", status=500 ) finally: # -------------------------------------------- # # Response Middleware # -------------------------------------------- # # Don't run response middleware if response is None if response is not None: try: response = await self._run_response_middleware( request, response ) except CancelledError: # Response middleware can timeout too, as above. response = None cancelled = True except BaseException: error_logger.exception( "Exception occurred in one of response " "middleware handlers" ) if cancelled: raise CancelledError() # pass the response to the correct callback if isinstance(response, StreamingHTTPResponse): await stream_callback(response) else: write_callback(response)
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) :type debug: bool :param ssl: SSLContext, or location of certificate and key for SSL encryption of worker(s) :type ssl:SSLContext or dict :param sock: Socket for the server to accept connections from :type sock: socket :param workers: Number of processes received before it is respected :type workers: int :param protocol: Subclass of asyncio Protocol class :type protocol: type[Protocol] :param backlog: a number of unaccepted connections that the system will allow before refusing new connections :type backlog: int :param stop_event: event to be triggered before stopping the app - deprecated :type stop_event: None :param register_sys_signals: Register SIG* events :type register_sys_signals: bool :param access_log: Enables writing access logs (slows server) :type access_log: bool :return: Nothing def run( self, host: Optional[str] = None, port: Optional[int] = None, debug: bool = False, ssl: Union[dict, SSLContext, None] = None, sock: Optional[socket] = None, workers: int = 1, protocol: Type[Protocol] = None, backlog: int = 100, stop_event: Any = None, register_sys_signals: bool = True, access_log: Optional[bool] = None, **kwargs: Any ) -> None: """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) :type debug: bool :param ssl: SSLContext, or location of certificate and key for SSL encryption of worker(s) :type ssl:SSLContext or dict :param sock: Socket for the server to accept connections from :type sock: socket :param workers: Number of processes received before it is respected :type workers: int :param protocol: Subclass of asyncio Protocol class :type protocol: type[Protocol] :param backlog: a number of unaccepted connections that the system will allow before refusing new connections :type backlog: int :param stop_event: event to be triggered before stopping the app - deprecated :type stop_event: None :param register_sys_signals: Register SIG* events :type register_sys_signals: bool :param access_log: Enables writing access logs (slows server) :type access_log: bool :return: Nothing """ if "loop" in kwargs: raise TypeError( "loop is not a valid argument. To use an existing loop, " "change to create_server().\nSee more: " "https://sanic.readthedocs.io/en/latest/sanic/deploying.html" "#asynchronous-support" ) # Default auto_reload to false auto_reload = False # If debug is set, default it to true (unless on windows) if debug and os.name == "posix": auto_reload = True # Allow for overriding either of the defaults auto_reload = kwargs.get("auto_reload", auto_reload) if sock is None: host, port = host or "127.0.0.1", port or 8000 if protocol is None: protocol = ( WebSocketProtocol if self.websocket_enabled else HttpProtocol ) if stop_event is not None: if debug: warnings.simplefilter("default") warnings.warn( "stop_event will be removed from future versions.", DeprecationWarning, ) # if access_log is passed explicitly change config.ACCESS_LOG if access_log is not None: self.config.ACCESS_LOG = access_log server_settings = self._helper( host=host, port=port, debug=debug, ssl=ssl, sock=sock, workers=workers, protocol=protocol, backlog=backlog, register_sys_signals=register_sys_signals, auto_reload=auto_reload, ) try: self.is_running = True if workers == 1: if auto_reload and os.name != "posix": # This condition must be removed after implementing # auto reloader for other operating systems. raise NotImplementedError if ( auto_reload and os.environ.get("SANIC_SERVER_RUNNING") != "true" ): reloader_helpers.watchdog(2) else: serve(**server_settings) else: serve_multiple(server_settings, workers) except BaseException: error_logger.exception( "Experienced exception while trying to serve" ) raise finally: self.is_running = False logger.info("Server Stopped")
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 not the preferred way to run a :class:`Sanic` application. :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) :type debug: bool :param ssl: SSLContext, or location of certificate and key for SSL encryption of worker(s) :type ssl:SSLContext or dict :param sock: Socket for the server to accept connections from :type sock: socket :param protocol: Subclass of asyncio Protocol class :type protocol: type[Protocol] :param backlog: a number of unaccepted connections that the system will allow before refusing new connections :type backlog: int :param stop_event: event to be triggered before stopping the app - deprecated :type stop_event: None :param access_log: Enables writing access logs (slows server) :type access_log: bool :param return_asyncio_server: flag that defines whether there's a need to return asyncio.Server or start it serving right away :type return_asyncio_server: bool :param asyncio_server_kwargs: key-value arguments for asyncio/uvloop create_server method :type asyncio_server_kwargs: dict :return: Nothing 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: Any = None, access_log: Optional[bool] = None, return_asyncio_server=False, asyncio_server_kwargs=None, ) -> None: """ 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 not the preferred way to run a :class:`Sanic` application. :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) :type debug: bool :param ssl: SSLContext, or location of certificate and key for SSL encryption of worker(s) :type ssl:SSLContext or dict :param sock: Socket for the server to accept connections from :type sock: socket :param protocol: Subclass of asyncio Protocol class :type protocol: type[Protocol] :param backlog: a number of unaccepted connections that the system will allow before refusing new connections :type backlog: int :param stop_event: event to be triggered before stopping the app - deprecated :type stop_event: None :param access_log: Enables writing access logs (slows server) :type access_log: bool :param return_asyncio_server: flag that defines whether there's a need to return asyncio.Server or start it serving right away :type return_asyncio_server: bool :param asyncio_server_kwargs: key-value arguments for asyncio/uvloop create_server method :type asyncio_server_kwargs: dict :return: Nothing """ if sock is None: host, port = host or "127.0.0.1", port or 8000 if protocol is None: protocol = ( WebSocketProtocol if self.websocket_enabled else HttpProtocol ) if stop_event is not None: if debug: warnings.simplefilter("default") warnings.warn( "stop_event will be removed from future versions.", DeprecationWarning, ) # if access_log is passed explicitly change config.ACCESS_LOG if access_log is not None: self.config.ACCESS_LOG = access_log server_settings = self._helper( host=host, port=port, debug=debug, ssl=ssl, sock=sock, loop=get_event_loop(), protocol=protocol, backlog=backlog, run_async=return_asyncio_server, ) # Trigger before_start events await self.trigger_events( server_settings.get("before_start", []), server_settings.get("loop"), ) return await serve( asyncio_server_kwargs=asyncio_server_kwargs, **server_settings )
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=False, ): """Helper function used by `run` and `create_server`.""" if isinstance(ssl, dict): # try common aliaseses cert = ssl.get("cert") or ssl.get("certificate") key = ssl.get("key") or ssl.get("keyfile") if cert is None or key is None: raise ValueError("SSLContext or certificate and key required.") context = create_default_context(purpose=Purpose.CLIENT_AUTH) context.load_cert_chain(cert, keyfile=key) ssl = context if stop_event is not None: if debug: warnings.simplefilter("default") warnings.warn( "stop_event will be removed from future versions.", DeprecationWarning, ) self.error_handler.debug = debug self.debug = debug server_settings = { "protocol": protocol, "request_class": self.request_class, "is_request_stream": self.is_request_stream, "router": self.router, "host": host, "port": port, "sock": sock, "ssl": ssl, "app": self, "signal": Signal(), "debug": debug, "request_handler": self.handle_request, "error_handler": self.error_handler, "request_timeout": self.config.REQUEST_TIMEOUT, "response_timeout": self.config.RESPONSE_TIMEOUT, "keep_alive_timeout": self.config.KEEP_ALIVE_TIMEOUT, "request_max_size": self.config.REQUEST_MAX_SIZE, "request_buffer_queue_size": self.config.REQUEST_BUFFER_QUEUE_SIZE, "keep_alive": self.config.KEEP_ALIVE, "loop": loop, "register_sys_signals": register_sys_signals, "backlog": backlog, "access_log": self.config.ACCESS_LOG, "websocket_max_size": self.config.WEBSOCKET_MAX_SIZE, "websocket_max_queue": self.config.WEBSOCKET_MAX_QUEUE, "websocket_read_limit": self.config.WEBSOCKET_READ_LIMIT, "websocket_write_limit": self.config.WEBSOCKET_WRITE_LIMIT, "graceful_shutdown_timeout": self.config.GRACEFUL_SHUTDOWN_TIMEOUT, } # -------------------------------------------- # # Register start/stop events # -------------------------------------------- # for event_name, settings_name, reverse in ( ("before_server_start", "before_start", False), ("after_server_start", "after_start", False), ("before_server_stop", "before_stop", True), ("after_server_stop", "after_stop", True), ): listeners = self.listeners[event_name].copy() if reverse: listeners.reverse() # Prepend sanic to the arguments when listeners are triggered listeners = [partial(listener, self) for listener in listeners] server_settings[settings_name] = listeners if self.configure_logging and debug: logger.setLevel(logging.DEBUG) if ( self.config.LOGO and os.environ.get("SANIC_SERVER_RUNNING") != "true" ): logger.debug( self.config.LOGO if isinstance(self.config.LOGO, str) else BASE_LOGO ) if run_async: server_settings["run_async"] = True # Serve if host and port and os.environ.get("SANIC_SERVER_RUNNING") != "true": proto = "http" if ssl is not None: proto = "https" logger.info("Goin' Fast @ {}://{}:{}".format(proto, host, port)) return server_settings
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="application/json", dumps=json_dumps, **kwargs ): """ 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. """ return HTTPResponse( dumps(body, **kwargs), headers=headers, status=status, content_type=content_type, )
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) of the response """ return HTTPResponse( body, status=status, headers=headers, content_type=content_type )
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 (in bytes) :param mime_type: Specific mime_type. :param headers: Custom Headers. :param filename: Override filename. :param _range: """ headers = headers or {} if filename: headers.setdefault( "Content-Disposition", 'attachment; filename="{}"'.format(filename) ) filename = filename or path.split(location)[-1] _file = await open_async(location, mode="rb") async def _streaming_fn(response): nonlocal _file, chunk_size try: if _range: chunk_size = min((_range.size, chunk_size)) await _file.seek(_range.start) to_send = _range.size while to_send > 0: content = await _file.read(chunk_size) if len(content) < 1: break to_send -= len(content) await response.write(content) else: while True: content = await _file.read(chunk_size) if len(content) < 1: break await response.write(content) finally: await _file.close() return # Returning from this fn closes the stream mime_type = mime_type or guess_type(filename)[0] or "text/plain" if _range: headers["Content-Range"] = "bytes %s-%s/%s" % ( _range.start, _range.end, _range.total, ) status = 206 return StreamingHTTPResponse( streaming_fn=_streaming_fn, status=status, headers=headers, content_type=mime_type, )
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') await response.write('bar') return stream(streaming_fn, content_type='text/plain') :param streaming_fn: A coroutine accepts a response and writes content to that response. :param mime_type: Specific mime_type. :param headers: Custom Headers. 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 index(request): async def streaming_fn(response): await response.write('foo') await response.write('bar') return stream(streaming_fn, content_type='text/plain') :param streaming_fn: A coroutine accepts a response and writes content to that response. :param mime_type: Specific mime_type. :param headers: Custom Headers. """ return StreamingHTTPResponse( streaming_fn, headers=headers, content_type=content_type, status=status )
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 response :returns: the redirecting Response def redirect( to, headers=None, status=302, content_type="text/html; charset=utf-8" ): """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 response :returns: the redirecting Response """ headers = headers or {} # URL Quote the URL before redirecting safe_to = quote_plus(to, safe=":/%#?&=@[]!$&'()*+,;") # According to RFC 7231, a relative URI is now permitted. headers["Location"] = safe_to return HTTPResponse( status=status, headers=headers, content_type=content_type )
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.protocol.drain()
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, keep_alive=keep_alive, keep_alive_timeout=keep_alive_timeout, ) self.protocol.push_data(headers) await self.protocol.drain() await self.streaming_fn(self) self.protocol.push_data(b"0\r\n\r\n")
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. :return: None """ self._blueprints.insert(index, item)
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 Parameters to be use middleware :param kwargs: Optional Keyword arg to use with Middleware :return: Partial function to apply the middleware 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 recursively. :param args: Optional positional Parameters to be use middleware :param kwargs: Optional Keyword arg to use with Middleware :return: Partial function to apply the middleware """ kwargs["bp_group"] = True def register_middleware_for_blueprints(fn): for blueprint in self.blueprints: blueprint.middleware(fn, *args, **kwargs) return register_middleware_for_blueprints
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 :class:`Exception` :return: Wrap the return value obtained from :func:`default` or registered handler for that type of exception. 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 exception: :class:`sanic.exceptions.SanicException` or :class:`Exception` :return: Wrap the return value obtained from :func:`default` or registered handler for that type of exception. """ handler = self.lookup(exception) response = None try: if handler: response = handler(request, exception) if response is None: response = self.default(request, exception) except Exception: self.log(format_exc()) try: url = repr(request.url) except AttributeError: url = "unknown" response_message = ( "Exception raised in exception handler " '"%s" for uri: %s' ) logger.exception(response_message, handler.__name__, url) if self.debug: return text(response_message % (handler.__name__, url), 500) else: return text("An error occurred while handling an error", 500) return response
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 object :type request: :class:`sanic.request.Request` :type exception: :class:`sanic.exceptions.SanicException` or :class:`Exception` :return: 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 request: Incoming request :param exception: Exception object :type request: :class:`sanic.request.Request` :type exception: :class:`sanic.exceptions.SanicException` or :class:`Exception` :return: """ self.log(format_exc()) try: url = repr(request.url) except AttributeError: url = "unknown" response_message = "Exception occurred while handling uri: %s" logger.exception(response_message, url) if issubclass(type(exception), SanicException): return text( "Error: {}".format(exception), status=getattr(exception, "status_code", 500), headers=getattr(exception, "headers", dict()), ) elif self.debug: html_output = self._render_traceback_html(exception, request) return html(html_output, status=500) else: return html(INTERNAL_SERVER_ERROR_HTML, status=500)
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 if cfg.ca_certs: ctx.load_verify_locations(cfg.ca_certs) if cfg.ciphers: ctx.set_ciphers(cfg.ciphers) return ctx
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 server starts listening. Takes arguments `app` instance and `loop` :param after_start: function to be executed after the server starts listening. Takes arguments `app` instance and `loop` :param before_stop: function to be executed when a stop signal is received before it is respected. Takes arguments `app` instance and `loop` :param after_stop: function to be executed when a stop signal is received after it is respected. Takes arguments `app` instance and `loop` :param debug: enables debug output (slows server) :param request_timeout: time in seconds :param response_timeout: time in seconds :param keep_alive_timeout: time in seconds :param ssl: SSLContext :param sock: Socket for the server to accept connections from :param request_max_size: size in bytes, `None` for no limit :param reuse_port: `True` for multiple workers :param loop: asyncio compatible event loop :param protocol: subclass of asyncio protocol class :param request_class: Request class to use :param access_log: disable/enable access log :param websocket_max_size: enforces the maximum size for incoming messages in bytes. :param websocket_max_queue: sets the maximum length of the queue that holds incoming messages. :param websocket_read_limit: sets the high-water limit of the buffer for incoming bytes, the low-water limit is half the high-water limit. :param websocket_write_limit: sets the high-water limit of the buffer for outgoing bytes, the low-water limit is a quarter of the high-water limit. :param is_request_stream: disable/enable Request.stream :param request_buffer_queue_size: streaming request buffer queue size :param router: Router object :param graceful_shutdown_timeout: How long take to Force close non-idle connection :param asyncio_server_kwargs: key-value args for asyncio/uvloop create_server method :return: Nothing 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, request_buffer_queue_size=100, reuse_port=False, loop=None, protocol=HttpProtocol, backlog=100, register_sys_signals=True, run_multiple=False, run_async=False, connections=None, signal=Signal(), request_class=None, access_log=True, keep_alive=True, is_request_stream=False, router=None, websocket_max_size=None, websocket_max_queue=None, websocket_read_limit=2 ** 16, websocket_write_limit=2 ** 16, state=None, graceful_shutdown_timeout=15.0, asyncio_server_kwargs=None, ): """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 server starts listening. Takes arguments `app` instance and `loop` :param after_start: function to be executed after the server starts listening. Takes arguments `app` instance and `loop` :param before_stop: function to be executed when a stop signal is received before it is respected. Takes arguments `app` instance and `loop` :param after_stop: function to be executed when a stop signal is received after it is respected. Takes arguments `app` instance and `loop` :param debug: enables debug output (slows server) :param request_timeout: time in seconds :param response_timeout: time in seconds :param keep_alive_timeout: time in seconds :param ssl: SSLContext :param sock: Socket for the server to accept connections from :param request_max_size: size in bytes, `None` for no limit :param reuse_port: `True` for multiple workers :param loop: asyncio compatible event loop :param protocol: subclass of asyncio protocol class :param request_class: Request class to use :param access_log: disable/enable access log :param websocket_max_size: enforces the maximum size for incoming messages in bytes. :param websocket_max_queue: sets the maximum length of the queue that holds incoming messages. :param websocket_read_limit: sets the high-water limit of the buffer for incoming bytes, the low-water limit is half the high-water limit. :param websocket_write_limit: sets the high-water limit of the buffer for outgoing bytes, the low-water limit is a quarter of the high-water limit. :param is_request_stream: disable/enable Request.stream :param request_buffer_queue_size: streaming request buffer queue size :param router: Router object :param graceful_shutdown_timeout: How long take to Force close non-idle connection :param asyncio_server_kwargs: key-value args for asyncio/uvloop create_server method :return: Nothing """ if not run_async: # create new event_loop after fork loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) if debug: loop.set_debug(debug) connections = connections if connections is not None else set() server = partial( protocol, loop=loop, connections=connections, signal=signal, app=app, request_handler=request_handler, error_handler=error_handler, request_timeout=request_timeout, response_timeout=response_timeout, keep_alive_timeout=keep_alive_timeout, request_max_size=request_max_size, request_class=request_class, access_log=access_log, keep_alive=keep_alive, is_request_stream=is_request_stream, router=router, websocket_max_size=websocket_max_size, websocket_max_queue=websocket_max_queue, websocket_read_limit=websocket_read_limit, websocket_write_limit=websocket_write_limit, state=state, debug=debug, ) asyncio_server_kwargs = ( asyncio_server_kwargs if asyncio_server_kwargs else {} ) server_coroutine = loop.create_server( server, host, port, ssl=ssl, reuse_port=reuse_port, sock=sock, backlog=backlog, **asyncio_server_kwargs ) if run_async: return server_coroutine trigger_events(before_start, loop) try: http_server = loop.run_until_complete(server_coroutine) except BaseException: logger.exception("Unable to start server") return trigger_events(after_start, loop) # Ignore SIGINT when run_multiple if run_multiple: signal_func(SIGINT, SIG_IGN) # Register signals for graceful termination if register_sys_signals: _singals = (SIGTERM,) if run_multiple else (SIGINT, SIGTERM) for _signal in _singals: try: loop.add_signal_handler(_signal, loop.stop) except NotImplementedError: logger.warning( "Sanic tried to use loop.add_signal_handler " "but it is not implemented on this platform." ) pid = os.getpid() try: logger.info("Starting worker [%s]", pid) loop.run_forever() finally: logger.info("Stopping worker [%s]", pid) # Run the on_stop function if provided trigger_events(before_stop, loop) # Wait for event loop to finish and all connections to drain http_server.close() loop.run_until_complete(http_server.wait_closed()) # Complete all tasks on the loop signal.stopped = True for connection in connections: connection.close_if_idle() # Gracefully shutdown timeout. # We should provide graceful_shutdown_timeout, # instead of letting connection hangs forever. # Let's roughly calcucate time. start_shutdown = 0 while connections and (start_shutdown < graceful_shutdown_timeout): loop.run_until_complete(asyncio.sleep(0.1)) start_shutdown = start_shutdown + 0.1 # Force close non-idle connection after waiting for # graceful_shutdown_timeout coros = [] for conn in connections: if hasattr(conn, "websocket") and conn.websocket: coros.append(conn.websocket.close_connection()) else: conn.close() _shutdown = asyncio.gather(*coros, loop=loop) loop.run_until_complete(_shutdown) trigger_events(after_stop, loop) loop.close()
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 """ return ( self._keep_alive and not self.signal.stopped and self.parser.should_keep_alive() )
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() - self._last_response_time if time_elapsed < self.keep_alive_timeout: time_left = self.keep_alive_timeout - time_elapsed self._keep_alive_timeout_handler = self.loop.call_later( time_left, self.keep_alive_timeout_callback ) else: logger.debug("KeepAlive Timeout. Closing connection.") self.transport.close() self.transport = None
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 ) self._last_request_time = time() self._request_handler_task = self.loop.create_task( self.request_handler( self.request, self.write_response, self.stream_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 :class:`sanic.response.StreamingHTTPResponse` :return: None 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 :class:`sanic.response.StreamingHTTPResponse` :return: None """ if self.access_log: extra = {"status": getattr(response, "status", 0)} if isinstance(response, HTTPResponse): extra["byte"] = len(response.body) else: extra["byte"] = -1 extra["host"] = "UNKNOWN" if self.request is not None: if self.request.ip: extra["host"] = "{0}:{1}".format( self.request.ip, self.request.port ) extra["request"] = "{0} {1}".format( self.request.method, self.request.url ) else: extra["request"] = "nil" access_logger.info("", extra=extra)
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_alive self.transport.write( response.output( self.request.version, keep_alive, self.keep_alive_timeout ) ) self.log_response(response) except AttributeError: logger.error( "Invalid response object for url %s, " "Expected Type: HTTPResponse, Actual Type: %s", self.url, type(response), ) self.write_error(ServerError("Invalid response type")) except RuntimeError: if self._debug: logger.error( "Connection lost before response written @ %s", self.request.ip, ) keep_alive = False except Exception as e: self.bail_out( "Writing response failed, connection closed {}".format(repr(e)) ) finally: if not keep_alive: self.transport.close() self.transport = None else: self._keep_alive_timeout_handler = self.loop.call_later( self.keep_alive_timeout, self.keep_alive_timeout_callback ) self._last_response_time = time() self.cleanup()
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 scenario. :type message: str :type from_error: bool :return: None 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: If the bail out was invoked while handling an exception scenario. :type message: str :type from_error: bool :return: None """ if from_error or self.transport is None or self.transport.is_closing(): logger.error( "Transport closed @ %s and exception " "experienced during error handling", ( self.transport.get_extra_info("peername") if self.transport is not None else "N/A" ), ) logger.debug("Exception:", exc_info=True) else: self.write_error(ServerError(message)) logger.error(message)
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 self._request_handler_task = None self._request_stream_task = None self._total_request_size = 0 self._is_stream_handler = False
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() form_parts = body.split(boundary) for form_part in form_parts[1:-1]: file_name = None content_type = "text/plain" content_charset = "utf-8" field_name = None line_index = 2 line_end_index = 0 while not line_end_index == -1: line_end_index = form_part.find(b"\r\n", line_index) form_line = form_part[line_index:line_end_index].decode("utf-8") line_index = line_end_index + 2 if not form_line: break colon_index = form_line.index(":") form_header_field = form_line[0:colon_index].lower() form_header_value, form_parameters = parse_header( form_line[colon_index + 2 :] ) if form_header_field == "content-disposition": field_name = form_parameters.get("name") file_name = form_parameters.get("filename") # non-ASCII filenames in RFC2231, "filename*" format if file_name is None and form_parameters.get("filename*"): encoding, _, value = email.utils.decode_rfc2231( form_parameters["filename*"] ) file_name = unquote(value, encoding=encoding) elif form_header_field == "content-type": content_type = form_header_value content_charset = form_parameters.get("charset", "utf-8") if field_name: post_data = form_part[line_index:-4] if file_name is None: value = post_data.decode(content_charset) if field_name in fields: fields[field_name].append(value) else: fields[field_name] = [value] else: form_file = File( type=content_type, name=file_name, body=post_data ) if field_name in files: files[field_name].append(form_file) else: files[field_name] = [form_file] else: logger.debug( "Form-data field does not have a 'name' parameter " "in the Content-Disposition header" ) return fields, files
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 auth_header: return auth_header.partition(prefix)[-1].strip() return auth_header
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 strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. :type keep_blank_values: bool :param strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. :type strict_parsing: bool :param encoding: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. :type encoding: str :param errors: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. :type errors: str :return: RequestParameters 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` 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 strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. :type keep_blank_values: bool :param strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. :type strict_parsing: bool :param encoding: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. :type encoding: str :param errors: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. :type errors: str :return: RequestParameters """ if not self.parsed_args[ (keep_blank_values, strict_parsing, encoding, errors) ]: if self.query_string: self.parsed_args[ (keep_blank_values, strict_parsing, encoding, errors) ] = RequestParameters( parse_qs( qs=self.query_string, keep_blank_values=keep_blank_values, strict_parsing=strict_parsing, encoding=encoding, errors=errors, ) ) return self.parsed_args[ (keep_blank_values, strict_parsing, encoding, errors) ]
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 blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. :type keep_blank_values: bool :param strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. :type strict_parsing: bool :param encoding: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. :type encoding: str :param errors: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. :type errors: str :return: list 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` 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 strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. :type keep_blank_values: bool :param strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. :type strict_parsing: bool :param encoding: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. :type encoding: str :param errors: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. :type errors: str :return: list """ if not self.parsed_not_grouped_args[ (keep_blank_values, strict_parsing, encoding, errors) ]: if self.query_string: self.parsed_not_grouped_args[ (keep_blank_values, strict_parsing, encoding, errors) ] = parse_qsl( qs=self.query_string, keep_blank_values=keep_blank_values, strict_parsing=strict_parsing, encoding=encoding, errors=errors, ) return self.parsed_not_grouped_args[ (keep_blank_values, strict_parsing, encoding, errors) ]
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.config.PROXIES_COUNT == 0: self._remote_addr = "" elif self.app.config.REAL_IP_HEADER and self.headers.get( self.app.config.REAL_IP_HEADER ): self._remote_addr = self.headers[ self.app.config.REAL_IP_HEADER ] elif self.app.config.FORWARDED_FOR_HEADER: forwarded_for = self.headers.get( self.app.config.FORWARDED_FOR_HEADER, "" ).split(",") remote_addrs = [ addr for addr in [addr.strip() for addr in forwarded_for] if addr ] if self.app.config.PROXIES_COUNT == -1: self._remote_addr = remote_addrs[0] elif len(remote_addrs) >= self.app.config.PROXIES_COUNT: self._remote_addr = remote_addrs[ -self.app.config.PROXIES_COUNT ] else: self._remote_addr = "" else: self._remote_addr = "" return self._remote_addr
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", "t", "true", "on", "1"): return True elif val in ("n", "no", "f", "false", "off", "0"): return False else: raise ValueError("invalid truth value %r" % (val,))
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.environ.get(variable_name) if not config_file: raise RuntimeError( "The environment variable %r is not set and " "thus configuration could not be loaded." % variable_name ) return self.from_pyfile(config_file)
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 should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with :meth:`from_pyfile` and ideally from a location not within the package because the package might be installed system wide. :param obj: an object holding the configuration 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.from_object(default_config) You should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with :meth:`from_pyfile` and ideally from a location not within the package because the package might be installed system wide. :param obj: an object holding the configuration """ for key in dir(obj): if key.isupper(): self[key] = getattr(obj, key)
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) try: self[config_key] = int(v) except ValueError: try: self[config_key] = float(v) except ValueError: try: self[config_key] = strtobool(v) except ValueError: self[config_key] = v
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, parameter_type, parameter_pattern) 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 :return: tuple containing (parameter_name, parameter_type, parameter_pattern) """ # We could receive NAME or NAME:PATTERN name = parameter_string pattern = "string" if ":" in parameter_string: name, pattern = parameter_string.split(":", 1) if not name: raise ValueError( "Invalid parameter syntax: {}".format(parameter_string) ) default = (str, pattern) # Pull from pre-configured types _type, pattern = REGEX_TYPES.get(pattern, default) return name, _type, pattern
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_slashes: strict to trailing slash :param version: current version of the route or blueprint. See docs for further details. :return: Nothing 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 provided, any method is allowed :param handler: request handler function. When executed, it should provide a response object. :param strict_slashes: strict to trailing slash :param version: current version of the route or blueprint. See docs for further details. :return: Nothing """ if version is not None: version = re.escape(str(version).strip("/").lstrip("v")) uri = "/".join(["/v{}".format(version), uri.lstrip("/")]) # add regular version self._add(uri, methods, handler, host, name) if strict_slashes: return if not isinstance(host, str) and host is not None: # we have gotten back to the top of the recursion tree where the # host was originally a list. By now, we've processed the strict # slashes logic on the leaf nodes (the individual host strings in # the list of host) return # Add versions with and without trailing / slashed_methods = self.routes_all.get(uri + "/", frozenset({})) unslashed_methods = self.routes_all.get(uri[:-1], frozenset({})) if isinstance(methods, Iterable): _slash_is_missing = all( method in slashed_methods for method in methods ) _without_slash_is_missing = all( method in unslashed_methods for method in methods ) else: _slash_is_missing = methods in slashed_methods _without_slash_is_missing = methods in unslashed_methods slash_is_missing = not uri[-1] == "/" and not _slash_is_missing without_slash_is_missing = ( uri[-1] == "/" and not _without_slash_is_missing and not uri == "/" ) # add version with trailing slash if slash_is_missing: self._add(uri + "/", methods, handler, host, name) # add version without trailing slash elif without_slash_is_missing: self._add(uri[:-1], methods, handler, host, name)
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: user defined route name for url_for :return: Nothing 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 executed, it should provide a response object. :param name: user defined route name for url_for :return: Nothing """ if host is not None: if isinstance(host, str): uri = host + uri self.hosts.add(host) else: if not isinstance(host, Iterable): raise ValueError( "Expected either string or Iterable of " "host strings, not {!r}".format(host) ) for host_ in host: self.add(uri, methods, handler, host_, name) return # Dict for faster lookups of if method allowed if methods: methods = frozenset(methods) parameters = [] parameter_names = set() properties = {"unhashable": None} def add_parameter(match): name = match.group(1) name, _type, pattern = self.parse_parameter_string(name) if name in parameter_names: raise ParameterNameConflicts( "Multiple parameter named <{name}> " "in route uri {uri}".format(name=name, uri=uri) ) parameter_names.add(name) parameter = Parameter(name=name, cast=_type) parameters.append(parameter) # Mark the whole route as unhashable if it has the hash key in it if re.search(r"(^|[^^]){1}/", pattern): properties["unhashable"] = True # Mark the route as unhashable if it matches the hash key elif re.search(r"/", pattern): properties["unhashable"] = True return "({})".format(pattern) pattern_string = re.sub(self.parameter_pattern, add_parameter, uri) pattern = re.compile(r"^{}$".format(pattern_string)) def merge_route(route, methods, handler): # merge to the existing route when possible. if not route.methods or not methods: # method-unspecified routes are not mergeable. raise RouteExists("Route already registered: {}".format(uri)) elif route.methods.intersection(methods): # already existing method is not overloadable. duplicated = methods.intersection(route.methods) raise RouteExists( "Route already registered: {} [{}]".format( uri, ",".join(list(duplicated)) ) ) if isinstance(route.handler, CompositionView): view = route.handler else: view = CompositionView() view.add(route.methods, route.handler) view.add(methods, handler) route = route._replace( handler=view, methods=methods.union(route.methods) ) return route if parameters: # TODO: This is too complex, we need to reduce the complexity if properties["unhashable"]: routes_to_check = self.routes_always_check ndx, route = self.check_dynamic_route_exists( pattern, routes_to_check, parameters ) else: routes_to_check = self.routes_dynamic[url_hash(uri)] ndx, route = self.check_dynamic_route_exists( pattern, routes_to_check, parameters ) if ndx != -1: # Pop the ndx of the route, no dups of the same route routes_to_check.pop(ndx) else: route = self.routes_all.get(uri) # prefix the handler name with the blueprint name # if available # special prefix for static files is_static = False if name and name.startswith("_static_"): is_static = True name = name.split("_static_", 1)[-1] if hasattr(handler, "__blueprintname__"): handler_name = "{}.{}".format( handler.__blueprintname__, name or handler.__name__ ) else: handler_name = name or getattr(handler, "__name__", None) if route: route = merge_route(route, methods, handler) else: route = Route( handler=handler, methods=methods, pattern=pattern, parameters=parameters, name=handler_name, uri=uri, ) self.routes_all[uri] = route if is_static: pair = self.routes_static_files.get(handler_name) if not (pair and (pair[0] + "/" == uri or uri + "/" == pair[0])): self.routes_static_files[handler_name] = (uri, route) else: pair = self.routes_names.get(handler_name) if not (pair and (pair[0] + "/" == uri or uri + "/" == pair[0])): self.routes_names[handler_name] = (uri, route) if properties["unhashable"]: self.routes_always_check.append(route) elif parameters: self.routes_dynamic[url_hash(uri)].append(route) else: self.routes_static[uri] = route
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:`Parameter` items :return: Tuple of index and route if matching route exists else -1 for index and None for route 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 either hashable or unhashable routes. :param parameters: List of :class:`Parameter` items :return: Tuple of index and route if matching route exists else -1 for index and None for route """ for ndx, route in enumerate(routes_to_check): if route.pattern == pattern and route.parameters == parameters: return ndx, route else: return -1, 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) 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) """ if not view_name: return (None, None) if view_name == "static" or view_name.endswith(".static"): return self.routes_static_files.get(name, (None, None)) return self.routes_names.get(view_name, (None, None))
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: return self._get(request.path, request.method, "") # virtual hosts specified; try to match route to the host header try: return self._get( request.path, request.method, request.headers.get("Host", "") ) # try default hosts except NotFound: return self._get(request.path, request.method, "")
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 an error return getattr(route, "methods", None) or frozenset()
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(host + url) # Check against known static routes route = self.routes_static.get(url) method_not_supported = MethodNotSupported( "Method {} not allowed for URL {}".format(method, url), method=method, allowed_methods=self.get_supported_methods(url), ) if route: if route.methods and method not in route.methods: raise method_not_supported match = route.pattern.match(url) else: route_found = False # Move on to testing all regex routes for route in self.routes_dynamic[url_hash(url)]: match = route.pattern.match(url) route_found |= match is not None # Do early method checking if match and method in route.methods: break else: # Lastly, check against all regex routes that cannot be hashed for route in self.routes_always_check: match = route.pattern.match(url) route_found |= match is not None # Do early method checking if match and method in route.methods: break else: # Route was found but the methods didn't match if route_found: raise method_not_supported raise NotFound("Requested URL {} not found".format(url)) kwargs = { p.name: p.cast(value) for value, p in zip(match.groups(1), route.parameters) } route_handler = route.handler if hasattr(route_handler, "handlers"): route_handler = route_handler.handlers[method] return route_handler, [], kwargs, route.uri
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, "view_class") and hasattr( handler.view_class, request.method.lower() ): handler = getattr(handler.view_class, request.method.lower()) return hasattr(handler, "is_stream")
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]) if len(sys.argv) > 1: rv.extend(sys.argv[1:]) else: rv.extend(sys.argv) return rv
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 = Process( target=subprocess.call, args=(cmd,), kwargs={"cwd": cwd, "shell": True, "env": new_environ}, ) worker_process.start() return worker_process
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): return with open(root_process_path) as children_list_file: children_list_pid = children_list_file.read().split() for child_pid in children_list_pid: children_proc_path = "/proc/%s/task/%s/children" % ( child_pid, child_pid, ) if not os.path.isfile(children_proc_path): continue with open(children_proc_path) as children_list_file_2: children_list_pid_2 = children_list_file_2.read().split() for _pid in children_list_pid_2: try: os.kill(int(_pid), signal.SIGTERM) except ProcessLookupError: continue try: os.kill(int(child_pid), signal.SIGTERM) except ProcessLookupError: continue
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: pass
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(worker_process) ) signal.signal( signal.SIGINT, lambda *args: kill_program_completly(worker_process) ) while True: for filename in _iter_module_files(): try: mtime = os.stat(filename).st_mtime except OSError: continue old_time = mtimes.get(filename) if old_time is None: mtimes[filename] = mtime continue elif mtime > old_time: kill_process_children(worker_process.pid) worker_process.terminate() worker_process = restart_with_reloader() mtimes[filename] = mtime break sleep(sleep_interval)
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_request(*args, **kwargs) if cls.decorators: view.__module__ = cls.__module__ for decorator in cls.decorators: view = decorator(view) view.view_class = cls view.__doc__ = cls.__doc__ view.__module__ = cls.__module__ view.__name__ = cls.__name__ return view
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#section-10.3.5 returns the headers without the entity headers """ allowed = set([h.lower() for h in allowed]) headers = { header: value for header, value in headers.items() if not is_entity_header(header) or header.lower() in allowed } return headers
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(result, axis=-1) return result return wrapped_function
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 needs_float = False snow_point *= 127.5 # = 255 / 2 snow_point += 85 # = 255 / 3 if input_dtype == np.float32: img = from_float(img, dtype=np.dtype('uint8')) needs_float = True elif input_dtype not in (np.uint8, np.float32): raise ValueError('Unexpected dtype {} for RandomSnow augmentation'.format(input_dtype)) image_HLS = cv2.cvtColor(img, cv2.COLOR_RGB2HLS) image_HLS = np.array(image_HLS, dtype=np.float32) image_HLS[:, :, 1][image_HLS[:, :, 1] < snow_point] *= brightness_coeff image_HLS[:, :, 1] = clip(image_HLS[:, :, 1], np.uint8, 255) image_HLS = np.array(image_HLS, dtype=np.uint8) image_RGB = cv2.cvtColor(image_HLS, cv2.COLOR_HLS2RGB) if needs_float: image_RGB = to_float(image_RGB, max_value=255) return image_RGB
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) input_dtype = img.dtype needs_float = False if input_dtype == np.float32: img = from_float(img, dtype=np.dtype('uint8')) needs_float = True elif input_dtype not in (np.uint8, np.float32): raise ValueError('Unexpected dtype {} for RandomFog augmentation'.format(input_dtype)) height, width = img.shape[:2] hw = max(int(width // 3 * fog_coef), 10) for haze_points in haze_list: x, y = haze_points overlay = img.copy() output = img.copy() alpha = alpha_coef * fog_coef rad = hw // 2 point = (x + hw // 2, y + hw // 2) cv2.circle(overlay, point, int(rad), (255, 255, 255), -1) cv2.addWeighted(overlay, alpha, output, 1 - alpha, 0, output) img = output.copy() image_rgb = cv2.blur(img, (hw // 10, hw // 10)) if needs_float: image_rgb = to_float(image_rgb, max_value=255) return image_rgb
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_color (int, int, int): circles (list): Returns: """ non_rgb_warning(img) input_dtype = img.dtype needs_float = False if input_dtype == np.float32: img = from_float(img, dtype=np.dtype('uint8')) needs_float = True elif input_dtype not in (np.uint8, np.float32): raise ValueError('Unexpected dtype {} for RandomSunFlareaugmentation'.format(input_dtype)) overlay = img.copy() output = img.copy() for (alpha, (x, y), rad3, (r_color, g_color, b_color)) in circles: cv2.circle(overlay, (x, y), rad3, (r_color, g_color, b_color), -1) cv2.addWeighted(overlay, alpha, output, 1 - alpha, 0, output) point = (int(flare_center_x), int(flare_center_y)) overlay = output.copy() num_times = src_radius // 10 alpha = np.linspace(0.0, 1, num=num_times) rad = np.linspace(1, src_radius, num=num_times) for i in range(num_times): cv2.circle(overlay, point, int(rad[i]), src_color, -1) alp = alpha[num_times - i - 1] * alpha[num_times - i - 1] * alpha[num_times - i - 1] cv2.addWeighted(overlay, alp, output, 1 - alp, 0, output) image_rgb = output if needs_float: image_rgb = to_float(image_rgb, max_value=255) return image_rgb
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 input_dtype == np.float32: img = from_float(img, dtype=np.dtype('uint8')) needs_float = True elif input_dtype not in (np.uint8, np.float32): raise ValueError('Unexpected dtype {} for RandomSnow augmentation'.format(input_dtype)) image_hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS) mask = np.zeros_like(img) # adding all shadow polygons on empty mask, single 255 denotes only red channel for vertices in vertices_list: cv2.fillPoly(mask, vertices, 255) # if red channel is hot, image's "Lightness" channel's brightness is lowered red_max_value_ind = mask[:, :, 0] == 255 image_hls[:, :, 1][red_max_value_ind] = image_hls[:, :, 1][red_max_value_ind] * 0.5 image_rgb = cv2.cvtColor(image_hls, cv2.COLOR_HLS2RGB) if needs_float: image_rgb = to_float(image_rgb, max_value=255) return image_rgb
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/correcting-fisheye-distortion-programmatically | http://www.coldvision.io/2017/03/02/advanced-lane-finding-using-opencv/ 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-distortion | https://stackoverflow.com/questions/10364201/image-transformation-in-opencv | https://stackoverflow.com/questions/2477774/correcting-fisheye-distortion-programmatically | http://www.coldvision.io/2017/03/02/advanced-lane-finding-using-opencv/ """ height, width = img.shape[:2] fx = width fy = width cx = width * 0.5 + dx cy = height * 0.5 + dy camera_matrix = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]], dtype=np.float32) distortion = np.array([k, k, 0, 0, 0], dtype=np.float32) map1, map2 = cv2.initUndistortRectifyMap(camera_matrix, distortion, None, None, (width, height), cv2.CV_32FC1) img = cv2.remap(img, map1, map2, interpolation=interpolation, borderMode=border_mode, borderValue=value) return img
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] x_step = width // num_steps xx = np.zeros(width, np.float32) prev = 0 for idx, x in enumerate(range(0, width, x_step)): start = x end = x + x_step if end > width: end = width cur = width else: cur = prev + x_step * xsteps[idx] xx[start:end] = np.linspace(prev, cur, end - start) prev = cur y_step = height // num_steps yy = np.zeros(height, np.float32) prev = 0 for idx, y in enumerate(range(0, height, y_step)): start = y end = y + y_step if end > height: end = height cur = height else: cur = prev + y_step * ysteps[idx] yy[start:end] = np.linspace(prev, cur, end - start) prev = cur map_x, map_y = np.meshgrid(xx, yy) map_x = map_x.astype(np.float32) map_y = map_y.astype(np.float32) img = cv2.remap(img, map_x, map_y, interpolation=interpolation, borderMode=border_mode, borderValue=value) return img
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 the International Conference on Document Analysis and Recognition, 2003. 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.com/erniejunior/601cdf56d2b424757de5 .. [Simard2003] Simard, Steinkraus and Platt, "Best Practices for Convolutional Neural Networks applied to Visual Document Analysis", in Proc. of the International Conference on Document Analysis and Recognition, 2003. """ if random_state is None: random_state = np.random.RandomState(1234) height, width = image.shape[:2] # Random affine center_square = np.float32((height, width)) // 2 square_size = min((height, width)) // 3 alpha = float(alpha) sigma = float(sigma) alpha_affine = float(alpha_affine) pts1 = np.float32([center_square + square_size, [center_square[0] + square_size, center_square[1] - square_size], center_square - square_size]) pts2 = pts1 + random_state.uniform(-alpha_affine, alpha_affine, size=pts1.shape).astype(np.float32) matrix = cv2.getAffineTransform(pts1, pts2) image = cv2.warpAffine(image, matrix, (width, height), flags=interpolation, borderMode=border_mode, borderValue=value) if approximate: # Approximate computation smooth displacement map with a large enough kernel. # On large images (512+) this is approximately 2X times faster dx = (random_state.rand(height, width).astype(np.float32) * 2 - 1) cv2.GaussianBlur(dx, (17, 17), sigma, dst=dx) dx *= alpha dy = (random_state.rand(height, width).astype(np.float32) * 2 - 1) cv2.GaussianBlur(dy, (17, 17), sigma, dst=dy) dy *= alpha else: dx = np.float32(gaussian_filter((random_state.rand(height, width) * 2 - 1), sigma) * alpha) dy = np.float32(gaussian_filter((random_state.rand(height, width) * 2 - 1), sigma) * alpha) x, y = np.meshgrid(np.arange(width), np.arange(height)) mapx = np.float32(x + dx) mapy = np.float32(y + dy) return cv2.remap(image, mapx, mapy, interpolation, borderMode=border_mode)
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, rows, cols) elif d == -1: bbox = bbox_hflip(bbox, rows, cols) bbox = bbox_vflip(bbox, rows, cols) else: raise ValueError('Invalid d value {}. Valid values are -1, 0 and 1'.format(d)) return bbox
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_max = bbox x1, y1, x2, y2 = crop_coords cropped_bbox = [x_min - x1, y_min - y1, x_max - x1, y_max - y1] return normalize_bbox(cropped_bbox, crop_height, crop_width)
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 cols. """ if factor < 0 or factor > 3: raise ValueError('Parameter n must be in range [0;3]') x_min, y_min, x_max, y_max = bbox if factor == 1: bbox = [y_min, 1 - x_max, y_max, 1 - x_min] if factor == 2: bbox = [1 - x_max, 1 - y_max, 1 - x_min, 1 - y_min] if factor == 3: bbox = [1 - y_max, x_min, 1 - y_min, x_max] return bbox
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, y_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): interpolation method. return a tuple (x_min, y_min, x_max, y_max) """ scale = cols / float(rows) x = np.array([bbox[0], bbox[2], bbox[2], bbox[0]]) y = np.array([bbox[1], bbox[1], bbox[3], bbox[3]]) x = x - 0.5 y = y - 0.5 angle = np.deg2rad(angle) x_t = (np.cos(angle) * x * scale + np.sin(angle) * y) / scale y_t = (-np.sin(angle) * x * scale + np.cos(angle) * y) x_t = x_t + 0.5 y_t = y_t + 0.5 return [min(x_t), min(y_t), max(x_t), max(y_t)]
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_max = bbox if axis != 0 and axis != 1: raise ValueError('Axis must be either 0 or 1.') if axis == 0: bbox = [y_min, x_min, y_max, x_max] if axis == 1: bbox = [1 - y_max, 1 - x_max, 1 - y_min, 1 - x_min] return bbox