resolve conflicts
This commit is contained in:
35
sanic/app.py
35
sanic/app.py
@@ -345,13 +345,13 @@ class Sanic:
|
||||
# Static Files
|
||||
def static(self, uri, file_or_directory, pattern=r'/?.+',
|
||||
use_modified_since=True, use_content_range=False,
|
||||
stream_large_files=False):
|
||||
stream_large_files=False, name='static'):
|
||||
"""Register a root to serve files from. The input can either be a
|
||||
file or a directory. See
|
||||
"""
|
||||
static_register(self, uri, file_or_directory, pattern,
|
||||
use_modified_since, use_content_range,
|
||||
stream_large_files)
|
||||
stream_large_files, name)
|
||||
|
||||
def blueprint(self, blueprint, **options):
|
||||
"""Register a blueprint on the application.
|
||||
@@ -401,12 +401,32 @@ class Sanic:
|
||||
URLBuildError
|
||||
"""
|
||||
# find the route by the supplied view name
|
||||
uri, route = self.router.find_route_by_view_name(view_name)
|
||||
kw = {}
|
||||
# special static files url_for
|
||||
if view_name == 'static':
|
||||
kw.update(name=kwargs.pop('name', 'static'))
|
||||
elif view_name.endswith('.static'): # blueprint.static
|
||||
kwargs.pop('name', None)
|
||||
kw.update(name=view_name)
|
||||
|
||||
if not uri or not route:
|
||||
uri, route = self.router.find_route_by_view_name(view_name, **kw)
|
||||
if not (uri and route):
|
||||
raise URLBuildError('Endpoint with name `{}` was not found'.format(
|
||||
view_name))
|
||||
|
||||
if view_name == 'static' or view_name.endswith('.static'):
|
||||
filename = kwargs.pop('filename', None)
|
||||
# it's static folder
|
||||
if '<file_uri:' in uri:
|
||||
folder_ = uri.split('<file_uri:', 1)[0]
|
||||
if folder_.endswith('/'):
|
||||
folder_ = folder_[:-1]
|
||||
|
||||
if filename.startswith('/'):
|
||||
filename = filename[1:]
|
||||
|
||||
uri = '{}/{}'.format(folder_, filename)
|
||||
|
||||
if uri != '/' and uri.endswith('/'):
|
||||
uri = uri[:-1]
|
||||
|
||||
@@ -429,6 +449,13 @@ class Sanic:
|
||||
if netloc is None and external:
|
||||
netloc = self.config.get('SERVER_NAME', '')
|
||||
|
||||
if external:
|
||||
if not scheme:
|
||||
scheme = netloc[:8].split(':', 1)[0]
|
||||
|
||||
if '://' in netloc[:8]:
|
||||
netloc = netloc.split('://', 1)[-1]
|
||||
|
||||
for match in matched_params:
|
||||
name, _type, pattern = self.router.parse_parameter_string(
|
||||
match)
|
||||
|
||||
@@ -218,6 +218,11 @@ class Blueprint:
|
||||
:param uri: endpoint at which the route will be accessible.
|
||||
:param file_or_directory: Static asset.
|
||||
"""
|
||||
name = kwargs.pop('name', 'static')
|
||||
if not name.startswith(self.name + '.'):
|
||||
name = '{}.{}'.format(self.name, name)
|
||||
|
||||
kwargs.update(name=name)
|
||||
static = FutureStatic(uri, file_or_directory, args, kwargs)
|
||||
self.statics.append(static)
|
||||
|
||||
|
||||
@@ -56,6 +56,7 @@ ALL_STATUS_CODES = {
|
||||
415: b'Unsupported Media Type',
|
||||
416: b'Requested Range Not Satisfiable',
|
||||
417: b'Expectation Failed',
|
||||
418: b'I\'m a teapot',
|
||||
422: b'Unprocessable Entity',
|
||||
423: b'Locked',
|
||||
424: b'Failed Dependency',
|
||||
@@ -63,6 +64,7 @@ ALL_STATUS_CODES = {
|
||||
428: b'Precondition Required',
|
||||
429: b'Too Many Requests',
|
||||
431: b'Request Header Fields Too Large',
|
||||
451: b'Unavailable For Legal Reasons',
|
||||
500: b'Internal Server Error',
|
||||
501: b'Not Implemented',
|
||||
502: b'Bad Gateway',
|
||||
|
||||
@@ -68,6 +68,7 @@ class Router:
|
||||
def __init__(self):
|
||||
self.routes_all = {}
|
||||
self.routes_names = {}
|
||||
self.routes_static_files = {}
|
||||
self.routes_static = {}
|
||||
self.routes_dynamic = defaultdict(list)
|
||||
self.routes_always_check = []
|
||||
@@ -148,6 +149,7 @@ class Router:
|
||||
provided, any method is allowed
|
||||
:param handler: request handler function.
|
||||
When executed, it should provide a response object.
|
||||
:param name: user defined route name for url_for
|
||||
:return: Nothing
|
||||
"""
|
||||
if host is not None:
|
||||
@@ -231,6 +233,12 @@ class Router:
|
||||
|
||||
# prefix the handler name with the blueprint name
|
||||
# if available
|
||||
# special prefix for static files
|
||||
is_static = False
|
||||
if name and name.startswith('_static_'):
|
||||
is_static = True
|
||||
name = name.split('_static_', 1)[-1]
|
||||
|
||||
if hasattr(handler, '__blueprintname__'):
|
||||
handler_name = '{}.{}'.format(
|
||||
handler.__blueprintname__, name or handler.__name__)
|
||||
@@ -245,9 +253,15 @@ class Router:
|
||||
parameters=parameters, name=handler_name, uri=uri)
|
||||
|
||||
self.routes_all[uri] = route
|
||||
pairs = self.routes_names.get(handler_name)
|
||||
if not (pairs and (pairs[0] + '/' == uri or uri + '/' == pairs[0])):
|
||||
self.routes_names[handler_name] = (uri, route)
|
||||
if is_static:
|
||||
pair = self.routes_static_files.get(handler_name)
|
||||
if not (pair and (pair[0] + '/' == uri or uri + '/' == pair[0])):
|
||||
self.routes_static_files[handler_name] = (uri, route)
|
||||
|
||||
else:
|
||||
pair = self.routes_names.get(handler_name)
|
||||
if not (pair and (pair[0] + '/' == uri or uri + '/' == pair[0])):
|
||||
self.routes_names[handler_name] = (uri, route)
|
||||
|
||||
if properties['unhashable']:
|
||||
self.routes_always_check.append(route)
|
||||
@@ -274,6 +288,11 @@ class Router:
|
||||
self.routes_names.pop(handler_name)
|
||||
break
|
||||
|
||||
for handler_name, pairs in self.routes_static_files.items():
|
||||
if pairs[0] == uri:
|
||||
self.routes_static_files.pop(handler_name)
|
||||
break
|
||||
|
||||
except KeyError:
|
||||
raise RouteDoesNotExist("Route was not registered: {}".format(uri))
|
||||
|
||||
@@ -289,15 +308,19 @@ class Router:
|
||||
self._get.cache_clear()
|
||||
|
||||
@lru_cache(maxsize=ROUTER_CACHE_SIZE)
|
||||
def find_route_by_view_name(self, 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)
|
||||
"""
|
||||
if not view_name:
|
||||
return (None, None)
|
||||
|
||||
if view_name == 'static' or view_name.endswith('.static'):
|
||||
return self.routes_static_files.get(name, (None, None))
|
||||
|
||||
return self.routes_names.get(view_name, (None, None))
|
||||
|
||||
def get(self, request):
|
||||
|
||||
@@ -189,10 +189,12 @@ class HttpProtocol(asyncio.Protocol):
|
||||
and int(value) > self.request_max_size:
|
||||
exception = PayloadTooLarge('Payload Too Large')
|
||||
self.write_error(exception)
|
||||
|
||||
try:
|
||||
value = value.decode()
|
||||
except UnicodeDecodeError:
|
||||
value = value.decode('latin_1')
|
||||
self.headers.append(
|
||||
(self._header_fragment.decode().casefold(),
|
||||
value.decode()))
|
||||
(self._header_fragment.decode().casefold(), value))
|
||||
|
||||
self._header_fragment = b''
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ from sanic.response import file, file_stream, HTTPResponse
|
||||
|
||||
def register(app, uri, file_or_directory, pattern,
|
||||
use_modified_since, use_content_range,
|
||||
stream_large_files):
|
||||
stream_large_files, name='static'):
|
||||
# TODO: Though sanic is not a file server, I feel like we should at least
|
||||
# make a good effort here. Modified-since is nice, but we could
|
||||
# also look into etags, expires, and caching
|
||||
@@ -39,6 +39,7 @@ def register(app, uri, file_or_directory, pattern,
|
||||
than the file() handler to send the file
|
||||
If this is an integer, this represents the
|
||||
threshold size to switch to file_stream()
|
||||
:param name: user defined name used for url_for
|
||||
"""
|
||||
# If we're not trying to match a file directly,
|
||||
# serve from the folder
|
||||
@@ -117,4 +118,8 @@ def register(app, uri, file_or_directory, pattern,
|
||||
path=file_or_directory,
|
||||
relative_url=file_uri)
|
||||
|
||||
app.route(uri, methods=['GET', 'HEAD'])(_handler)
|
||||
# special prefix for static files
|
||||
if not name.startswith('_static_'):
|
||||
name = '_static_{}'.format(name)
|
||||
|
||||
app.route(uri, methods=['GET', 'HEAD'], name=name)(_handler)
|
||||
|
||||
Reference in New Issue
Block a user