repo stringclasses 85
values | path stringlengths 8 121 | func_name stringlengths 1 82 | original_string stringlengths 112 65.5k | language stringclasses 1
value | code stringlengths 112 65.5k | code_tokens listlengths 20 4.09k | docstring stringlengths 3 46.3k | docstring_tokens listlengths 1 564 | sha stringclasses 85
values | url stringlengths 93 218 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
Rapptz/discord.py | discord/shard.py | AutoShardedClient.latency | 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... | python | 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... | [
"def",
"latency",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"shards",
":",
"return",
"float",
"(",
"'nan'",
")",
"return",
"sum",
"(",
"latency",
"for",
"_",
",",
"latency",
"in",
"self",
".",
"latencies",
")",
"/",
"len",
"(",
"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... | [
":",
"class",
":",
"float",
":",
"Measures",
"latency",
"between",
"a",
"HEARTBEAT",
"and",
"a",
"HEARTBEAT_ACK",
"in",
"seconds",
"."
] | 05d4f7f9620ef33635d6ac965b26528e09cdaf5b | https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/shard.py#L163-L172 | train |
Rapptz/discord.py | discord/shard.py | AutoShardedClient.latencies | def latencies(self):
"""List[Tuple[:class:`int`, :class:`float`]]: A list of latencies between a HEARTBEAT and a HEARTBEAT_ACK in seconds.
This returns a list of tuples with elements ``(shard_id, latency)``.
"""
return [(shard_id, shard.ws.latency) for shard_id, shard in self.shards.ite... | python | def latencies(self):
"""List[Tuple[:class:`int`, :class:`float`]]: A list of latencies between a HEARTBEAT and a HEARTBEAT_ACK in seconds.
This returns a list of tuples with elements ``(shard_id, latency)``.
"""
return [(shard_id, shard.ws.latency) for shard_id, shard in self.shards.ite... | [
"def",
"latencies",
"(",
"self",
")",
":",
"return",
"[",
"(",
"shard_id",
",",
"shard",
".",
"ws",
".",
"latency",
")",
"for",
"shard_id",
",",
"shard",
"in",
"self",
".",
"shards",
".",
"items",
"(",
")",
"]"
] | 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)``. | [
"List",
"[",
"Tuple",
"[",
":",
"class",
":",
"int",
":",
"class",
":",
"float",
"]]",
":",
"A",
"list",
"of",
"latencies",
"between",
"a",
"HEARTBEAT",
"and",
"a",
"HEARTBEAT_ACK",
"in",
"seconds",
"."
] | 05d4f7f9620ef33635d6ac965b26528e09cdaf5b | https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/shard.py#L175-L180 | train |
Rapptz/discord.py | discord/shard.py | AutoShardedClient.request_offline_members | async def request_offline_members(self, *guilds):
r"""|coro|
Requests previously offline members from the guild to be filled up
into the :attr:`Guild.members` cache. This function is usually not
called. It should only be used if you have the ``fetch_offline_members``
parameter s... | python | async def request_offline_members(self, *guilds):
r"""|coro|
Requests previously offline members from the guild to be filled up
into the :attr:`Guild.members` cache. This function is usually not
called. It should only be used if you have the ``fetch_offline_members``
parameter s... | [
"async",
"def",
"request_offline_members",
"(",
"self",
",",
"*",
"guilds",
")",
":",
"if",
"any",
"(",
"not",
"g",
".",
"large",
"or",
"g",
".",
"unavailable",
"for",
"g",
"in",
"guilds",
")",
":",
"raise",
"InvalidArgument",
"(",
"'An unavailable or non-... | r"""|coro|
Requests previously offline members from the guild to be filled up
into the :attr:`Guild.members` cache. This function is usually not
called. It should only be used if you have the ``fetch_offline_members``
parameter set to ``False``.
When the client logs on and conn... | [
"r",
"|coro|"
] | 05d4f7f9620ef33635d6ac965b26528e09cdaf5b | https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/shard.py#L182-L211 | train |
Rapptz/discord.py | discord/shard.py | AutoShardedClient.close | 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
... | python | 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
... | [
"async",
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_closed",
"(",
")",
":",
"return",
"self",
".",
"_closed",
"=",
"True",
"for",
"vc",
"in",
"self",
".",
"voice_clients",
":",
"try",
":",
"await",
"vc",
".",
"disconnect",
"(",
"... | |coro|
Closes the connection to discord. | [
"|coro|"
] | 05d4f7f9620ef33635d6ac965b26528e09cdaf5b | https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/shard.py#L275-L295 | train |
Rapptz/discord.py | discord/shard.py | AutoShardedClient.change_presence | 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 ... | python | 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 ... | [
"async",
"def",
"change_presence",
"(",
"self",
",",
"*",
",",
"activity",
"=",
"None",
",",
"status",
"=",
"None",
",",
"afk",
"=",
"False",
",",
"shard_id",
"=",
"None",
")",
":",
"if",
"status",
"is",
"None",
":",
"status",
"=",
"'online'",
"statu... | |coro|
Changes the client's presence.
The activity parameter is a :class:`Activity` object (not a string) that represents
the activity being done currently. This could also be the slimmed down versions,
:class:`Game` and :class:`Streaming`.
Example: ::
game = disc... | [
"|coro|"
] | 05d4f7f9620ef33635d6ac965b26528e09cdaf5b | https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/shard.py#L297-L359 | train |
Rapptz/discord.py | discord/role.py | Role.members | 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)] | python | 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)] | [
"def",
"members",
"(",
"self",
")",
":",
"all_members",
"=",
"self",
".",
"guild",
".",
"members",
"if",
"self",
".",
"is_default",
"(",
")",
":",
"return",
"all_members",
"role_id",
"=",
"self",
".",
"id",
"return",
"[",
"member",
"for",
"member",
"in... | Returns a :class:`list` of :class:`Member` with this role. | [
"Returns",
"a",
":",
"class",
":",
"list",
"of",
":",
"class",
":",
"Member",
"with",
"this",
"role",
"."
] | 05d4f7f9620ef33635d6ac965b26528e09cdaf5b | https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/role.py#L170-L177 | train |
Rapptz/discord.py | discord/role.py | Role.edit | 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 ch... | python | 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 ch... | [
"async",
"def",
"edit",
"(",
"self",
",",
"*",
",",
"reason",
"=",
"None",
",",
"*",
"*",
"fields",
")",
":",
"position",
"=",
"fields",
".",
"get",
"(",
"'position'",
")",
"if",
"position",
"is",
"not",
"None",
":",
"await",
"self",
".",
"_move",
... | |coro|
Edits the role.
You must have the :attr:`~Permissions.manage_roles` permission to
use this.
All fields are optional.
Parameters
-----------
name: :class:`str`
The new role name to change to.
permissions: :class:`Permissions`
... | [
"|coro|"
] | 05d4f7f9620ef33635d6ac965b26528e09cdaf5b | https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/role.py#L202-L260 | train |
Rapptz/discord.py | discord/role.py | Role.delete | 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 ... | python | 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 ... | [
"async",
"def",
"delete",
"(",
"self",
",",
"*",
",",
"reason",
"=",
"None",
")",
":",
"await",
"self",
".",
"_state",
".",
"http",
".",
"delete_role",
"(",
"self",
".",
"guild",
".",
"id",
",",
"self",
".",
"id",
",",
"reason",
"=",
"reason",
")... | |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
--------
... | [
"|coro|"
] | 05d4f7f9620ef33635d6ac965b26528e09cdaf5b | https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/role.py#L262-L283 | train |
huge-success/sanic | sanic/blueprints.py | Blueprint.group | 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(... | python | 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(... | [
"def",
"group",
"(",
"*",
"blueprints",
",",
"url_prefix",
"=",
"\"\"",
")",
":",
"def",
"chain",
"(",
"nested",
")",
":",
"\"\"\"itertools.chain() but leaves strings untouched\"\"\"",
"for",
"i",
"in",
"nested",
":",
"if",
"isinstance",
"(",
"i",
",",
"(",
... | 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 | [
"Create",
"a",
"list",
"of",
"blueprints",
"optionally",
"grouping",
"them",
"under",
"a",
"general",
"URL",
"prefix",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L68-L93 | train |
huge-success/sanic | sanic/blueprints.py | Blueprint.register | 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 bluepr... | python | 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 bluepr... | [
"def",
"register",
"(",
"self",
",",
"app",
",",
"options",
")",
":",
"url_prefix",
"=",
"options",
".",
"get",
"(",
"\"url_prefix\"",
",",
"self",
".",
"url_prefix",
")",
"# Routes",
"for",
"future",
"in",
"self",
".",
"routes",
":",
"# attach the bluepri... | 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 | [
"Register",
"the",
"blueprint",
"to",
"the",
"sanic",
"app",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L95-L164 | train |
huge-success/sanic | sanic/blueprints.py | Blueprint.route | 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 accessib... | python | 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 accessib... | [
"def",
"route",
"(",
"self",
",",
"uri",
",",
"methods",
"=",
"frozenset",
"(",
"{",
"\"GET\"",
"}",
")",
",",
"host",
"=",
"None",
",",
"strict_slashes",
"=",
"None",
",",
"stream",
"=",
"False",
",",
"version",
"=",
"None",
",",
"name",
"=",
"Non... | Create a blueprint route from a decorated function.
:param uri: endpoint at which the route will be accessible.
:param methods: list of acceptable HTTP methods.
:param host: IP Address of FQDN for the sanic server to use.
:param strict_slashes: Enforce the API urls are requested with a
... | [
"Create",
"a",
"blueprint",
"route",
"from",
"a",
"decorated",
"function",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L166-L207 | train |
huge-success/sanic | sanic/blueprints.py | Blueprint.websocket | def websocket(
self, uri, host=None, strict_slashes=None, version=None, name=None
):
"""Create a blueprint websocket route from a decorated function.
:param uri: endpoint at which the route will be accessible.
:param host: IP Address of FQDN for the sanic server to use.
:par... | python | def websocket(
self, uri, host=None, strict_slashes=None, version=None, name=None
):
"""Create a blueprint websocket route from a decorated function.
:param uri: endpoint at which the route will be accessible.
:param host: IP Address of FQDN for the sanic server to use.
:par... | [
"def",
"websocket",
"(",
"self",
",",
"uri",
",",
"host",
"=",
"None",
",",
"strict_slashes",
"=",
"None",
",",
"version",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"strict_slashes",
"is",
"None",
":",
"strict_slashes",
"=",
"self",
".",
... | Create a blueprint websocket route from a decorated function.
:param uri: endpoint at which the route will be accessible.
:param host: IP Address of FQDN for the sanic server to use.
:param strict_slashes: Enforce the API urls are requested with a
training */*
:param version... | [
"Create",
"a",
"blueprint",
"websocket",
"route",
"from",
"a",
"decorated",
"function",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L260-L282 | train |
huge-success/sanic | sanic/blueprints.py | Blueprint.add_websocket_route | 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 ... | python | 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 ... | [
"def",
"add_websocket_route",
"(",
"self",
",",
"handler",
",",
"uri",
",",
"host",
"=",
"None",
",",
"version",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"self",
".",
"websocket",
"(",
"uri",
"=",
"uri",
",",
"host",
"=",
"host",
",",
"vers... | Create a blueprint websocket route from a function.
:param handler: function for handling uri requests. Accepts function,
or class instance with a view_class method.
:param uri: endpoint at which the route will be accessible.
:param host: IP Address of FQDN for the sanic... | [
"Create",
"a",
"blueprint",
"websocket",
"route",
"from",
"a",
"function",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L284-L298 | train |
huge-success/sanic | sanic/blueprints.py | Blueprint.listener | 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 | python | 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 | [
"def",
"listener",
"(",
"self",
",",
"event",
")",
":",
"def",
"decorator",
"(",
"listener",
")",
":",
"self",
".",
"listeners",
"[",
"event",
"]",
".",
"append",
"(",
"listener",
")",
"return",
"listener",
"return",
"decorator"
] | Create a listener from a decorated function.
:param event: Event to listen to. | [
"Create",
"a",
"listener",
"from",
"a",
"decorated",
"function",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L300-L310 | train |
huge-success/sanic | sanic/blueprints.py | Blueprint.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.
"""
... | python | 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",
"middleware",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"register_middleware",
"(",
"_middleware",
")",
":",
"future_middleware",
"=",
"FutureMiddleware",
"(",
"_middleware",
",",
"args",
",",
"kwargs",
")",
"self",
".... | 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. | [
"Create",
"a",
"blueprint",
"middleware",
"from",
"a",
"decorated",
"function",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L312-L339 | train |
huge-success/sanic | sanic/blueprints.py | Blueprint.exception | 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... | python | 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... | [
"def",
"exception",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"handler",
")",
":",
"exception",
"=",
"FutureException",
"(",
"handler",
",",
"args",
",",
"kwargs",
")",
"self",
".",
"exceptions",
".",
... | This method enables the process of creating a global exception
handler for the current blueprint under question.
:param args: List of Python exceptions to be caught by the handler
:param kwargs: Additional optional arguments to be passed to the
exception handler
:return a d... | [
"This",
"method",
"enables",
"the",
"process",
"of",
"creating",
"a",
"global",
"exception",
"handler",
"for",
"the",
"current",
"blueprint",
"under",
"question",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L341-L359 | train |
huge-success/sanic | sanic/blueprints.py | Blueprint.static | 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 nam... | python | 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 nam... | [
"def",
"static",
"(",
"self",
",",
"uri",
",",
"file_or_directory",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"kwargs",
".",
"pop",
"(",
"\"name\"",
",",
"\"static\"",
")",
"if",
"not",
"name",
".",
"startswith",
"(",
"self",
... | 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. | [
"Create",
"a",
"blueprint",
"static",
"route",
"from",
"a",
"decorated",
"function",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L361-L377 | train |
huge-success/sanic | sanic/blueprints.py | Blueprint.get | def get(
self, uri, host=None, strict_slashes=None, version=None, name=None
):
"""
Add an API URL under the **GET** *HTTP* method
:param uri: URL to be tagged to **GET** method of *HTTP*
:param host: Host IP or FQDN for the service to use
:param strict_slashes: Instr... | python | def get(
self, uri, host=None, strict_slashes=None, version=None, name=None
):
"""
Add an API URL under the **GET** *HTTP* method
:param uri: URL to be tagged to **GET** method of *HTTP*
:param host: Host IP or FQDN for the service to use
:param strict_slashes: Instr... | [
"def",
"get",
"(",
"self",
",",
"uri",
",",
"host",
"=",
"None",
",",
"strict_slashes",
"=",
"None",
",",
"version",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"return",
"self",
".",
"route",
"(",
"uri",
",",
"methods",
"=",
"frozenset",
"(",... | Add an API URL under the **GET** *HTTP* method
:param uri: URL to be tagged to **GET** method of *HTTP*
:param host: Host IP or FQDN for the service to use
:param strict_slashes: Instruct :class:`sanic.app.Sanic` to check
if the request URLs need to terminate with a */*
:par... | [
"Add",
"an",
"API",
"URL",
"under",
"the",
"**",
"GET",
"**",
"*",
"HTTP",
"*",
"method"
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L380-L401 | train |
huge-success/sanic | sanic/exceptions.py | add_status_code | 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 | python | 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 | [
"def",
"add_status_code",
"(",
"code",
")",
":",
"def",
"class_decorator",
"(",
"cls",
")",
":",
"cls",
".",
"status_code",
"=",
"code",
"_sanic_exceptions",
"[",
"code",
"]",
"=",
"cls",
"return",
"cls",
"return",
"class_decorator"
] | Decorator used for adding exceptions to :class:`SanicException`. | [
"Decorator",
"used",
"for",
"adding",
"exceptions",
"to",
":",
"class",
":",
"SanicException",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/exceptions.py#L124-L134 | train |
huge-success/sanic | sanic/exceptions.py | abort | 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
... | python | 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
... | [
"def",
"abort",
"(",
"status_code",
",",
"message",
"=",
"None",
")",
":",
"if",
"message",
"is",
"None",
":",
"message",
"=",
"STATUS_CODES",
".",
"get",
"(",
"status_code",
")",
"# These are stored as bytes in the STATUS_CODES dict",
"message",
"=",
"message",
... | 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 ... | [
"Raise",
"an",
"exception",
"based",
"on",
"SanicException",
".",
"Returns",
"the",
"HTTP",
"response",
"message",
"appropriate",
"for",
"the",
"given",
"status",
"code",
"unless",
"provided",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/exceptions.py#L284-L298 | train |
huge-success/sanic | sanic/app.py | Sanic.add_task | 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 awaita... | python | 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 awaita... | [
"def",
"add_task",
"(",
"self",
",",
"task",
")",
":",
"try",
":",
"if",
"callable",
"(",
"task",
")",
":",
"try",
":",
"self",
".",
"loop",
".",
"create_task",
"(",
"task",
"(",
"self",
")",
")",
"except",
"TypeError",
":",
"self",
".",
"loop",
... | 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 | [
"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",
... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L94-L120 | train |
huge-success/sanic | sanic/app.py | Sanic.route | 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 ... | python | 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 ... | [
"def",
"route",
"(",
"self",
",",
"uri",
",",
"methods",
"=",
"frozenset",
"(",
"{",
"\"GET\"",
"}",
")",
",",
"host",
"=",
"None",
",",
"strict_slashes",
"=",
"None",
",",
"stream",
"=",
"False",
",",
"version",
"=",
"None",
",",
"name",
"=",
"Non... | Decorate a function to be registered as a route
:param uri: path of the URL
:param methods: list or tuple of methods allowed
:param host:
:param strict_slashes:
:param stream:
:param version:
:param name: user defined route name for url_for
:return: decor... | [
"Decorate",
"a",
"function",
"to",
"be",
"registered",
"as",
"a",
"route"
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L149-L205 | train |
huge-success/sanic | sanic/app.py | Sanic.websocket | 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:
:retur... | python | 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:
:retur... | [
"def",
"websocket",
"(",
"self",
",",
"uri",
",",
"host",
"=",
"None",
",",
"strict_slashes",
"=",
"None",
",",
"subprotocols",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"self",
".",
"enable_websocket",
"(",
")",
"# Fix case where the user did not pre... | 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 | [
"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",
":",
"par... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L439-L499 | train |
huge-success/sanic | sanic/app.py | Sanic.add_websocket_route | 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
... | python | 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
... | [
"def",
"add_websocket_route",
"(",
"self",
",",
"handler",
",",
"uri",
",",
"host",
"=",
"None",
",",
"strict_slashes",
"=",
"None",
",",
"subprotocols",
"=",
"None",
",",
"name",
"=",
"None",
",",
")",
":",
"if",
"strict_slashes",
"is",
"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
... | [
"A",
"helper",
"method",
"to",
"register",
"a",
"function",
"as",
"a",
"websocket",
"route",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L501-L535 | train |
huge-success/sanic | sanic/app.py | Sanic.enable_websocket | 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
... | python | 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
... | [
"def",
"enable_websocket",
"(",
"self",
",",
"enable",
"=",
"True",
")",
":",
"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",
".",
"liste... | Enable or disable the support for websocket.
Websocket is enabled automatically if websocket routes are
added to the application. | [
"Enable",
"or",
"disable",
"the",
"support",
"for",
"websocket",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L537-L551 | train |
huge-success/sanic | sanic/app.py | Sanic.remove_route | def remove_route(self, uri, clean_cache=True, host=None):
"""
This method provides the app user a mechanism by which an already
existing route can be removed from the :class:`Sanic` object
:param uri: URL Path to be removed from the app
:param clean_cache: Instruct sanic if it n... | python | def remove_route(self, uri, clean_cache=True, host=None):
"""
This method provides the app user a mechanism by which an already
existing route can be removed from the :class:`Sanic` object
:param uri: URL Path to be removed from the app
:param clean_cache: Instruct sanic if it n... | [
"def",
"remove_route",
"(",
"self",
",",
"uri",
",",
"clean_cache",
"=",
"True",
",",
"host",
"=",
"None",
")",
":",
"self",
".",
"router",
".",
"remove",
"(",
"uri",
",",
"clean_cache",
",",
"host",
")"
] | This method provides the app user a mechanism by which an already
existing route can be removed from the :class:`Sanic` object
:param uri: URL Path to be removed from the app
:param clean_cache: Instruct sanic if it needs to clean up the LRU
route cache
:param host: IP addre... | [
"This",
"method",
"provides",
"the",
"app",
"user",
"a",
"mechanism",
"by",
"which",
"an",
"already",
"existing",
"route",
"can",
"be",
"removed",
"from",
"the",
":",
"class",
":",
"Sanic",
"object"
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L553-L564 | train |
huge-success/sanic | sanic/app.py | Sanic.exception | 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, l... | python | 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, l... | [
"def",
"exception",
"(",
"self",
",",
"*",
"exceptions",
")",
":",
"def",
"response",
"(",
"handler",
")",
":",
"for",
"exception",
"in",
"exceptions",
":",
"if",
"isinstance",
"(",
"exception",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"for",
"... | Decorate a function to be registered as a handler for exceptions
:param exceptions: exceptions
:return: decorated function | [
"Decorate",
"a",
"function",
"to",
"be",
"registered",
"as",
"a",
"handler",
"for",
"exceptions"
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L567-L583 | train |
huge-success/sanic | sanic/app.py | Sanic.register_middleware | def register_middleware(self, middleware, attach_to="request"):
"""
Register an application level middleware that will be attached
to all the API URLs registered under this application.
This method is internally invoked by the :func:`middleware`
decorator provided at the app lev... | python | def register_middleware(self, middleware, attach_to="request"):
"""
Register an application level middleware that will be attached
to all the API URLs registered under this application.
This method is internally invoked by the :func:`middleware`
decorator provided at the app lev... | [
"def",
"register_middleware",
"(",
"self",
",",
"middleware",
",",
"attach_to",
"=",
"\"request\"",
")",
":",
"if",
"attach_to",
"==",
"\"request\"",
":",
"if",
"middleware",
"not",
"in",
"self",
".",
"request_middleware",
":",
"self",
".",
"request_middleware",... | Register an application level middleware that will be attached
to all the API URLs registered under this application.
This method is internally invoked by the :func:`middleware`
decorator provided at the app level.
:param middleware: Callback method to be attached to the
mi... | [
"Register",
"an",
"application",
"level",
"middleware",
"that",
"will",
"be",
"attached",
"to",
"all",
"the",
"API",
"URLs",
"registered",
"under",
"this",
"application",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L585-L607 | train |
huge-success/sanic | sanic/app.py | Sanic.middleware | def middleware(self, middleware_or_request):
"""
Decorate and register middleware to be called before a request.
Can either be called as *@app.middleware* or
*@app.middleware('request')*
:param: middleware_or_request: Optional parameter to use for
identifying which t... | python | def middleware(self, middleware_or_request):
"""
Decorate and register middleware to be called before a request.
Can either be called as *@app.middleware* or
*@app.middleware('request')*
:param: middleware_or_request: Optional parameter to use for
identifying which t... | [
"def",
"middleware",
"(",
"self",
",",
"middleware_or_request",
")",
":",
"# Detect which way this was called, @middleware or @middleware('AT')",
"if",
"callable",
"(",
"middleware_or_request",
")",
":",
"return",
"self",
".",
"register_middleware",
"(",
"middleware_or_reques... | 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. | [
"Decorate",
"and",
"register",
"middleware",
"to",
"be",
"called",
"before",
"a",
"request",
".",
"Can",
"either",
"be",
"called",
"as",
"*",
"@app",
".",
"middleware",
"*",
"or",
"*",
"@app",
".",
"middleware",
"(",
"request",
")",
"*"
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L610-L626 | train |
huge-success/sanic | sanic/app.py | Sanic.static | def static(
self,
uri,
file_or_directory,
pattern=r"/?.+",
use_modified_since=True,
use_content_range=False,
stream_large_files=False,
name="static",
host=None,
strict_slashes=None,
content_type=None,
):
"""
Regi... | python | def static(
self,
uri,
file_or_directory,
pattern=r"/?.+",
use_modified_since=True,
use_content_range=False,
stream_large_files=False,
name="static",
host=None,
strict_slashes=None,
content_type=None,
):
"""
Regi... | [
"def",
"static",
"(",
"self",
",",
"uri",
",",
"file_or_directory",
",",
"pattern",
"=",
"r\"/?.+\"",
",",
"use_modified_since",
"=",
"True",
",",
"use_content_range",
"=",
"False",
",",
"stream_large_files",
"=",
"False",
",",
"name",
"=",
"\"static\"",
",",
... | Register a root to serve files from. The input can either be a
file or a directory. This method will enable an easy and simple way
to setup the :class:`Route` necessary to serve the static files.
:param uri: URL path to be used for serving static content
:param file_or_directory: Path f... | [
"Register",
"a",
"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",... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L629-L679 | train |
huge-success/sanic | sanic/app.py | Sanic.blueprint | 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, Bluepr... | python | 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, Bluepr... | [
"def",
"blueprint",
"(",
"self",
",",
"blueprint",
",",
"*",
"*",
"options",
")",
":",
"if",
"isinstance",
"(",
"blueprint",
",",
"(",
"list",
",",
"tuple",
",",
"BlueprintGroup",
")",
")",
":",
"for",
"item",
"in",
"blueprint",
":",
"self",
".",
"bl... | Register a blueprint on the application.
:param blueprint: Blueprint object or (list, tuple) thereof
:param options: option dictionary with blueprint defaults
:return: Nothing | [
"Register",
"a",
"blueprint",
"on",
"the",
"application",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L681-L700 | train |
huge-success/sanic | sanic/app.py | Sanic.register_blueprint | def register_blueprint(self, *args, **kwargs):
"""
Proxy method provided for invoking the :func:`blueprint` method
.. note::
To be deprecated in 1.0. Use :func:`blueprint` instead.
:param args: Blueprint object or (list, tuple) thereof
:param kwargs: option dictiona... | python | def register_blueprint(self, *args, **kwargs):
"""
Proxy method provided for invoking the :func:`blueprint` method
.. note::
To be deprecated in 1.0. Use :func:`blueprint` instead.
:param args: Blueprint object or (list, tuple) thereof
:param kwargs: option dictiona... | [
"def",
"register_blueprint",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"debug",
":",
"warnings",
".",
"simplefilter",
"(",
"\"default\"",
")",
"warnings",
".",
"warn",
"(",
"\"Use of register_blueprint will be depreca... | 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 | [
"Proxy",
"method",
"provided",
"for",
"invoking",
"the",
":",
"func",
":",
"blueprint",
"method"
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L702-L722 | train |
huge-success/sanic | sanic/app.py | Sanic.handle_request | 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
... | python | 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
... | [
"async",
"def",
"handle_request",
"(",
"self",
",",
"request",
",",
"write_callback",
",",
"stream_callback",
")",
":",
"# Define `response` var here to remove warnings about",
"# allocation before assignment below.",
"response",
"=",
"None",
"cancelled",
"=",
"False",
"try... | 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... | [
"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",
"he... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L863-L975 | train |
huge-success/sanic | sanic/app.py | Sanic.run | 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,
sto... | python | 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,
sto... | [
"def",
"run",
"(",
"self",
",",
"host",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"port",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"debug",
":",
"bool",
"=",
"False",
",",
"ssl",
":",
"Union",
"[",
"dict",
",",
"SSLContext",
... | 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)
... | [
"Run",
"the",
"HTTP",
"Server",
"and",
"listen",
"until",
"keyboard",
"interrupt",
"or",
"term",
"signal",
".",
"On",
"termination",
"drain",
"connections",
"before",
"closing",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L989-L1105 | train |
huge-success/sanic | sanic/app.py | Sanic.create_server | async def create_server(
self,
host: Optional[str] = None,
port: Optional[int] = None,
debug: bool = False,
ssl: Union[dict, SSLContext, None] = None,
sock: Optional[socket] = None,
protocol: Type[Protocol] = None,
backlog: int = 100,
stop_event: A... | python | async def create_server(
self,
host: Optional[str] = None,
port: Optional[int] = None,
debug: bool = False,
ssl: Union[dict, SSLContext, None] = None,
sock: Optional[socket] = None,
protocol: Type[Protocol] = None,
backlog: int = 100,
stop_event: A... | [
"async",
"def",
"create_server",
"(",
"self",
",",
"host",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"port",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"debug",
":",
"bool",
"=",
"False",
",",
"ssl",
":",
"Union",
"[",
"dict",
... | 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... | [
"Asynchronous",
"version",
"of",
":",
"func",
":",
"run",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L1115-L1209 | train |
huge-success/sanic | sanic/app.py | Sanic._helper | def _helper(
self,
host=None,
port=None,
debug=False,
ssl=None,
sock=None,
workers=1,
loop=None,
protocol=HttpProtocol,
backlog=100,
stop_event=None,
register_sys_signals=True,
run_async=False,
auto_reload=Fa... | python | def _helper(
self,
host=None,
port=None,
debug=False,
ssl=None,
sock=None,
workers=1,
loop=None,
protocol=HttpProtocol,
backlog=100,
stop_event=None,
register_sys_signals=True,
run_async=False,
auto_reload=Fa... | [
"def",
"_helper",
"(",
"self",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"debug",
"=",
"False",
",",
"ssl",
"=",
"None",
",",
"sock",
"=",
"None",
",",
"workers",
"=",
"1",
",",
"loop",
"=",
"None",
",",
"protocol",
"=",
"HttpProto... | Helper function used by `run` and `create_server`. | [
"Helper",
"function",
"used",
"by",
"run",
"and",
"create_server",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/app.py#L1243-L1351 | train |
huge-success/sanic | sanic/response.py | json | 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.
:para... | python | 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.
:para... | [
"def",
"json",
"(",
"body",
",",
"status",
"=",
"200",
",",
"headers",
"=",
"None",
",",
"content_type",
"=",
"\"application/json\"",
",",
"dumps",
"=",
"json_dumps",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"HTTPResponse",
"(",
"dumps",
"(",
"body",... | 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. | [
"Returns",
"response",
"object",
"with",
"body",
"in",
"json",
"format",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/response.py#L203-L224 | train |
huge-success/sanic | sanic/response.py | text | 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) ... | python | 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) ... | [
"def",
"text",
"(",
"body",
",",
"status",
"=",
"200",
",",
"headers",
"=",
"None",
",",
"content_type",
"=",
"\"text/plain; charset=utf-8\"",
")",
":",
"return",
"HTTPResponse",
"(",
"body",
",",
"status",
"=",
"status",
",",
"headers",
"=",
"headers",
",... | 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 | [
"Returns",
"response",
"object",
"with",
"body",
"in",
"text",
"format",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/response.py#L227-L240 | train |
huge-success/sanic | sanic/response.py | file_stream | 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 (... | python | 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 (... | [
"async",
"def",
"file_stream",
"(",
"location",
",",
"status",
"=",
"200",
",",
"chunk_size",
"=",
"4096",
",",
"mime_type",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"_range",
"=",
"None",
",",
")",
":",
"headers",
... | 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: | [
"Return",
"a",
"streaming",
"response",
"object",
"with",
"file",
"data",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/response.py#L323-L386 | train |
huge-success/sanic | sanic/response.py | stream | def stream(
streaming_fn,
status=200,
headers=None,
content_type="text/plain; charset=utf-8",
):
"""Accepts an coroutine `streaming_fn` which can be used to
write chunks to a streaming response. Returns a `StreamingHTTPResponse`.
Example usage::
@app.route("/")
async def in... | python | def stream(
streaming_fn,
status=200,
headers=None,
content_type="text/plain; charset=utf-8",
):
"""Accepts an coroutine `streaming_fn` which can be used to
write chunks to a streaming response. Returns a `StreamingHTTPResponse`.
Example usage::
@app.route("/")
async def in... | [
"def",
"stream",
"(",
"streaming_fn",
",",
"status",
"=",
"200",
",",
"headers",
"=",
"None",
",",
"content_type",
"=",
"\"text/plain; charset=utf-8\"",
",",
")",
":",
"return",
"StreamingHTTPResponse",
"(",
"streaming_fn",
",",
"headers",
"=",
"headers",
",",
... | 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')
... | [
"Accepts",
"an",
"coroutine",
"streaming_fn",
"which",
"can",
"be",
"used",
"to",
"write",
"chunks",
"to",
"a",
"streaming",
"response",
".",
"Returns",
"a",
"StreamingHTTPResponse",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/response.py#L389-L415 | train |
huge-success/sanic | sanic/response.py | redirect | 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 (i... | python | 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 (i... | [
"def",
"redirect",
"(",
"to",
",",
"headers",
"=",
"None",
",",
"status",
"=",
"302",
",",
"content_type",
"=",
"\"text/html; charset=utf-8\"",
")",
":",
"headers",
"=",
"headers",
"or",
"{",
"}",
"# URL Quote the URL before redirecting",
"safe_to",
"=",
"quote_... | 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 ... | [
"Abort",
"execution",
"and",
"cause",
"a",
"302",
"redirect",
"(",
"by",
"default",
")",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/response.py#L418-L439 | train |
huge-success/sanic | sanic/response.py | StreamingHTTPResponse.write | async def write(self, data):
"""Writes a chunk of data to the streaming response.
:param data: bytes-ish data to be written.
"""
if type(data) != bytes:
data = self._encode_body(data)
self.protocol.push_data(b"%x\r\n%b\r\n" % (len(data), data))
await self.pr... | python | async def write(self, data):
"""Writes a chunk of data to the streaming response.
:param data: bytes-ish data to be written.
"""
if type(data) != bytes:
data = self._encode_body(data)
self.protocol.push_data(b"%x\r\n%b\r\n" % (len(data), data))
await self.pr... | [
"async",
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"if",
"type",
"(",
"data",
")",
"!=",
"bytes",
":",
"data",
"=",
"self",
".",
"_encode_body",
"(",
"data",
")",
"self",
".",
"protocol",
".",
"push_data",
"(",
"b\"%x\\r\\n%b\\r\\n\"",
"%",
... | Writes a chunk of data to the streaming response.
:param data: bytes-ish data to be written. | [
"Writes",
"a",
"chunk",
"of",
"data",
"to",
"the",
"streaming",
"response",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/response.py#L74-L83 | train |
huge-success/sanic | sanic/response.py | StreamingHTTPResponse.stream | 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,
... | python | 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,
... | [
"async",
"def",
"stream",
"(",
"self",
",",
"version",
"=",
"\"1.1\"",
",",
"keep_alive",
"=",
"False",
",",
"keep_alive_timeout",
"=",
"None",
")",
":",
"headers",
"=",
"self",
".",
"get_headers",
"(",
"version",
",",
"keep_alive",
"=",
"keep_alive",
",",... | Streams headers, runs the `streaming_fn` callback that writes
content to the response body, then finalizes the response body. | [
"Streams",
"headers",
"runs",
"the",
"streaming_fn",
"callback",
"that",
"writes",
"content",
"to",
"the",
"response",
"body",
"then",
"finalizes",
"the",
"response",
"body",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/response.py#L85-L99 | train |
huge-success/sanic | sanic/blueprint_group.py | BlueprintGroup.insert | 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.
:... | python | 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.
:... | [
"def",
"insert",
"(",
"self",
",",
"index",
":",
"int",
",",
"item",
":",
"object",
")",
"->",
"None",
":",
"self",
".",
"_blueprints",
".",
"insert",
"(",
"index",
",",
"item",
")"
] | 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 | [
"The",
"Abstract",
"class",
"MutableSequence",
"leverages",
"this",
"insert",
"method",
"to",
"perform",
"the",
"BlueprintGroup",
".",
"append",
"operation",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprint_group.py#L91-L100 | train |
huge-success/sanic | sanic/blueprint_group.py | BlueprintGroup.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 recur... | python | def middleware(self, *args, **kwargs):
"""
A decorator that can be used to implement a Middleware plugin to
all of the Blueprints that belongs to this specific Blueprint Group.
In case of nested Blueprint Groups, the same middleware is applied
across each of the Blueprints recur... | [
"def",
"middleware",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"\"bp_group\"",
"]",
"=",
"True",
"def",
"register_middleware_for_blueprints",
"(",
"fn",
")",
":",
"for",
"blueprint",
"in",
"self",
".",
"blueprints",
... | A decorator that can be used to implement a Middleware plugin to
all of the Blueprints that belongs to this specific Blueprint Group.
In case of nested Blueprint Groups, the same middleware is applied
across each of the Blueprints recursively.
:param args: Optional positional Parameter... | [
"A",
"decorator",
"that",
"can",
"be",
"used",
"to",
"implement",
"a",
"Middleware",
"plugin",
"to",
"all",
"of",
"the",
"Blueprints",
"that",
"belongs",
"to",
"this",
"specific",
"Blueprint",
"Group",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprint_group.py#L102-L120 | train |
huge-success/sanic | sanic/handlers.py | ErrorHandler.response | def response(self, request, exception):
"""Fetches and executes an exception handler and returns a response
object
:param request: Instance of :class:`sanic.request.Request`
:param exception: Exception to handle
:type request: :class:`sanic.request.Request`
:type except... | python | def response(self, request, exception):
"""Fetches and executes an exception handler and returns a response
object
:param request: Instance of :class:`sanic.request.Request`
:param exception: Exception to handle
:type request: :class:`sanic.request.Request`
:type except... | [
"def",
"response",
"(",
"self",
",",
"request",
",",
"exception",
")",
":",
"handler",
"=",
"self",
".",
"lookup",
"(",
"exception",
")",
"response",
"=",
"None",
"try",
":",
"if",
"handler",
":",
"response",
"=",
"handler",
"(",
"request",
",",
"excep... | 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
... | [
"Fetches",
"and",
"executes",
"an",
"exception",
"handler",
"and",
"returns",
"a",
"response",
"object"
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/handlers.py#L111-L147 | train |
huge-success/sanic | sanic/handlers.py | ErrorHandler.default | def default(self, request, exception):
"""
Provide a default behavior for the objects of :class:`ErrorHandler`.
If a developer chooses to extent the :class:`ErrorHandler` they can
provide a custom implementation for this method to behave in a way
they see fit.
:param req... | python | def default(self, request, exception):
"""
Provide a default behavior for the objects of :class:`ErrorHandler`.
If a developer chooses to extent the :class:`ErrorHandler` they can
provide a custom implementation for this method to behave in a way
they see fit.
:param req... | [
"def",
"default",
"(",
"self",
",",
"request",
",",
"exception",
")",
":",
"self",
".",
"log",
"(",
"format_exc",
"(",
")",
")",
"try",
":",
"url",
"=",
"repr",
"(",
"request",
".",
"url",
")",
"except",
"AttributeError",
":",
"url",
"=",
"\"unknown\... | 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 ... | [
"Provide",
"a",
"default",
"behavior",
"for",
"the",
"objects",
"of",
":",
"class",
":",
"ErrorHandler",
".",
"If",
"a",
"developer",
"chooses",
"to",
"extent",
"the",
":",
"class",
":",
"ErrorHandler",
"they",
"can",
"provide",
"a",
"custom",
"implementatio... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/handlers.py#L154-L189 | train |
huge-success/sanic | sanic/worker.py | GunicornWorker._create_ssl_context | 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
... | python | 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
... | [
"def",
"_create_ssl_context",
"(",
"cfg",
")",
":",
"ctx",
"=",
"ssl",
".",
"SSLContext",
"(",
"cfg",
".",
"ssl_version",
")",
"ctx",
".",
"load_cert_chain",
"(",
"cfg",
".",
"certfile",
",",
"cfg",
".",
"keyfile",
")",
"ctx",
".",
"verify_mode",
"=",
... | Creates SSLContext instance for usage in asyncio.create_server.
See ssl.SSLSocket.__init__ for more details. | [
"Creates",
"SSLContext",
"instance",
"for",
"usage",
"in",
"asyncio",
".",
"create_server",
".",
"See",
"ssl",
".",
"SSLSocket",
".",
"__init__",
"for",
"more",
"details",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/worker.py#L176-L187 | train |
huge-success/sanic | sanic/server.py | trigger_events | 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) | python | 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) | [
"def",
"trigger_events",
"(",
"events",
",",
"loop",
")",
":",
"for",
"event",
"in",
"events",
":",
"result",
"=",
"event",
"(",
"loop",
")",
"if",
"isawaitable",
"(",
"result",
")",
":",
"loop",
".",
"run_until_complete",
"(",
"result",
")"
] | Trigger event callbacks (functions or async)
:param events: one or more sync or async functions to execute
:param loop: event loop | [
"Trigger",
"event",
"callbacks",
"(",
"functions",
"or",
"async",
")"
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L604-L613 | train |
huge-success/sanic | sanic/server.py | serve | def serve(
host,
port,
app,
request_handler,
error_handler,
before_start=None,
after_start=None,
before_stop=None,
after_stop=None,
debug=False,
request_timeout=60,
response_timeout=60,
keep_alive_timeout=5,
ssl=None,
sock=None,
request_max_size=None,
... | python | 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,
... | [
"def",
"serve",
"(",
"host",
",",
"port",
",",
"app",
",",
"request_handler",
",",
"error_handler",
",",
"before_start",
"=",
"None",
",",
"after_start",
"=",
"None",
",",
"before_stop",
"=",
"None",
",",
"after_stop",
"=",
"None",
",",
"debug",
"=",
"Fa... | Start asynchronous HTTP Server on an individual process.
:param host: Address to host on
:param port: Port to host on
:param request_handler: Sanic request handler with middleware
:param error_handler: Sanic error handler with middleware
:param before_start: function to be executed before the serve... | [
"Start",
"asynchronous",
"HTTP",
"Server",
"on",
"an",
"individual",
"process",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L616-L820 | train |
huge-success/sanic | sanic/server.py | HttpProtocol.keep_alive | 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
... | python | 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
... | [
"def",
"keep_alive",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"_keep_alive",
"and",
"not",
"self",
".",
"signal",
".",
"stopped",
"and",
"self",
".",
"parser",
".",
"should_keep_alive",
"(",
")",
")"
] | Check if the connection needs to be kept alive based on the params
attached to the `_keep_alive` attribute, :attr:`Signal.stopped`
and :func:`HttpProtocol.parser.should_keep_alive`
:return: ``True`` if connection is to be kept alive ``False`` else | [
"Check",
"if",
"the",
"connection",
"needs",
"to",
"be",
"kept",
"alive",
"based",
"on",
"the",
"params",
"attached",
"to",
"the",
"_keep_alive",
"attribute",
":",
"attr",
":",
"Signal",
".",
"stopped",
"and",
":",
"func",
":",
"HttpProtocol",
".",
"parser... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L151-L163 | train |
huge-success/sanic | sanic/server.py | HttpProtocol.keep_alive_timeout_callback | 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() ... | python | 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() ... | [
"def",
"keep_alive_timeout_callback",
"(",
"self",
")",
":",
"time_elapsed",
"=",
"time",
"(",
")",
"-",
"self",
".",
"_last_response_time",
"if",
"time_elapsed",
"<",
"self",
".",
"keep_alive_timeout",
":",
"time_left",
"=",
"self",
".",
"keep_alive_timeout",
"... | 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 | [
"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",
... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L230-L247 | train |
huge-success/sanic | sanic/server.py | HttpProtocol.execute_request_handler | 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
... | python | 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
... | [
"def",
"execute_request_handler",
"(",
"self",
")",
":",
"self",
".",
"_response_timeout_handler",
"=",
"self",
".",
"loop",
".",
"call_later",
"(",
"self",
".",
"response_timeout",
",",
"self",
".",
"response_timeout_callback",
")",
"self",
".",
"_last_request_ti... | Invoke the request handler defined by the
:func:`sanic.app.Sanic.handle_request` method
:return: None | [
"Invoke",
"the",
"request",
"handler",
"defined",
"by",
"the",
":",
"func",
":",
"sanic",
".",
"app",
".",
"Sanic",
".",
"handle_request",
"method"
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L357-L372 | train |
huge-success/sanic | sanic/server.py | HttpProtocol.log_response | 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
... | python | 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
... | [
"def",
"log_response",
"(",
"self",
",",
"response",
")",
":",
"if",
"self",
".",
"access_log",
":",
"extra",
"=",
"{",
"\"status\"",
":",
"getattr",
"(",
"response",
",",
"\"status\"",
",",
"0",
")",
"}",
"if",
"isinstance",
"(",
"response",
",",
"HTT... | 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`
... | [
"Helper",
"method",
"provided",
"to",
"enable",
"the",
"logging",
"of",
"responses",
"in",
"case",
"if",
"the",
":",
"attr",
":",
"HttpProtocol",
".",
"access_log",
"is",
"enabled",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L377-L410 | train |
huge-success/sanic | sanic/server.py | HttpProtocol.write_response | def write_response(self, response):
"""
Writes response content synchronously to the transport.
"""
if self._response_timeout_handler:
self._response_timeout_handler.cancel()
self._response_timeout_handler = None
try:
keep_alive = self.keep_ali... | python | def write_response(self, response):
"""
Writes response content synchronously to the transport.
"""
if self._response_timeout_handler:
self._response_timeout_handler.cancel()
self._response_timeout_handler = None
try:
keep_alive = self.keep_ali... | [
"def",
"write_response",
"(",
"self",
",",
"response",
")",
":",
"if",
"self",
".",
"_response_timeout_handler",
":",
"self",
".",
"_response_timeout_handler",
".",
"cancel",
"(",
")",
"self",
".",
"_response_timeout_handler",
"=",
"None",
"try",
":",
"keep_aliv... | Writes response content synchronously to the transport. | [
"Writes",
"response",
"content",
"synchronously",
"to",
"the",
"transport",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L412-L455 | train |
huge-success/sanic | sanic/server.py | HttpProtocol.bail_out | 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: ... | python | 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: ... | [
"def",
"bail_out",
"(",
"self",
",",
"message",
",",
"from_error",
"=",
"False",
")",
":",
"if",
"from_error",
"or",
"self",
".",
"transport",
"is",
"None",
"or",
"self",
".",
"transport",
".",
"is_closing",
"(",
")",
":",
"logger",
".",
"error",
"(",
... | 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... | [
"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",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L542-L570 | train |
huge-success/sanic | sanic/server.py | HttpProtocol.cleanup | 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
... | python | 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
... | [
"def",
"cleanup",
"(",
"self",
")",
":",
"self",
".",
"parser",
"=",
"None",
"self",
".",
"request",
"=",
"None",
"self",
".",
"url",
"=",
"None",
"self",
".",
"headers",
"=",
"None",
"self",
".",
"_request_handler_task",
"=",
"None",
"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. | [
"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",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/server.py#L572-L583 | train |
huge-success/sanic | sanic/request.py | parse_multipart_form | 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(... | python | 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(... | [
"def",
"parse_multipart_form",
"(",
"body",
",",
"boundary",
")",
":",
"files",
"=",
"RequestParameters",
"(",
")",
"fields",
"=",
"RequestParameters",
"(",
")",
"form_parts",
"=",
"body",
".",
"split",
"(",
"boundary",
")",
"for",
"form_part",
"in",
"form_p... | Parse a request body and returns fields and files
:param body: bytes request body
:param boundary: bytes multipart boundary
:return: fields (RequestParameters), files (RequestParameters) | [
"Parse",
"a",
"request",
"body",
"and",
"returns",
"fields",
"and",
"files"
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/request.py#L445-L513 | train |
huge-success/sanic | sanic/request.py | StreamBuffer.read | async def read(self):
""" Stop reading when gets None """
payload = await self._queue.get()
self._queue.task_done()
return payload | python | async def read(self):
""" Stop reading when gets None """
payload = await self._queue.get()
self._queue.task_done()
return payload | [
"async",
"def",
"read",
"(",
"self",
")",
":",
"payload",
"=",
"await",
"self",
".",
"_queue",
".",
"get",
"(",
")",
"self",
".",
"_queue",
".",
"task_done",
"(",
")",
"return",
"payload"
] | Stop reading when gets None | [
"Stop",
"reading",
"when",
"gets",
"None"
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/request.py#L57-L61 | train |
huge-success/sanic | sanic/request.py | Request.token | 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... | python | 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... | [
"def",
"token",
"(",
"self",
")",
":",
"prefixes",
"=",
"(",
"\"Bearer\"",
",",
"\"Token\"",
")",
"auth_header",
"=",
"self",
".",
"headers",
".",
"get",
"(",
"\"Authorization\"",
")",
"if",
"auth_header",
"is",
"not",
"None",
":",
"for",
"prefix",
"in",... | Attempt to return the auth header token.
:return: token related to request | [
"Attempt",
"to",
"return",
"the",
"auth",
"header",
"token",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/request.py#L158-L171 | train |
huge-success/sanic | sanic/request.py | Request.get_args | 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... | python | 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... | [
"def",
"get_args",
"(",
"self",
",",
"keep_blank_values",
":",
"bool",
"=",
"False",
",",
"strict_parsing",
":",
"bool",
"=",
"False",
",",
"encoding",
":",
"str",
"=",
"\"utf-8\"",
",",
"errors",
":",
"str",
"=",
"\"replace\"",
",",
")",
"->",
"RequestP... | Method to parse `query_string` using `urllib.parse.parse_qs`.
This methods is used by `args` property.
Can be used directly if you need to change default parameters.
:param keep_blank_values: flag indicating whether blank values in
percent-encoded queries should be treated as blank s... | [
"Method",
"to",
"parse",
"query_string",
"using",
"urllib",
".",
"parse",
".",
"parse_qs",
".",
"This",
"methods",
"is",
"used",
"by",
"args",
"property",
".",
"Can",
"be",
"used",
"directly",
"if",
"you",
"need",
"to",
"change",
"default",
"parameters",
"... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/request.py#L205-L252 | train |
huge-success/sanic | sanic/request.py | Request.get_query_args | 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... | python | 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... | [
"def",
"get_query_args",
"(",
"self",
",",
"keep_blank_values",
":",
"bool",
"=",
"False",
",",
"strict_parsing",
":",
"bool",
"=",
"False",
",",
"encoding",
":",
"str",
"=",
"\"utf-8\"",
",",
"errors",
":",
"str",
"=",
"\"replace\"",
",",
")",
"->",
"li... | 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 ... | [
"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",
"parameter... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/request.py#L268-L312 | train |
huge-success/sanic | sanic/request.py | Request.remote_addr | 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... | python | 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... | [
"def",
"remote_addr",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_remote_addr\"",
")",
":",
"if",
"self",
".",
"app",
".",
"config",
".",
"PROXIES_COUNT",
"==",
"0",
":",
"self",
".",
"_remote_addr",
"=",
"\"\"",
"elif",
"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. | [
"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",
... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/request.py#L357-L392 | train |
huge-success/sanic | sanic/config.py | strtobool | 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... | python | 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... | [
"def",
"strtobool",
"(",
"val",
")",
":",
"val",
"=",
"val",
".",
"lower",
"(",
")",
"if",
"val",
"in",
"(",
"\"y\"",
",",
"\"yes\"",
",",
"\"t\"",
",",
"\"true\"",
",",
"\"on\"",
",",
"\"1\"",
")",
":",
"return",
"True",
"elif",
"val",
"in",
"("... | 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. | [
"This",
"function",
"was",
"borrowed",
"from",
"distutils",
".",
"utils",
".",
"While",
"distutils",
"is",
"part",
"of",
"stdlib",
"it",
"feels",
"odd",
"to",
"use",
"distutils",
"in",
"main",
"application",
"code",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/config.py#L136-L150 | train |
huge-success/sanic | sanic/config.py | Config.from_envvar | def from_envvar(self, variable_name):
"""Load a configuration from an environment variable pointing to
a configuration file.
:param variable_name: name of the environment variable
:return: bool. ``True`` if able to load config, ``False`` otherwise.
"""
config_file = os.e... | python | def from_envvar(self, variable_name):
"""Load a configuration from an environment variable pointing to
a configuration file.
:param variable_name: name of the environment variable
:return: bool. ``True`` if able to load config, ``False`` otherwise.
"""
config_file = os.e... | [
"def",
"from_envvar",
"(",
"self",
",",
"variable_name",
")",
":",
"config_file",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"variable_name",
")",
"if",
"not",
"config_file",
":",
"raise",
"RuntimeError",
"(",
"\"The environment variable %r is not set and \"",
"\... | 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. | [
"Load",
"a",
"configuration",
"from",
"an",
"environment",
"variable",
"pointing",
"to",
"a",
"configuration",
"file",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/config.py#L57-L70 | train |
huge-success/sanic | sanic/config.py | Config.from_object | def from_object(self, obj):
"""Update the values from the given object.
Objects are usually either modules or classes.
Just the uppercase variables in that object are stored in the config.
Example usage::
from yourapplication import default_config
app.config.fro... | python | def from_object(self, obj):
"""Update the values from the given object.
Objects are usually either modules or classes.
Just the uppercase variables in that object are stored in the config.
Example usage::
from yourapplication import default_config
app.config.fro... | [
"def",
"from_object",
"(",
"self",
",",
"obj",
")",
":",
"for",
"key",
"in",
"dir",
"(",
"obj",
")",
":",
"if",
"key",
".",
"isupper",
"(",
")",
":",
"self",
"[",
"key",
"]",
"=",
"getattr",
"(",
"obj",
",",
"key",
")"
] | Update the values from the given object.
Objects are usually either modules or classes.
Just the uppercase variables in that object are stored in the config.
Example usage::
from yourapplication import default_config
app.config.from_object(default_config)
You s... | [
"Update",
"the",
"values",
"from",
"the",
"given",
"object",
".",
"Objects",
"are",
"usually",
"either",
"modules",
"or",
"classes",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/config.py#L95-L114 | train |
huge-success/sanic | sanic/config.py | Config.load_environment_vars | 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)
... | python | 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)
... | [
"def",
"load_environment_vars",
"(",
"self",
",",
"prefix",
"=",
"SANIC_PREFIX",
")",
":",
"for",
"k",
",",
"v",
"in",
"os",
".",
"environ",
".",
"items",
"(",
")",
":",
"if",
"k",
".",
"startswith",
"(",
"prefix",
")",
":",
"_",
",",
"config_key",
... | Looks for prefixed environment variables and applies
them to the configuration if present. | [
"Looks",
"for",
"prefixed",
"environment",
"variables",
"and",
"applies",
"them",
"to",
"the",
"configuration",
"if",
"present",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/config.py#L116-L133 | train |
huge-success/sanic | sanic/router.py | Router.parse_parameter_string | 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
... | python | 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
... | [
"def",
"parse_parameter_string",
"(",
"cls",
",",
"parameter_string",
")",
":",
"# We could receive NAME or NAME:PATTERN",
"name",
"=",
"parameter_string",
"pattern",
"=",
"\"string\"",
"if",
"\":\"",
"in",
"parameter_string",
":",
"name",
",",
"pattern",
"=",
"parame... | Parse a parameter string into its constituent name, type, and
pattern
For example::
parse_parameter_string('<param_one:[A-z]>')` ->
('param_one', str, '[A-z]')
:param parameter_string: String to parse
:return: tuple containing
(parameter_name, p... | [
"Parse",
"a",
"parameter",
"string",
"into",
"its",
"constituent",
"name",
"type",
"and",
"pattern"
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L92-L119 | train |
huge-success/sanic | sanic/router.py | Router.add | 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
... | python | 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
... | [
"def",
"add",
"(",
"self",
",",
"uri",
",",
"methods",
",",
"handler",
",",
"host",
"=",
"None",
",",
"strict_slashes",
"=",
"False",
",",
"version",
"=",
"None",
",",
"name",
"=",
"None",
",",
")",
":",
"if",
"version",
"is",
"not",
"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_sl... | [
"Add",
"a",
"handler",
"to",
"the",
"route",
"list"
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L121-L182 | train |
huge-success/sanic | sanic/router.py | Router._add | 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... | python | 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... | [
"def",
"_add",
"(",
"self",
",",
"uri",
",",
"methods",
",",
"handler",
",",
"host",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"host",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"host",
",",
"str",
")",
":",
"uri",
"=",
"ho... | Add a handler to the route list
:param uri: path to match
:param methods: sequence of accepted method names. If none are
provided, any method is allowed
:param handler: request handler function.
When executed, it should provide a response object.
:param name: use... | [
"Add",
"a",
"handler",
"to",
"the",
"route",
"list"
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L184-L330 | train |
huge-success/sanic | sanic/router.py | Router.check_dynamic_route_exists | def check_dynamic_route_exists(pattern, routes_to_check, parameters):
"""
Check if a URL pattern exists in a list of routes provided based on
the comparison of URL pattern and the parameters.
:param pattern: URL parameter pattern
:param routes_to_check: list of dynamic routes ei... | python | def check_dynamic_route_exists(pattern, routes_to_check, parameters):
"""
Check if a URL pattern exists in a list of routes provided based on
the comparison of URL pattern and the parameters.
:param pattern: URL parameter pattern
:param routes_to_check: list of dynamic routes ei... | [
"def",
"check_dynamic_route_exists",
"(",
"pattern",
",",
"routes_to_check",
",",
"parameters",
")",
":",
"for",
"ndx",
",",
"route",
"in",
"enumerate",
"(",
"routes_to_check",
")",
":",
"if",
"route",
".",
"pattern",
"==",
"pattern",
"and",
"route",
".",
"p... | 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:... | [
"Check",
"if",
"a",
"URL",
"pattern",
"exists",
"in",
"a",
"list",
"of",
"routes",
"provided",
"based",
"on",
"the",
"comparison",
"of",
"URL",
"pattern",
"and",
"the",
"parameters",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L333-L349 | train |
huge-success/sanic | sanic/router.py | Router.find_route_by_view_name | 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)
"""
... | python | 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)
"""
... | [
"def",
"find_route_by_view_name",
"(",
"self",
",",
"view_name",
",",
"name",
"=",
"None",
")",
":",
"if",
"not",
"view_name",
":",
"return",
"(",
"None",
",",
"None",
")",
"if",
"view_name",
"==",
"\"static\"",
"or",
"view_name",
".",
"endswith",
"(",
"... | 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) | [
"Find",
"a",
"route",
"in",
"the",
"router",
"based",
"on",
"the",
"specified",
"view",
"name",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L383-L396 | train |
huge-success/sanic | sanic/router.py | Router.get | def get(self, request):
"""Get a request handler based on the URL of the request, or raises an
error
:param request: Request object
:return: handler, arguments, keyword arguments
"""
# No virtual hosts specified; default behavior
if not self.hosts:
re... | python | def get(self, request):
"""Get a request handler based on the URL of the request, or raises an
error
:param request: Request object
:return: handler, arguments, keyword arguments
"""
# No virtual hosts specified; default behavior
if not self.hosts:
re... | [
"def",
"get",
"(",
"self",
",",
"request",
")",
":",
"# No virtual hosts specified; default behavior",
"if",
"not",
"self",
".",
"hosts",
":",
"return",
"self",
".",
"_get",
"(",
"request",
".",
"path",
",",
"request",
".",
"method",
",",
"\"\"",
")",
"# v... | Get a request handler based on the URL of the request, or raises an
error
:param request: Request object
:return: handler, arguments, keyword arguments | [
"Get",
"a",
"request",
"handler",
"based",
"on",
"the",
"URL",
"of",
"the",
"request",
"or",
"raises",
"an",
"error"
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L398-L415 | train |
huge-success/sanic | sanic/router.py | Router.get_supported_methods | def get_supported_methods(self, url):
"""Get a list of supported methods for a url and optional host.
:param url: URL string (including host)
:return: frozenset of supported methods
"""
route = self.routes_all.get(url)
# if methods are None then this logic will prevent a... | python | def get_supported_methods(self, url):
"""Get a list of supported methods for a url and optional host.
:param url: URL string (including host)
:return: frozenset of supported methods
"""
route = self.routes_all.get(url)
# if methods are None then this logic will prevent a... | [
"def",
"get_supported_methods",
"(",
"self",
",",
"url",
")",
":",
"route",
"=",
"self",
".",
"routes_all",
".",
"get",
"(",
"url",
")",
"# if methods are None then this logic will prevent an error",
"return",
"getattr",
"(",
"route",
",",
"\"methods\"",
",",
"Non... | Get a list of supported methods for a url and optional host.
:param url: URL string (including host)
:return: frozenset of supported methods | [
"Get",
"a",
"list",
"of",
"supported",
"methods",
"for",
"a",
"url",
"and",
"optional",
"host",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L417-L425 | train |
huge-success/sanic | sanic/router.py | Router._get | def _get(self, url, method, host):
"""Get a request handler based on the URL of the request, or raises an
error. Internal method for caching.
:param url: request URL
:param method: request method
:return: handler, arguments, keyword arguments
"""
url = unquote(h... | python | def _get(self, url, method, host):
"""Get a request handler based on the URL of the request, or raises an
error. Internal method for caching.
:param url: request URL
:param method: request method
:return: handler, arguments, keyword arguments
"""
url = unquote(h... | [
"def",
"_get",
"(",
"self",
",",
"url",
",",
"method",
",",
"host",
")",
":",
"url",
"=",
"unquote",
"(",
"host",
"+",
"url",
")",
"# Check against known static routes",
"route",
"=",
"self",
".",
"routes_static",
".",
"get",
"(",
"url",
")",
"method_not... | 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 | [
"Get",
"a",
"request",
"handler",
"based",
"on",
"the",
"URL",
"of",
"the",
"request",
"or",
"raises",
"an",
"error",
".",
"Internal",
"method",
"for",
"caching",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L428-L478 | train |
huge-success/sanic | sanic/router.py | Router.is_stream_handler | def is_stream_handler(self, request):
""" Handler for request is stream or not.
:param request: Request object
:return: bool
"""
try:
handler = self.get(request)[0]
except (NotFound, MethodNotSupported):
return False
if hasattr(handler, "vi... | python | def is_stream_handler(self, request):
""" Handler for request is stream or not.
:param request: Request object
:return: bool
"""
try:
handler = self.get(request)[0]
except (NotFound, MethodNotSupported):
return False
if hasattr(handler, "vi... | [
"def",
"is_stream_handler",
"(",
"self",
",",
"request",
")",
":",
"try",
":",
"handler",
"=",
"self",
".",
"get",
"(",
"request",
")",
"[",
"0",
"]",
"except",
"(",
"NotFound",
",",
"MethodNotSupported",
")",
":",
"return",
"False",
"if",
"hasattr",
"... | Handler for request is stream or not.
:param request: Request object
:return: bool | [
"Handler",
"for",
"request",
"is",
"stream",
"or",
"not",
".",
":",
"param",
"request",
":",
"Request",
"object",
":",
"return",
":",
"bool"
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/router.py#L480-L493 | train |
huge-success/sanic | sanic/reloader_helpers.py | _get_args_for_reloading | 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])
... | python | 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])
... | [
"def",
"_get_args_for_reloading",
"(",
")",
":",
"rv",
"=",
"[",
"sys",
".",
"executable",
"]",
"main_module",
"=",
"sys",
".",
"modules",
"[",
"\"__main__\"",
"]",
"mod_spec",
"=",
"getattr",
"(",
"main_module",
",",
"\"__spec__\"",
",",
"None",
")",
"if"... | Returns the executable. | [
"Returns",
"the",
"executable",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/reloader_helpers.py#L36-L48 | train |
huge-success/sanic | sanic/reloader_helpers.py | restart_with_reloader | def restart_with_reloader():
"""Create a new process and a subprocess in it with the same arguments as
this one.
"""
cwd = os.getcwd()
args = _get_args_for_reloading()
new_environ = os.environ.copy()
new_environ["SANIC_SERVER_RUNNING"] = "true"
cmd = " ".join(args)
worker_process = P... | python | def restart_with_reloader():
"""Create a new process and a subprocess in it with the same arguments as
this one.
"""
cwd = os.getcwd()
args = _get_args_for_reloading()
new_environ = os.environ.copy()
new_environ["SANIC_SERVER_RUNNING"] = "true"
cmd = " ".join(args)
worker_process = P... | [
"def",
"restart_with_reloader",
"(",
")",
":",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"args",
"=",
"_get_args_for_reloading",
"(",
")",
"new_environ",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"new_environ",
"[",
"\"SANIC_SERVER_RUNNING\"",
"]",
... | Create a new process and a subprocess in it with the same arguments as
this one. | [
"Create",
"a",
"new",
"process",
"and",
"a",
"subprocess",
"in",
"it",
"with",
"the",
"same",
"arguments",
"as",
"this",
"one",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/reloader_helpers.py#L51-L66 | train |
huge-success/sanic | sanic/reloader_helpers.py | kill_process_children_unix | def kill_process_children_unix(pid):
"""Find and kill child processes of a process (maximum two level).
:param pid: PID of parent process (process ID)
:return: Nothing
"""
root_process_path = "/proc/{pid}/task/{pid}/children".format(pid=pid)
if not os.path.isfile(root_process_path):
ret... | python | def kill_process_children_unix(pid):
"""Find and kill child processes of a process (maximum two level).
:param pid: PID of parent process (process ID)
:return: Nothing
"""
root_process_path = "/proc/{pid}/task/{pid}/children".format(pid=pid)
if not os.path.isfile(root_process_path):
ret... | [
"def",
"kill_process_children_unix",
"(",
"pid",
")",
":",
"root_process_path",
"=",
"\"/proc/{pid}/task/{pid}/children\"",
".",
"format",
"(",
"pid",
"=",
"pid",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"root_process_path",
")",
":",
"return",
... | Find and kill child processes of a process (maximum two level).
:param pid: PID of parent process (process ID)
:return: Nothing | [
"Find",
"and",
"kill",
"child",
"processes",
"of",
"a",
"process",
"(",
"maximum",
"two",
"level",
")",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/reloader_helpers.py#L69-L98 | train |
huge-success/sanic | sanic/reloader_helpers.py | kill_process_children | 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:
... | python | 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:
... | [
"def",
"kill_process_children",
"(",
"pid",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"\"darwin\"",
":",
"kill_process_children_osx",
"(",
"pid",
")",
"elif",
"sys",
".",
"platform",
"==",
"\"linux\"",
":",
"kill_process_children_unix",
"(",
"pid",
")",
"e... | Find and kill child processes of a process.
:param pid: PID of parent process (process ID)
:return: Nothing | [
"Find",
"and",
"kill",
"child",
"processes",
"of",
"a",
"process",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/reloader_helpers.py#L110-L121 | train |
huge-success/sanic | sanic/reloader_helpers.py | watchdog | 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... | python | 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... | [
"def",
"watchdog",
"(",
"sleep_interval",
")",
":",
"mtimes",
"=",
"{",
"}",
"worker_process",
"=",
"restart_with_reloader",
"(",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGTERM",
",",
"lambda",
"*",
"args",
":",
"kill_program_completly",
"(",
"wo... | Watch project files, restart worker process if a change happened.
:param sleep_interval: interval in second.
:return: Nothing | [
"Watch",
"project",
"files",
"restart",
"worker",
"process",
"if",
"a",
"change",
"happened",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/reloader_helpers.py#L135-L167 | train |
huge-success/sanic | sanic/views.py | HTTPMethodView.as_view | 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_... | python | 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_... | [
"def",
"as_view",
"(",
"cls",
",",
"*",
"class_args",
",",
"*",
"*",
"class_kwargs",
")",
":",
"def",
"view",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
"=",
"view",
".",
"view_class",
"(",
"*",
"class_args",
",",
"*",
"*",
"cla... | Return view function for use with the routing system, that
dispatches request to appropriate handler method. | [
"Return",
"view",
"function",
"for",
"use",
"with",
"the",
"routing",
"system",
"that",
"dispatches",
"request",
"to",
"appropriate",
"handler",
"method",
"."
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/views.py#L47-L65 | train |
huge-success/sanic | examples/limit_concurrency.py | bounded_fetch | 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() | python | 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() | [
"async",
"def",
"bounded_fetch",
"(",
"session",
",",
"url",
")",
":",
"async",
"with",
"sem",
",",
"session",
".",
"get",
"(",
"url",
")",
"as",
"response",
":",
"return",
"await",
"response",
".",
"json",
"(",
")"
] | Use session object to perform 'get' request on url | [
"Use",
"session",
"object",
"to",
"perform",
"get",
"request",
"on",
"url"
] | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/examples/limit_concurrency.py#L18-L23 | train |
huge-success/sanic | sanic/helpers.py | remove_entity_headers | def remove_entity_headers(headers, allowed=("content-location", "expires")):
"""
Removes all the entity headers present in the headers given.
According to RFC 2616 Section 10.3.5,
Content-Location and Expires are allowed as for the
"strong cache validator".
https://tools.ietf.org/html/rfc2616#se... | python | def remove_entity_headers(headers, allowed=("content-location", "expires")):
"""
Removes all the entity headers present in the headers given.
According to RFC 2616 Section 10.3.5,
Content-Location and Expires are allowed as for the
"strong cache validator".
https://tools.ietf.org/html/rfc2616#se... | [
"def",
"remove_entity_headers",
"(",
"headers",
",",
"allowed",
"=",
"(",
"\"content-location\"",
",",
"\"expires\"",
")",
")",
":",
"allowed",
"=",
"set",
"(",
"[",
"h",
".",
"lower",
"(",
")",
"for",
"h",
"in",
"allowed",
"]",
")",
"headers",
"=",
"{... | 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 | [
"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",
"str... | 6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/helpers.py#L117-L133 | train |
albu/albumentations | albumentations/augmentations/functional.py | preserve_shape | 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 | python | 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 | [
"def",
"preserve_shape",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped_function",
"(",
"img",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"shape",
"=",
"img",
".",
"shape",
"result",
"=",
"func",
"(",
"img",
",",
... | Preserve shape of the image. | [
"Preserve",
"shape",
"of",
"the",
"image",
"."
] | b31393cd6126516d37a84e44c879bd92c68ffc93 | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L35-L44 | train |
albu/albumentations | albumentations/augmentations/functional.py | preserve_channel_dim | def preserve_channel_dim(func):
"""Preserve dummy channel dim."""
@wraps(func)
def wrapped_function(img, *args, **kwargs):
shape = img.shape
result = func(img, *args, **kwargs)
if len(shape) == 3 and shape[-1] == 1 and len(result.shape) == 2:
result = np.expand_dims(resul... | python | def preserve_channel_dim(func):
"""Preserve dummy channel dim."""
@wraps(func)
def wrapped_function(img, *args, **kwargs):
shape = img.shape
result = func(img, *args, **kwargs)
if len(shape) == 3 and shape[-1] == 1 and len(result.shape) == 2:
result = np.expand_dims(resul... | [
"def",
"preserve_channel_dim",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped_function",
"(",
"img",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"shape",
"=",
"img",
".",
"shape",
"result",
"=",
"func",
"(",
"img",
... | Preserve dummy channel dim. | [
"Preserve",
"dummy",
"channel",
"dim",
"."
] | b31393cd6126516d37a84e44c879bd92c68ffc93 | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L47-L57 | train |
albu/albumentations | albumentations/augmentations/functional.py | add_snow | 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
... | python | 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
... | [
"def",
"add_snow",
"(",
"img",
",",
"snow_point",
",",
"brightness_coeff",
")",
":",
"non_rgb_warning",
"(",
"img",
")",
"input_dtype",
"=",
"img",
".",
"dtype",
"needs_float",
"=",
"False",
"snow_point",
"*=",
"127.5",
"# = 255 / 2",
"snow_point",
"+=",
"85",... | Bleaches out pixels, mitation snow.
From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library
Args:
img:
snow_point:
brightness_coeff:
Returns: | [
"Bleaches",
"out",
"pixels",
"mitation",
"snow",
"."
] | b31393cd6126516d37a84e44c879bd92c68ffc93 | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L438-L479 | train |
albu/albumentations | albumentations/augmentations/functional.py | add_fog | 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)
... | python | 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)
... | [
"def",
"add_fog",
"(",
"img",
",",
"fog_coef",
",",
"alpha_coef",
",",
"haze_list",
")",
":",
"non_rgb_warning",
"(",
"img",
")",
"input_dtype",
"=",
"img",
".",
"dtype",
"needs_float",
"=",
"False",
"if",
"input_dtype",
"==",
"np",
".",
"float32",
":",
... | 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: | [
"Add",
"fog",
"to",
"the",
"image",
"."
] | b31393cd6126516d37a84e44c879bd92c68ffc93 | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L533-L578 | train |
albu/albumentations | albumentations/augmentations/functional.py | add_sun_flare | def add_sun_flare(img, flare_center_x, flare_center_y, src_radius, src_color, circles):
"""Add sun flare.
From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library
Args:
img (np.array):
flare_center_x (float):
flare_center_y (float):
src_radius:
src_c... | python | def add_sun_flare(img, flare_center_x, flare_center_y, src_radius, src_color, circles):
"""Add sun flare.
From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library
Args:
img (np.array):
flare_center_x (float):
flare_center_y (float):
src_radius:
src_c... | [
"def",
"add_sun_flare",
"(",
"img",
",",
"flare_center_x",
",",
"flare_center_y",
",",
"src_radius",
",",
"src_color",
",",
"circles",
")",
":",
"non_rgb_warning",
"(",
"img",
")",
"input_dtype",
"=",
"img",
".",
"dtype",
"needs_float",
"=",
"False",
"if",
"... | 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: | [
"Add",
"sun",
"flare",
"."
] | b31393cd6126516d37a84e44c879bd92c68ffc93 | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L582-L633 | train |
albu/albumentations | albumentations/augmentations/functional.py | add_shadow | 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 ... | python | 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 ... | [
"def",
"add_shadow",
"(",
"img",
",",
"vertices_list",
")",
":",
"non_rgb_warning",
"(",
"img",
")",
"input_dtype",
"=",
"img",
".",
"dtype",
"needs_float",
"=",
"False",
"if",
"input_dtype",
"==",
"np",
".",
"float32",
":",
"img",
"=",
"from_float",
"(",
... | Add shadows to the image.
From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library
Args:
img (np.array):
vertices_list (list):
Returns: | [
"Add",
"shadows",
"to",
"the",
"image",
"."
] | b31393cd6126516d37a84e44c879bd92c68ffc93 | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L637-L675 | train |
albu/albumentations | albumentations/augmentations/functional.py | optical_distortion | def optical_distortion(img, k=0, dx=0, dy=0, interpolation=cv2.INTER_LINEAR, border_mode=cv2.BORDER_REFLECT_101,
value=None):
"""Barrel / pincushion distortion. Unconventional augment.
Reference:
| https://stackoverflow.com/questions/6199636/formulas-for-barrel-pincushion-distor... | python | def optical_distortion(img, k=0, dx=0, dy=0, interpolation=cv2.INTER_LINEAR, border_mode=cv2.BORDER_REFLECT_101,
value=None):
"""Barrel / pincushion distortion. Unconventional augment.
Reference:
| https://stackoverflow.com/questions/6199636/formulas-for-barrel-pincushion-distor... | [
"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/correctin... | [
"Barrel",
"/",
"pincushion",
"distortion",
".",
"Unconventional",
"augment",
"."
] | b31393cd6126516d37a84e44c879bd92c68ffc93 | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L679-L704 | train |
albu/albumentations | albumentations/augmentations/functional.py | grid_distortion | 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]
... | python | 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]
... | [
"def",
"grid_distortion",
"(",
"img",
",",
"num_steps",
"=",
"10",
",",
"xsteps",
"=",
"[",
"]",
",",
"ysteps",
"=",
"[",
"]",
",",
"interpolation",
"=",
"cv2",
".",
"INTER_LINEAR",
",",
"border_mode",
"=",
"cv2",
".",
"BORDER_REFLECT_101",
",",
"value",... | Reference:
http://pythology.blogspot.sg/2014/03/interpolation-on-regular-distorted-grid.html | [
"Reference",
":",
"http",
":",
"//",
"pythology",
".",
"blogspot",
".",
"sg",
"/",
"2014",
"/",
"03",
"/",
"interpolation",
"-",
"on",
"-",
"regular",
"-",
"distorted",
"-",
"grid",
".",
"html"
] | b31393cd6126516d37a84e44c879bd92c68ffc93 | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L708-L750 | train |
albu/albumentations | albumentations/augmentations/functional.py | elastic_transform | 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.... | python | 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.... | [
"def",
"elastic_transform",
"(",
"image",
",",
"alpha",
",",
"sigma",
",",
"alpha_affine",
",",
"interpolation",
"=",
"cv2",
".",
"INTER_LINEAR",
",",
"border_mode",
"=",
"cv2",
".",
"BORDER_REFLECT_101",
",",
"value",
"=",
"None",
",",
"random_state",
"=",
... | 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... | [
"Elastic",
"deformation",
"of",
"images",
"as",
"described",
"in",
"[",
"Simard2003",
"]",
"_",
"(",
"with",
"modifications",
")",
".",
"Based",
"on",
"https",
":",
"//",
"gist",
".",
"github",
".",
"com",
"/",
"erniejunior",
"/",
"601cdf56d2b424757de5"
] | b31393cd6126516d37a84e44c879bd92c68ffc93 | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L754-L803 | train |
albu/albumentations | albumentations/augmentations/functional.py | bbox_vflip | 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] | python | 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] | [
"def",
"bbox_vflip",
"(",
"bbox",
",",
"rows",
",",
"cols",
")",
":",
"x_min",
",",
"y_min",
",",
"x_max",
",",
"y_max",
"=",
"bbox",
"return",
"[",
"x_min",
",",
"1",
"-",
"y_max",
",",
"x_max",
",",
"1",
"-",
"y_min",
"]"
] | Flip a bounding box vertically around the x-axis. | [
"Flip",
"a",
"bounding",
"box",
"vertically",
"around",
"the",
"x",
"-",
"axis",
"."
] | b31393cd6126516d37a84e44c879bd92c68ffc93 | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L918-L921 | train |
albu/albumentations | albumentations/augmentations/functional.py | bbox_hflip | 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] | python | 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] | [
"def",
"bbox_hflip",
"(",
"bbox",
",",
"rows",
",",
"cols",
")",
":",
"x_min",
",",
"y_min",
",",
"x_max",
",",
"y_max",
"=",
"bbox",
"return",
"[",
"1",
"-",
"x_max",
",",
"y_min",
",",
"1",
"-",
"x_min",
",",
"y_max",
"]"
] | Flip a bounding box horizontally around the y-axis. | [
"Flip",
"a",
"bounding",
"box",
"horizontally",
"around",
"the",
"y",
"-",
"axis",
"."
] | b31393cd6126516d37a84e44c879bd92c68ffc93 | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L924-L927 | train |
albu/albumentations | albumentations/augmentations/functional.py | bbox_flip | def bbox_flip(bbox, d, rows, cols):
"""Flip a bounding box either vertically, horizontally or both depending on the value of `d`.
Raises:
ValueError: if value of `d` is not -1, 0 or 1.
"""
if d == 0:
bbox = bbox_vflip(bbox, rows, cols)
elif d == 1:
bbox = bbox_hflip(bbox, r... | python | def bbox_flip(bbox, d, rows, cols):
"""Flip a bounding box either vertically, horizontally or both depending on the value of `d`.
Raises:
ValueError: if value of `d` is not -1, 0 or 1.
"""
if d == 0:
bbox = bbox_vflip(bbox, rows, cols)
elif d == 1:
bbox = bbox_hflip(bbox, r... | [
"def",
"bbox_flip",
"(",
"bbox",
",",
"d",
",",
"rows",
",",
"cols",
")",
":",
"if",
"d",
"==",
"0",
":",
"bbox",
"=",
"bbox_vflip",
"(",
"bbox",
",",
"rows",
",",
"cols",
")",
"elif",
"d",
"==",
"1",
":",
"bbox",
"=",
"bbox_hflip",
"(",
"bbox"... | 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. | [
"Flip",
"a",
"bounding",
"box",
"either",
"vertically",
"horizontally",
"or",
"both",
"depending",
"on",
"the",
"value",
"of",
"d",
"."
] | b31393cd6126516d37a84e44c879bd92c68ffc93 | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L930-L946 | train |
albu/albumentations | albumentations/augmentations/functional.py | crop_bbox_by_coords | def crop_bbox_by_coords(bbox, crop_coords, crop_height, crop_width, rows, cols):
"""Crop a bounding box using the provided coordinates of bottom-left and top-right corners in pixels and the
required height and width of the crop.
"""
bbox = denormalize_bbox(bbox, rows, cols)
x_min, y_min, x_max, y_ma... | python | def crop_bbox_by_coords(bbox, crop_coords, crop_height, crop_width, rows, cols):
"""Crop a bounding box using the provided coordinates of bottom-left and top-right corners in pixels and the
required height and width of the crop.
"""
bbox = denormalize_bbox(bbox, rows, cols)
x_min, y_min, x_max, y_ma... | [
"def",
"crop_bbox_by_coords",
"(",
"bbox",
",",
"crop_coords",
",",
"crop_height",
",",
"crop_width",
",",
"rows",
",",
"cols",
")",
":",
"bbox",
"=",
"denormalize_bbox",
"(",
"bbox",
",",
"rows",
",",
"cols",
")",
"x_min",
",",
"y_min",
",",
"x_max",
",... | 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. | [
"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",
"."
] | b31393cd6126516d37a84e44c879bd92c68ffc93 | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L949-L957 | train |
albu/albumentations | albumentations/augmentations/functional.py | bbox_rot90 | def bbox_rot90(bbox, factor, rows, cols):
"""Rotates a bounding box by 90 degrees CCW (see np.rot90)
Args:
bbox (tuple): A tuple (x_min, y_min, x_max, y_max).
factor (int): Number of CCW rotations. Must be in range [0;3] See np.rot90.
rows (int): Image rows.
cols (int): Image co... | python | def bbox_rot90(bbox, factor, rows, cols):
"""Rotates a bounding box by 90 degrees CCW (see np.rot90)
Args:
bbox (tuple): A tuple (x_min, y_min, x_max, y_max).
factor (int): Number of CCW rotations. Must be in range [0;3] See np.rot90.
rows (int): Image rows.
cols (int): Image co... | [
"def",
"bbox_rot90",
"(",
"bbox",
",",
"factor",
",",
"rows",
",",
"cols",
")",
":",
"if",
"factor",
"<",
"0",
"or",
"factor",
">",
"3",
":",
"raise",
"ValueError",
"(",
"'Parameter n must be in range [0;3]'",
")",
"x_min",
",",
"y_min",
",",
"x_max",
",... | 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. | [
"Rotates",
"a",
"bounding",
"box",
"by",
"90",
"degrees",
"CCW",
"(",
"see",
"np",
".",
"rot90",
")"
] | b31393cd6126516d37a84e44c879bd92c68ffc93 | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L977-L995 | train |
albu/albumentations | albumentations/augmentations/functional.py | bbox_rotate | def bbox_rotate(bbox, angle, rows, cols, interpolation):
"""Rotates a bounding box by angle degrees
Args:
bbox (tuple): A tuple (x_min, y_min, x_max, y_max).
angle (int): Angle of rotation in degrees
rows (int): Image rows.
cols (int): Image cols.
interpolation (int): in... | python | def bbox_rotate(bbox, angle, rows, cols, interpolation):
"""Rotates a bounding box by angle degrees
Args:
bbox (tuple): A tuple (x_min, y_min, x_max, y_max).
angle (int): Angle of rotation in degrees
rows (int): Image rows.
cols (int): Image cols.
interpolation (int): in... | [
"def",
"bbox_rotate",
"(",
"bbox",
",",
"angle",
",",
"rows",
",",
"cols",
",",
"interpolation",
")",
":",
"scale",
"=",
"cols",
"/",
"float",
"(",
"rows",
")",
"x",
"=",
"np",
".",
"array",
"(",
"[",
"bbox",
"[",
"0",
"]",
",",
"bbox",
"[",
"2... | 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... | [
"Rotates",
"a",
"bounding",
"box",
"by",
"angle",
"degrees"
] | b31393cd6126516d37a84e44c879bd92c68ffc93 | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L998-L1020 | train |
albu/albumentations | albumentations/augmentations/functional.py | bbox_transpose | 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_... | python | 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_... | [
"def",
"bbox_transpose",
"(",
"bbox",
",",
"axis",
",",
"rows",
",",
"cols",
")",
":",
"x_min",
",",
"y_min",
",",
"x_max",
",",
"y_max",
"=",
"bbox",
"if",
"axis",
"!=",
"0",
"and",
"axis",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"'Axis must be ... | 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. | [
"Transposes",
"a",
"bounding",
"box",
"along",
"given",
"axis",
"."
] | b31393cd6126516d37a84e44c879bd92c68ffc93 | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L1023-L1039 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.