improve url_for to support multi values for one arg, add _anchor/_external/_scheme options

This commit is contained in:
lixxu
2017-02-09 16:44:23 +08:00
parent 7401facc21
commit cf2a363e5e
3 changed files with 58 additions and 9 deletions

View File

@@ -230,6 +230,16 @@ class Sanic:
matched_params = re.findall(
self.router.parameter_pattern, uri)
# _method is only a placeholder now, don't know how to support it
kwargs.pop('_method', None)
anchor = kwargs.pop('_anchor', '')
# _external need SERVER_NAME in config or pass _server arg
external = kwargs.pop('_external', False)
scheme = kwargs.pop('_scheme', '')
if scheme and not external:
raise ValueError('When specifying _scheme, _external must be True')
netloc = kwargs.pop('_server', self.config.get('SERVER_NAME', ''))
for match in matched_params:
name, _type, pattern = self.router.parse_parameter_string(
match)
@@ -271,11 +281,9 @@ class Sanic:
# parse the remainder of the keyword arguments into a querystring
if kwargs:
query_string = urlencode(kwargs)
out = urlunparse((
'', '', out,
'', query_string, ''
))
query_string = urlencode(kwargs, doseq=True)
# scheme://netloc/path;parameters?query#fragment
out = urlunparse((scheme, netloc, out, '', query_string, anchor))
return out

View File

@@ -6,7 +6,11 @@ PORT = 42101
async def local_request(method, uri, cookies=None, *args, **kwargs):
url = 'http://{host}:{port}{uri}'.format(host=HOST, port=PORT, uri=uri)
if uri.startswith(('http:', 'https:', 'ftp:', 'ftps://' '//')):
url = uri
else:
url = 'http://{host}:{port}{uri}'.format(host=HOST, port=PORT, uri=uri)
log.info(url)
async with aiohttp.ClientSession(cookies=cookies) as session:
async with getattr(