Pep8 cleanups (#429)
* PEP8 cleanups * PEP8 cleanups (server.py) * PEP8 cleanups (blueprints.py) * PEP8 cleanups (config.py) * PEP8 cleanups (cookies.py) * PEP8 cleanups (handlers.py) * PEP8 cleanups (request.py) * PEP8 cleanups (response.py) * PEP8 cleanups (router.py) * PEP8 cleanups (sanic.py) #2 * PEP8 cleanups (server.py) #2 * PEP8 cleanups (static.py) * PEP8 cleanups (utils.py) * PEP8 cleanups (views.py) Updated docstring
This commit is contained in:
parent
286dc3c32b
commit
51611c3934
|
@ -13,9 +13,9 @@ FutureStatic = namedtuple('Route',
|
||||||
|
|
||||||
class Blueprint:
|
class Blueprint:
|
||||||
def __init__(self, name, url_prefix=None, host=None):
|
def __init__(self, name, url_prefix=None, host=None):
|
||||||
"""
|
"""Create a new blueprint
|
||||||
Creates a new blueprint
|
|
||||||
:param name: Unique name of the blueprint
|
:param name: unique name of the blueprint
|
||||||
:param url_prefix: URL to be prefixed before all route URLs
|
:param url_prefix: URL to be prefixed before all route URLs
|
||||||
"""
|
"""
|
||||||
self.name = name
|
self.name = name
|
||||||
|
@ -29,9 +29,7 @@ class Blueprint:
|
||||||
self.statics = []
|
self.statics = []
|
||||||
|
|
||||||
def register(self, app, options):
|
def register(self, app, options):
|
||||||
"""
|
"""Register the blueprint to the sanic app."""
|
||||||
Registers the blueprint to the sanic app.
|
|
||||||
"""
|
|
||||||
|
|
||||||
url_prefix = options.get('url_prefix', self.url_prefix)
|
url_prefix = options.get('url_prefix', self.url_prefix)
|
||||||
|
|
||||||
|
@ -73,10 +71,10 @@ class Blueprint:
|
||||||
app.listener(event)(listener)
|
app.listener(event)(listener)
|
||||||
|
|
||||||
def route(self, uri, methods=frozenset({'GET'}), host=None):
|
def route(self, uri, methods=frozenset({'GET'}), host=None):
|
||||||
"""
|
"""Create a blueprint route from a decorated function.
|
||||||
Creates a blueprint route from a decorated function.
|
|
||||||
:param uri: Endpoint at which the route will be accessible.
|
:param uri: endpoint at which the route will be accessible.
|
||||||
:param methods: List of acceptable HTTP methods.
|
:param methods: list of acceptable HTTP methods.
|
||||||
"""
|
"""
|
||||||
def decorator(handler):
|
def decorator(handler):
|
||||||
route = FutureRoute(handler, uri, methods, host)
|
route = FutureRoute(handler, uri, methods, host)
|
||||||
|
@ -85,12 +83,12 @@ class Blueprint:
|
||||||
return decorator
|
return decorator
|
||||||
|
|
||||||
def add_route(self, handler, uri, methods=frozenset({'GET'}), host=None):
|
def add_route(self, handler, uri, methods=frozenset({'GET'}), host=None):
|
||||||
"""
|
"""Create a blueprint route from a function.
|
||||||
Creates a blueprint route from a function.
|
|
||||||
:param handler: Function for handling uri requests. Accepts function,
|
:param handler: function for handling uri requests. Accepts function,
|
||||||
or class instance with a view_class method.
|
or class instance with a view_class method.
|
||||||
:param uri: Endpoint at which the route will be accessible.
|
:param uri: endpoint at which the route will be accessible.
|
||||||
:param methods: List of acceptable HTTP methods.
|
:param methods: list of acceptable HTTP methods.
|
||||||
:return: function or class instance
|
:return: function or class instance
|
||||||
"""
|
"""
|
||||||
# Handle HTTPMethodView differently
|
# Handle HTTPMethodView differently
|
||||||
|
@ -109,8 +107,8 @@ class Blueprint:
|
||||||
return handler
|
return handler
|
||||||
|
|
||||||
def listener(self, event):
|
def listener(self, event):
|
||||||
"""
|
"""Create a listener from a decorated function.
|
||||||
Create a listener from a decorated function.
|
|
||||||
:param event: Event to listen to.
|
:param event: Event to listen to.
|
||||||
"""
|
"""
|
||||||
def decorator(listener):
|
def decorator(listener):
|
||||||
|
@ -119,9 +117,7 @@ class Blueprint:
|
||||||
return decorator
|
return decorator
|
||||||
|
|
||||||
def middleware(self, *args, **kwargs):
|
def middleware(self, *args, **kwargs):
|
||||||
"""
|
"""Create a blueprint middleware from a decorated function."""
|
||||||
Creates a blueprint middleware from a decorated function.
|
|
||||||
"""
|
|
||||||
def register_middleware(_middleware):
|
def register_middleware(_middleware):
|
||||||
future_middleware = FutureMiddleware(_middleware, args, kwargs)
|
future_middleware = FutureMiddleware(_middleware, args, kwargs)
|
||||||
self.middlewares.append(future_middleware)
|
self.middlewares.append(future_middleware)
|
||||||
|
@ -136,9 +132,7 @@ class Blueprint:
|
||||||
return register_middleware
|
return register_middleware
|
||||||
|
|
||||||
def exception(self, *args, **kwargs):
|
def exception(self, *args, **kwargs):
|
||||||
"""
|
"""Create a blueprint exception from a decorated function."""
|
||||||
Creates a blueprint exception from a decorated function.
|
|
||||||
"""
|
|
||||||
def decorator(handler):
|
def decorator(handler):
|
||||||
exception = FutureException(handler, args, kwargs)
|
exception = FutureException(handler, args, kwargs)
|
||||||
self.exceptions.append(exception)
|
self.exceptions.append(exception)
|
||||||
|
@ -146,9 +140,9 @@ class Blueprint:
|
||||||
return decorator
|
return decorator
|
||||||
|
|
||||||
def static(self, uri, file_or_directory, *args, **kwargs):
|
def static(self, uri, file_or_directory, *args, **kwargs):
|
||||||
"""
|
"""Create a blueprint static route from a decorated function.
|
||||||
Creates a blueprint static route from a decorated function.
|
|
||||||
:param uri: Endpoint at which the route will be accessible.
|
:param uri: endpoint at which the route will be accessible.
|
||||||
:param file_or_directory: Static asset.
|
:param file_or_directory: Static asset.
|
||||||
"""
|
"""
|
||||||
static = FutureStatic(uri, file_or_directory, args, kwargs)
|
static = FutureStatic(uri, file_or_directory, args, kwargs)
|
||||||
|
|
|
@ -39,8 +39,9 @@ class Config(dict):
|
||||||
self[attr] = value
|
self[attr] = value
|
||||||
|
|
||||||
def from_envvar(self, variable_name):
|
def from_envvar(self, variable_name):
|
||||||
"""Loads a configuration from an environment variable pointing to
|
"""Load a configuration from an environment variable pointing to
|
||||||
a configuration file.
|
a configuration file.
|
||||||
|
|
||||||
:param variable_name: name of the environment variable
|
:param variable_name: name of the environment variable
|
||||||
:return: bool. ``True`` if able to load config, ``False`` otherwise.
|
:return: bool. ``True`` if able to load config, ``False`` otherwise.
|
||||||
"""
|
"""
|
||||||
|
@ -52,8 +53,9 @@ class Config(dict):
|
||||||
return self.from_pyfile(config_file)
|
return self.from_pyfile(config_file)
|
||||||
|
|
||||||
def from_pyfile(self, filename):
|
def from_pyfile(self, filename):
|
||||||
"""Updates the values in the config from a Python file. Only the uppercase
|
"""Update the values in the config from a Python file.
|
||||||
variables in that module are stored in the config.
|
Only the uppercase variables in that module are stored in the config.
|
||||||
|
|
||||||
:param filename: an absolute path to the config file
|
:param filename: an absolute path to the config file
|
||||||
"""
|
"""
|
||||||
module = types.ModuleType('config')
|
module = types.ModuleType('config')
|
||||||
|
@ -69,7 +71,7 @@ class Config(dict):
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def from_object(self, obj):
|
def from_object(self, obj):
|
||||||
"""Updates the values from the given object.
|
"""Update the values from the given object.
|
||||||
Objects are usually either modules or classes.
|
Objects are usually either modules or classes.
|
||||||
|
|
||||||
Just the uppercase variables in that object are stored in the config.
|
Just the uppercase variables in that object are stored in the config.
|
||||||
|
|
|
@ -39,8 +39,7 @@ _is_legal_key = re.compile('[%s]+' % re.escape(_LegalChars)).fullmatch
|
||||||
|
|
||||||
|
|
||||||
class CookieJar(dict):
|
class CookieJar(dict):
|
||||||
"""
|
"""CookieJar dynamically writes headers as cookies are added and removed
|
||||||
CookieJar dynamically writes headers as cookies are added and removed
|
|
||||||
It gets around the limitation of one header per name by using the
|
It gets around the limitation of one header per name by using the
|
||||||
MultiHeader class to provide a unique key that encodes to Set-Cookie.
|
MultiHeader class to provide a unique key that encodes to Set-Cookie.
|
||||||
"""
|
"""
|
||||||
|
@ -75,9 +74,7 @@ class CookieJar(dict):
|
||||||
|
|
||||||
|
|
||||||
class Cookie(dict):
|
class Cookie(dict):
|
||||||
"""
|
"""A stripped down version of Morsel from SimpleCookie #gottagofast"""
|
||||||
This is a stripped down version of Morsel from SimpleCookie #gottagofast
|
|
||||||
"""
|
|
||||||
_keys = {
|
_keys = {
|
||||||
"expires": "expires",
|
"expires": "expires",
|
||||||
"path": "Path",
|
"path": "Path",
|
||||||
|
@ -128,9 +125,8 @@ class Cookie(dict):
|
||||||
|
|
||||||
|
|
||||||
class MultiHeader:
|
class MultiHeader:
|
||||||
"""
|
"""String-holding object which allow us to set a header within response
|
||||||
Allows us to set a header within response that has a unique key,
|
that has a unique key, but may contain duplicate header names
|
||||||
but may contain duplicate header names
|
|
||||||
"""
|
"""
|
||||||
def __init__(self, name):
|
def __init__(self, name):
|
||||||
self.name = name
|
self.name = name
|
||||||
|
|
|
@ -35,8 +35,8 @@ class ErrorHandler:
|
||||||
self.handlers[exception] = handler
|
self.handlers[exception] = handler
|
||||||
|
|
||||||
def response(self, request, exception):
|
def response(self, request, exception):
|
||||||
"""
|
"""Fetches and executes an exception handler and returns a response
|
||||||
Fetches and executes an exception handler and returns a response object
|
object
|
||||||
|
|
||||||
:param request: Request
|
:param request: Request
|
||||||
:param exception: Exception to handle
|
:param exception: Exception to handle
|
||||||
|
@ -79,9 +79,7 @@ class ErrorHandler:
|
||||||
|
|
||||||
|
|
||||||
class ContentRangeHandler:
|
class ContentRangeHandler:
|
||||||
"""
|
"""Class responsible for parsing request header"""
|
||||||
This class is for parsing the request header
|
|
||||||
"""
|
|
||||||
__slots__ = ('start', 'end', 'size', 'total', 'headers')
|
__slots__ = ('start', 'end', 'size', 'total', 'headers')
|
||||||
|
|
||||||
def __init__(self, request, stats):
|
def __init__(self, request, stats):
|
||||||
|
|
|
@ -16,8 +16,7 @@ DEFAULT_HTTP_CONTENT_TYPE = "application/octet-stream"
|
||||||
|
|
||||||
|
|
||||||
class RequestParameters(dict):
|
class RequestParameters(dict):
|
||||||
"""
|
"""Hosts a dict with lists as values where get returns the first
|
||||||
Hosts a dict with lists as values where get returns the first
|
|
||||||
value of the list and getlist returns the whole shebang
|
value of the list and getlist returns the whole shebang
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
@ -31,9 +30,7 @@ class RequestParameters(dict):
|
||||||
|
|
||||||
|
|
||||||
class Request(dict):
|
class Request(dict):
|
||||||
"""
|
"""Properties of an HTTP request such as URL, headers, etc."""
|
||||||
Properties of an HTTP request such as URL, headers, etc.
|
|
||||||
"""
|
|
||||||
__slots__ = (
|
__slots__ = (
|
||||||
'url', 'headers', 'version', 'method', '_cookies', 'transport',
|
'url', 'headers', 'version', 'method', '_cookies', 'transport',
|
||||||
'query_string', 'body',
|
'query_string', 'body',
|
||||||
|
@ -73,8 +70,8 @@ class Request(dict):
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def token(self):
|
def token(self):
|
||||||
"""
|
"""Attempt to return the auth header token.
|
||||||
Attempts to return the auth header token.
|
|
||||||
:return: token related to request
|
:return: token related to request
|
||||||
"""
|
"""
|
||||||
auth_header = self.headers.get('Authorization')
|
auth_header = self.headers.get('Authorization')
|
||||||
|
@ -146,11 +143,10 @@ File = namedtuple('File', ['type', 'body', 'name'])
|
||||||
|
|
||||||
|
|
||||||
def parse_multipart_form(body, boundary):
|
def parse_multipart_form(body, boundary):
|
||||||
"""
|
"""Parse a request body and returns fields and files
|
||||||
Parses a request body and returns fields and files
|
|
||||||
|
|
||||||
:param body: Bytes request body
|
:param body: bytes request body
|
||||||
:param boundary: Bytes multipart boundary
|
:param boundary: bytes multipart boundary
|
||||||
:return: fields (RequestParameters), files (RequestParameters)
|
:return: fields (RequestParameters), files (RequestParameters)
|
||||||
"""
|
"""
|
||||||
files = RequestParameters()
|
files = RequestParameters()
|
||||||
|
|
|
@ -177,8 +177,8 @@ def html(body, status=200, headers=None):
|
||||||
|
|
||||||
|
|
||||||
async def file(location, mime_type=None, headers=None, _range=None):
|
async def file(location, mime_type=None, headers=None, _range=None):
|
||||||
"""
|
"""Return a response object with file data.
|
||||||
Returns response object with file data.
|
|
||||||
:param location: Location of file on system.
|
:param location: Location of file on system.
|
||||||
:param mime_type: Specific mime_type.
|
:param mime_type: Specific mime_type.
|
||||||
:param headers: Custom Headers.
|
:param headers: Custom Headers.
|
||||||
|
@ -205,14 +205,12 @@ async def file(location, mime_type=None, headers=None, _range=None):
|
||||||
|
|
||||||
def redirect(to, headers=None, status=302,
|
def redirect(to, headers=None, status=302,
|
||||||
content_type="text/html; charset=utf-8"):
|
content_type="text/html; charset=utf-8"):
|
||||||
"""
|
"""Abort execution and cause a 302 redirect (by default).
|
||||||
Aborts execution and causes a 302 redirect (by default).
|
|
||||||
|
|
||||||
:param to: path or fully qualified URL to redirect to
|
:param to: path or fully qualified URL to redirect to
|
||||||
:param headers: optional dict of headers to include in the new request
|
: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 status: status code (int) of the new request, defaults to 302
|
||||||
:param content_type:
|
:param content_type: the content type (string) of the response
|
||||||
the content type (string) of the response
|
|
||||||
:returns: the redirecting Response
|
:returns: the redirecting Response
|
||||||
"""
|
"""
|
||||||
headers = headers or {}
|
headers = headers or {}
|
||||||
|
|
|
@ -32,8 +32,7 @@ class RouteDoesNotExist(Exception):
|
||||||
|
|
||||||
|
|
||||||
class Router:
|
class Router:
|
||||||
"""
|
"""Router supports basic routing with parameters and method checks
|
||||||
Router supports basic routing with parameters and method checks
|
|
||||||
|
|
||||||
Usage:
|
Usage:
|
||||||
|
|
||||||
|
@ -71,8 +70,9 @@ class Router:
|
||||||
self.hosts = None
|
self.hosts = None
|
||||||
|
|
||||||
def parse_parameter_string(self, parameter_string):
|
def parse_parameter_string(self, parameter_string):
|
||||||
"""
|
"""Parse a parameter string into its constituent name, type, and
|
||||||
Parse a parameter string into its constituent name, type, and pattern
|
pattern
|
||||||
|
|
||||||
For example:
|
For example:
|
||||||
`parse_parameter_string('<param_one:[A-z]')` ->
|
`parse_parameter_string('<param_one:[A-z]')` ->
|
||||||
('param_one', str, '[A-z]')
|
('param_one', str, '[A-z]')
|
||||||
|
@ -94,13 +94,12 @@ class Router:
|
||||||
return name, _type, pattern
|
return name, _type, pattern
|
||||||
|
|
||||||
def add(self, uri, methods, handler, host=None):
|
def add(self, uri, methods, handler, host=None):
|
||||||
"""
|
"""Add a handler to the route list
|
||||||
Adds a handler to the route list
|
|
||||||
|
|
||||||
:param uri: Path to match
|
:param uri: path to match
|
||||||
:param methods: Array of accepted method names.
|
:param methods: sequence of accepted method names. If none are
|
||||||
If none are provided, any method is allowed
|
provided, any method is allowed
|
||||||
:param handler: Request handler function.
|
:param handler: request handler function.
|
||||||
When executed, it should provide a response object.
|
When executed, it should provide a response object.
|
||||||
:return: Nothing
|
:return: Nothing
|
||||||
"""
|
"""
|
||||||
|
@ -239,8 +238,7 @@ class Router:
|
||||||
|
|
||||||
@lru_cache(maxsize=ROUTER_CACHE_SIZE)
|
@lru_cache(maxsize=ROUTER_CACHE_SIZE)
|
||||||
def find_route_by_view_name(self, view_name):
|
def find_route_by_view_name(self, view_name):
|
||||||
"""
|
"""Find a route in the router based on the specified view name.
|
||||||
Find a route in the router based on the specified view name.
|
|
||||||
|
|
||||||
:param view_name: string of view name to search by
|
:param view_name: string of view name to search by
|
||||||
:return: tuple containing (uri, Route)
|
:return: tuple containing (uri, Route)
|
||||||
|
@ -255,8 +253,7 @@ class Router:
|
||||||
return (None, None)
|
return (None, None)
|
||||||
|
|
||||||
def get(self, request):
|
def get(self, request):
|
||||||
"""
|
"""Get a request handler based on the URL of the request, or raises an
|
||||||
Gets a request handler based on the URL of the request, or raises an
|
|
||||||
error
|
error
|
||||||
|
|
||||||
:param request: Request object
|
:param request: Request object
|
||||||
|
@ -270,11 +267,11 @@ class Router:
|
||||||
|
|
||||||
@lru_cache(maxsize=ROUTER_CACHE_SIZE)
|
@lru_cache(maxsize=ROUTER_CACHE_SIZE)
|
||||||
def _get(self, url, method, host):
|
def _get(self, url, method, host):
|
||||||
"""
|
"""Get a request handler based on the URL of the request, or raises an
|
||||||
Gets a request handler based on the URL of the request, or raises an
|
|
||||||
error. Internal method for caching.
|
error. Internal method for caching.
|
||||||
:param url: Request URL
|
|
||||||
:param method: Request method
|
:param url: request URL
|
||||||
|
:param method: request method
|
||||||
:return: handler, arguments, keyword arguments
|
:return: handler, arguments, keyword arguments
|
||||||
"""
|
"""
|
||||||
url = host + url
|
url = host + url
|
||||||
|
|
|
@ -22,8 +22,7 @@ from .views import CompositionView
|
||||||
|
|
||||||
class Sanic:
|
class Sanic:
|
||||||
|
|
||||||
def __init__(self, name=None, router=None,
|
def __init__(self, name=None, router=None, error_handler=None):
|
||||||
error_handler=None):
|
|
||||||
# Only set up a default log handler if the
|
# Only set up a default log handler if the
|
||||||
# end-user application didn't set anything up.
|
# end-user application didn't set anything up.
|
||||||
if not logging.root.handlers and log.level == logging.NOTSET:
|
if not logging.root.handlers and log.level == logging.NOTSET:
|
||||||
|
@ -33,9 +32,12 @@ class Sanic:
|
||||||
handler.setFormatter(formatter)
|
handler.setFormatter(formatter)
|
||||||
log.addHandler(handler)
|
log.addHandler(handler)
|
||||||
log.setLevel(logging.INFO)
|
log.setLevel(logging.INFO)
|
||||||
|
|
||||||
|
# Get name from previous stack frame
|
||||||
if name is None:
|
if name is None:
|
||||||
frame_records = stack()[1]
|
frame_records = stack()[1]
|
||||||
name = getmodulename(frame_records[1])
|
name = getmodulename(frame_records[1])
|
||||||
|
|
||||||
self.name = name
|
self.name = name
|
||||||
self.router = router or Router()
|
self.router = router or Router()
|
||||||
self.error_handler = error_handler or ErrorHandler()
|
self.error_handler = error_handler or ErrorHandler()
|
||||||
|
@ -53,9 +55,7 @@ class Sanic:
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def loop(self):
|
def loop(self):
|
||||||
"""
|
"""Synonymous with asyncio.get_event_loop()."""
|
||||||
Synonymous with asyncio.get_event_loop()
|
|
||||||
"""
|
|
||||||
return get_event_loop()
|
return get_event_loop()
|
||||||
|
|
||||||
# -------------------------------------------------------------------- #
|
# -------------------------------------------------------------------- #
|
||||||
|
@ -63,13 +63,12 @@ class Sanic:
|
||||||
# -------------------------------------------------------------------- #
|
# -------------------------------------------------------------------- #
|
||||||
|
|
||||||
def add_task(self, task):
|
def add_task(self, task):
|
||||||
"""
|
"""Schedule a task to run later, after the loop has started.
|
||||||
Schedule a task to run later, after the loop has started.
|
|
||||||
Different from asyncio.ensure_future in that it does not
|
Different from asyncio.ensure_future in that it does not
|
||||||
also return a future, and the actual ensure_future call
|
also return a future, and the actual ensure_future call
|
||||||
is delayed until before server start.
|
is delayed until before server start.
|
||||||
|
|
||||||
:param task: A future, couroutine or awaitable.
|
:param task: future, couroutine or awaitable
|
||||||
"""
|
"""
|
||||||
@self.listener('before_server_start')
|
@self.listener('before_server_start')
|
||||||
def run(app, loop):
|
def run(app, loop):
|
||||||
|
@ -80,10 +79,9 @@ class Sanic:
|
||||||
|
|
||||||
# Decorator
|
# Decorator
|
||||||
def listener(self, event):
|
def listener(self, event):
|
||||||
"""
|
"""Create a listener from a decorated function.
|
||||||
Create a listener from a decorated function.
|
|
||||||
|
|
||||||
:param event: Event to listen to.
|
:param event: event to listen to
|
||||||
"""
|
"""
|
||||||
def decorator(listener):
|
def decorator(listener):
|
||||||
self.listeners[event].append(listener)
|
self.listeners[event].append(listener)
|
||||||
|
@ -92,8 +90,7 @@ class Sanic:
|
||||||
|
|
||||||
# Decorator
|
# Decorator
|
||||||
def route(self, uri, methods=frozenset({'GET'}), host=None):
|
def route(self, uri, methods=frozenset({'GET'}), host=None):
|
||||||
"""
|
"""Decorate a function to be registered as a route
|
||||||
Decorates a function to be registered as a route
|
|
||||||
|
|
||||||
:param uri: path of the URL
|
:param uri: path of the URL
|
||||||
:param methods: list or tuple of methods allowed
|
:param methods: list or tuple of methods allowed
|
||||||
|
@ -136,8 +133,7 @@ class Sanic:
|
||||||
return self.route(uri, methods=frozenset({"DELETE"}), host=host)
|
return self.route(uri, methods=frozenset({"DELETE"}), host=host)
|
||||||
|
|
||||||
def add_route(self, handler, uri, methods=frozenset({'GET'}), host=None):
|
def add_route(self, handler, uri, methods=frozenset({'GET'}), host=None):
|
||||||
"""
|
"""A helper method to register class instance or
|
||||||
A helper method to register class instance or
|
|
||||||
functions as a handler to the application url
|
functions as a handler to the application url
|
||||||
routes.
|
routes.
|
||||||
|
|
||||||
|
@ -168,8 +164,7 @@ class Sanic:
|
||||||
|
|
||||||
# Decorator
|
# Decorator
|
||||||
def exception(self, *exceptions):
|
def exception(self, *exceptions):
|
||||||
"""
|
"""Decorate a function to be registered as a handler for exceptions
|
||||||
Decorates a function to be registered as a handler for exceptions
|
|
||||||
|
|
||||||
:param exceptions: exceptions
|
:param exceptions: exceptions
|
||||||
:return: decorated function
|
:return: decorated function
|
||||||
|
@ -184,9 +179,8 @@ class Sanic:
|
||||||
|
|
||||||
# Decorator
|
# Decorator
|
||||||
def middleware(self, middleware_or_request):
|
def middleware(self, middleware_or_request):
|
||||||
"""
|
"""Decorate and register middleware to be called before a request.
|
||||||
Decorates and registers middleware to be called before a request
|
Can either be called as @app.middleware or @app.middleware('request')
|
||||||
can either be called as @app.middleware or @app.middleware('request')
|
|
||||||
"""
|
"""
|
||||||
def register_middleware(middleware, attach_to='request'):
|
def register_middleware(middleware, attach_to='request'):
|
||||||
if attach_to == 'request':
|
if attach_to == 'request':
|
||||||
|
@ -206,16 +200,14 @@ class Sanic:
|
||||||
# Static Files
|
# Static Files
|
||||||
def static(self, uri, file_or_directory, pattern='.+',
|
def static(self, uri, file_or_directory, pattern='.+',
|
||||||
use_modified_since=True, use_content_range=False):
|
use_modified_since=True, use_content_range=False):
|
||||||
"""
|
"""Register a root to serve files from. The input can either be a
|
||||||
Registers a root to serve files from. The input can either be a file
|
file or a directory. See
|
||||||
or a directory. See
|
|
||||||
"""
|
"""
|
||||||
static_register(self, uri, file_or_directory, pattern,
|
static_register(self, uri, file_or_directory, pattern,
|
||||||
use_modified_since, use_content_range)
|
use_modified_since, use_content_range)
|
||||||
|
|
||||||
def blueprint(self, blueprint, **options):
|
def blueprint(self, blueprint, **options):
|
||||||
"""
|
"""Register a blueprint on the application.
|
||||||
Registers a blueprint on the application.
|
|
||||||
|
|
||||||
:param blueprint: Blueprint object
|
:param blueprint: Blueprint object
|
||||||
:param options: option dictionary with blueprint defaults
|
:param options: option dictionary with blueprint defaults
|
||||||
|
@ -242,7 +234,7 @@ class Sanic:
|
||||||
return self.blueprint(*args, **kwargs)
|
return self.blueprint(*args, **kwargs)
|
||||||
|
|
||||||
def url_for(self, view_name: str, **kwargs):
|
def url_for(self, view_name: str, **kwargs):
|
||||||
"""Builds a URL based on a view name and the values provided.
|
"""Build a URL based on a view name and the values provided.
|
||||||
|
|
||||||
In order to build a URL, all request parameters must be supplied as
|
In order to build a URL, all request parameters must be supplied as
|
||||||
keyword arguments, and each parameter must pass the test for the
|
keyword arguments, and each parameter must pass the test for the
|
||||||
|
@ -252,7 +244,7 @@ class Sanic:
|
||||||
Keyword arguments that are not request parameters will be included in
|
Keyword arguments that are not request parameters will be included in
|
||||||
the output URL's query string.
|
the output URL's query string.
|
||||||
|
|
||||||
:param view_name: A string referencing the view name
|
:param view_name: string referencing the view name
|
||||||
:param **kwargs: keys and values that are used to build request
|
:param **kwargs: keys and values that are used to build request
|
||||||
parameters and query string arguments.
|
parameters and query string arguments.
|
||||||
|
|
||||||
|
@ -342,9 +334,8 @@ class Sanic:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
async def handle_request(self, request, response_callback):
|
async def handle_request(self, request, response_callback):
|
||||||
"""
|
"""Take a request from the HTTP Server and return a response object
|
||||||
Takes a request from the HTTP Server and returns a response object to
|
to be sent back The HTTP Server only expects a response object, so
|
||||||
be sent back The HTTP Server only expects a response object, so
|
|
||||||
exception handling must be done here
|
exception handling must be done here
|
||||||
|
|
||||||
:param request: HTTP Request object
|
:param request: HTTP Request object
|
||||||
|
@ -426,9 +417,8 @@ class Sanic:
|
||||||
after_start=None, before_stop=None, after_stop=None, ssl=None,
|
after_start=None, before_stop=None, after_stop=None, ssl=None,
|
||||||
sock=None, workers=1, loop=None, protocol=HttpProtocol,
|
sock=None, workers=1, loop=None, protocol=HttpProtocol,
|
||||||
backlog=100, stop_event=None, register_sys_signals=True):
|
backlog=100, stop_event=None, register_sys_signals=True):
|
||||||
"""
|
"""Run the HTTP Server and listen until keyboard interrupt or term
|
||||||
Runs the HTTP Server and listens until keyboard interrupt or term
|
signal. On termination, drain connections before closing.
|
||||||
signal. On termination, drains connections before closing.
|
|
||||||
|
|
||||||
:param host: Address to host on
|
:param host: Address to host on
|
||||||
:param port: Port to host on
|
:param port: Port to host on
|
||||||
|
@ -478,9 +468,7 @@ class Sanic:
|
||||||
before_stop=None, after_stop=None, ssl=None,
|
before_stop=None, after_stop=None, ssl=None,
|
||||||
sock=None, loop=None, protocol=HttpProtocol,
|
sock=None, loop=None, protocol=HttpProtocol,
|
||||||
backlog=100, stop_event=None):
|
backlog=100, stop_event=None):
|
||||||
"""
|
"""Asynchronous version of `run`."""
|
||||||
Asynchronous version of `run`.
|
|
||||||
"""
|
|
||||||
server_settings = self._helper(
|
server_settings = self._helper(
|
||||||
host=host, port=port, debug=debug, before_start=before_start,
|
host=host, port=port, debug=debug, before_start=before_start,
|
||||||
after_start=after_start, before_stop=before_stop,
|
after_start=after_start, before_stop=before_stop,
|
||||||
|
@ -501,9 +489,7 @@ class Sanic:
|
||||||
after_stop=None, ssl=None, sock=None, workers=1, loop=None,
|
after_stop=None, ssl=None, sock=None, workers=1, loop=None,
|
||||||
protocol=HttpProtocol, backlog=100, stop_event=None,
|
protocol=HttpProtocol, backlog=100, stop_event=None,
|
||||||
register_sys_signals=True, run_async=False):
|
register_sys_signals=True, run_async=False):
|
||||||
"""
|
"""Helper function used by `run` and `create_server`."""
|
||||||
Helper function used by `run` and `create_server`.
|
|
||||||
"""
|
|
||||||
|
|
||||||
if loop is not None:
|
if loop is not None:
|
||||||
if debug:
|
if debug:
|
||||||
|
|
|
@ -33,8 +33,7 @@ class Signal:
|
||||||
|
|
||||||
|
|
||||||
class CIDict(dict):
|
class CIDict(dict):
|
||||||
"""
|
"""Case Insensitive dict where all keys are converted to lowercase
|
||||||
Case Insensitive dict where all keys are converted to lowercase
|
|
||||||
This does not maintain the inputted case when calling items() or keys()
|
This does not maintain the inputted case when calling items() or keys()
|
||||||
in favor of speed, since headers are case insensitive
|
in favor of speed, since headers are case insensitive
|
||||||
"""
|
"""
|
||||||
|
@ -228,8 +227,8 @@ class HttpProtocol(asyncio.Protocol):
|
||||||
self._total_request_size = 0
|
self._total_request_size = 0
|
||||||
|
|
||||||
def close_if_idle(self):
|
def close_if_idle(self):
|
||||||
"""
|
"""Close the connection if a request is not being sent or received
|
||||||
Close the connection if a request is not being sent or received
|
|
||||||
:return: boolean - True if closed, false if staying open
|
:return: boolean - True if closed, false if staying open
|
||||||
"""
|
"""
|
||||||
if not self.parser:
|
if not self.parser:
|
||||||
|
@ -239,9 +238,8 @@ class HttpProtocol(asyncio.Protocol):
|
||||||
|
|
||||||
|
|
||||||
def update_current_time(loop):
|
def update_current_time(loop):
|
||||||
"""
|
"""Cache the current time, since it is needed at the end of every
|
||||||
Caches the current time, since it is needed
|
keep-alive request to update the request timeout time
|
||||||
at the end of every keep-alive request to update the request timeout time
|
|
||||||
|
|
||||||
:param loop:
|
:param loop:
|
||||||
:return:
|
:return:
|
||||||
|
@ -252,7 +250,8 @@ def update_current_time(loop):
|
||||||
|
|
||||||
|
|
||||||
def trigger_events(events, loop):
|
def trigger_events(events, loop):
|
||||||
"""
|
"""Trigger event callbacks (functions or async)
|
||||||
|
|
||||||
:param events: one or more sync or async functions to execute
|
:param events: one or more sync or async functions to execute
|
||||||
:param loop: event loop
|
:param loop: event loop
|
||||||
"""
|
"""
|
||||||
|
@ -267,31 +266,30 @@ def serve(host, port, request_handler, error_handler, before_start=None,
|
||||||
request_timeout=60, ssl=None, sock=None, request_max_size=None,
|
request_timeout=60, ssl=None, sock=None, request_max_size=None,
|
||||||
reuse_port=False, loop=None, protocol=HttpProtocol, backlog=100,
|
reuse_port=False, loop=None, protocol=HttpProtocol, backlog=100,
|
||||||
register_sys_signals=True, run_async=False):
|
register_sys_signals=True, run_async=False):
|
||||||
"""
|
"""Start asynchronous HTTP Server on an individual process.
|
||||||
Starts asynchronous HTTP Server on an individual process.
|
|
||||||
|
|
||||||
:param host: Address to host on
|
:param host: Address to host on
|
||||||
:param port: Port to host on
|
:param port: Port to host on
|
||||||
:param request_handler: Sanic request handler with middleware
|
:param request_handler: Sanic request handler with middleware
|
||||||
:param error_handler: Sanic error handler with middleware
|
:param error_handler: Sanic error handler with middleware
|
||||||
:param before_start: Function to be executed before the server starts
|
:param before_start: function to be executed before the server starts
|
||||||
listening. Takes arguments `app` instance and `loop`
|
listening. Takes arguments `app` instance and `loop`
|
||||||
:param after_start: Function to be executed after the server starts
|
:param after_start: function to be executed after the server starts
|
||||||
listening. Takes arguments `app` instance and `loop`
|
listening. Takes arguments `app` instance and `loop`
|
||||||
:param before_stop: Function to be executed when a stop signal is
|
:param before_stop: function to be executed when a stop signal is
|
||||||
received before it is respected. Takes arguments
|
received before it is respected. Takes arguments
|
||||||
`app` instance and `loop`
|
`app` instance and `loop`
|
||||||
:param after_stop: Function to be executed when a stop signal is
|
:param after_stop: function to be executed when a stop signal is
|
||||||
received after it is respected. Takes arguments
|
received after it is respected. Takes arguments
|
||||||
`app` instance and `loop`
|
`app` instance and `loop`
|
||||||
:param debug: Enables debug output (slows server)
|
:param debug: enables debug output (slows server)
|
||||||
:param request_timeout: time in seconds
|
:param request_timeout: time in seconds
|
||||||
:param ssl: SSLContext
|
:param ssl: SSLContext
|
||||||
:param sock: Socket for the server to accept connections from
|
:param sock: Socket for the server to accept connections from
|
||||||
:param request_max_size: size in bytes, `None` for no limit
|
:param request_max_size: size in bytes, `None` for no limit
|
||||||
:param reuse_port: `True` for multiple workers
|
:param reuse_port: `True` for multiple workers
|
||||||
:param loop: asyncio compatible event loop
|
:param loop: asyncio compatible event loop
|
||||||
:param protocol: Subclass of asyncio protocol class
|
:param protocol: subclass of asyncio protocol class
|
||||||
:return: Nothing
|
:return: Nothing
|
||||||
"""
|
"""
|
||||||
if not run_async:
|
if not run_async:
|
||||||
|
@ -377,9 +375,8 @@ def serve(host, port, request_handler, error_handler, before_start=None,
|
||||||
|
|
||||||
|
|
||||||
def serve_multiple(server_settings, workers, stop_event=None):
|
def serve_multiple(server_settings, workers, stop_event=None):
|
||||||
"""
|
"""Start multiple server processes simultaneously. Stop on interrupt
|
||||||
Starts multiple server processes simultaneously. Stops on interrupt
|
and terminate signals, and drain connections when complete.
|
||||||
and terminate signals, and drains connections when complete.
|
|
||||||
|
|
||||||
:param server_settings: kw arguments to be passed to the serve function
|
:param server_settings: kw arguments to be passed to the serve function
|
||||||
:param workers: number of workers to launch
|
:param workers: number of workers to launch
|
||||||
|
|
|
@ -18,7 +18,7 @@ def register(app, uri, file_or_directory, pattern,
|
||||||
# make a good effort here. Modified-since is nice, but we could
|
# make a good effort here. Modified-since is nice, but we could
|
||||||
# also look into etags, expires, and caching
|
# also look into etags, expires, and caching
|
||||||
"""
|
"""
|
||||||
Registers a static directory handler with Sanic by adding a route to the
|
Register a static directory handler with Sanic by adding a route to the
|
||||||
router and registering a handler.
|
router and registering a handler.
|
||||||
|
|
||||||
:param app: Sanic
|
:param app: Sanic
|
||||||
|
|
|
@ -21,8 +21,8 @@ async def local_request(method, uri, cookies=None, *args, **kwargs):
|
||||||
|
|
||||||
|
|
||||||
def sanic_endpoint_test(app, method='get', uri='/', gather_request=True,
|
def sanic_endpoint_test(app, method='get', uri='/', gather_request=True,
|
||||||
debug=False, server_kwargs={},
|
debug=False, server_kwargs={}, *request_args,
|
||||||
*request_args, **request_kwargs):
|
**request_kwargs):
|
||||||
results = [None, None]
|
results = [None, None]
|
||||||
exceptions = []
|
exceptions = []
|
||||||
|
|
||||||
|
|
|
@ -3,7 +3,7 @@ from .constants import HTTP_METHODS
|
||||||
|
|
||||||
|
|
||||||
class HTTPMethodView:
|
class HTTPMethodView:
|
||||||
""" Simple class based implementation of view for the sanic.
|
"""Simple class based implementation of view for the sanic.
|
||||||
You should implement methods (get, post, put, patch, delete) for the class
|
You should implement methods (get, post, put, patch, delete) for the class
|
||||||
to every HTTP method you want to support.
|
to every HTTP method you want to support.
|
||||||
|
|
||||||
|
@ -45,9 +45,8 @@ class HTTPMethodView:
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def as_view(cls, *class_args, **class_kwargs):
|
def as_view(cls, *class_args, **class_kwargs):
|
||||||
""" Converts the class into an actual view function that can be used
|
"""Return view function for use with the routing system, that
|
||||||
with the routing system.
|
dispatches request to appropriate handler method.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
def view(*args, **kwargs):
|
def view(*args, **kwargs):
|
||||||
self = view.view_class(*class_args, **class_kwargs)
|
self = view.view_class(*class_args, **class_kwargs)
|
||||||
|
@ -66,7 +65,7 @@ class HTTPMethodView:
|
||||||
|
|
||||||
|
|
||||||
class CompositionView:
|
class CompositionView:
|
||||||
""" Simple method-function mapped view for the sanic.
|
"""Simple method-function mapped view for the sanic.
|
||||||
You can add handler functions to methods (get, post, put, patch, delete)
|
You can add handler functions to methods (get, post, put, patch, delete)
|
||||||
for every HTTP method you want to support.
|
for every HTTP method you want to support.
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue
Block a user