Replaced str.format() method in core functionality (#1819)

* Replaced str.format() method in core functionality

* Fixed linter checks
This commit is contained in:
Mykhailo Yusko 2020-04-06 22:45:25 +03:00 committed by GitHub
parent 78e912ea45
commit 9a39aff803
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 74 additions and 96 deletions

View File

@ -28,12 +28,12 @@ if __name__ == "__main__":
module = import_module(module_name) module = import_module(module_name)
app = getattr(module, app_name, None) app = getattr(module, app_name, None)
app_name = type(app).__name__
if not isinstance(app, Sanic): if not isinstance(app, Sanic):
raise ValueError( raise ValueError(
"Module is not a Sanic app, it is a {}. " f"Module is not a Sanic app, it is a {app_name}. "
"Perhaps you meant {}.app?".format( f"Perhaps you meant {args.module}.app?"
type(app).__name__, args.module
)
) )
if args.cert is not None or args.key is not None: if args.cert is not None or args.key is not None:
ssl = { ssl = {
@ -52,9 +52,9 @@ if __name__ == "__main__":
) )
except ImportError as e: except ImportError as e:
logger.error( logger.error(
"No module named {} found.\n" f"No module named {e.name} found.\n"
" Example File: project/sanic_server.py -> app\n" f" Example File: project/sanic_server.py -> app\n"
" Example Module: project.sanic_server.app".format(e.name) f" Example Module: project.sanic_server.app"
) )
except ValueError: except ValueError:
logger.exception("Failed to run app") logger.exception("Failed to run app")

View File

@ -204,9 +204,11 @@ class Sanic:
args = list(signature(handler).parameters.keys()) args = list(signature(handler).parameters.keys())
if not args: if not args:
handler_name = handler.__name__
raise ValueError( raise ValueError(
"Required parameter `request` missing " f"Required parameter `request` missing "
"in the {0}() route?".format(handler.__name__) f"in the {handler_name}() route?"
) )
if stream: if stream:
@ -800,7 +802,7 @@ class Sanic:
uri, route = self.router.find_route_by_view_name(view_name, **kw) uri, route = self.router.find_route_by_view_name(view_name, **kw)
if not (uri and route): if not (uri and route):
raise URLBuildError( raise URLBuildError(
"Endpoint with name `{}` was not found".format(view_name) f"Endpoint with name `{view_name}` was not found"
) )
# If the route has host defined, split that off # If the route has host defined, split that off
@ -822,7 +824,7 @@ class Sanic:
if filename.startswith("/"): if filename.startswith("/"):
filename = filename[1:] filename = filename[1:]
uri = "{}/{}".format(folder_, filename) uri = f"{folder_}/{filename}"
if uri != "/" and uri.endswith("/"): if uri != "/" and uri.endswith("/"):
uri = uri[:-1] uri = uri[:-1]
@ -858,7 +860,7 @@ class Sanic:
for match in matched_params: for match in matched_params:
name, _type, pattern = self.router.parse_parameter_string(match) name, _type, pattern = self.router.parse_parameter_string(match)
# we only want to match against each individual parameter # we only want to match against each individual parameter
specific_pattern = "^{}$".format(pattern) specific_pattern = f"^{pattern}$"
supplied_param = None supplied_param = None
if name in kwargs: if name in kwargs:
@ -866,9 +868,7 @@ class Sanic:
del kwargs[name] del kwargs[name]
else: else:
raise URLBuildError( raise URLBuildError(
"Required parameter `{}` was not passed to url_for".format( f"Required parameter `{name}` was not passed to url_for"
name
)
) )
supplied_param = str(supplied_param) supplied_param = str(supplied_param)
@ -878,23 +878,22 @@ class Sanic:
if not passes_pattern: if not passes_pattern:
if _type != str: if _type != str:
type_name = _type.__name__
msg = ( msg = (
'Value "{}" for parameter `{}` does not ' f'Value "{supplied_param}" '
"match pattern for type `{}`: {}".format( f"for parameter `{name}` does not "
supplied_param, name, _type.__name__, pattern f"match pattern for type `{type_name}`: {pattern}"
)
) )
else: else:
msg = ( msg = (
'Value "{}" for parameter `{}` ' f'Value "{supplied_param}" for parameter `{name}` '
"does not satisfy pattern {}".format( f"does not satisfy pattern {pattern}"
supplied_param, name, pattern
)
) )
raise URLBuildError(msg) raise URLBuildError(msg)
# replace the parameter in the URL with the supplied value # replace the parameter in the URL with the supplied value
replacement_regex = "(<{}.*?>)".format(name) replacement_regex = f"(<{name}.*?>)"
out = re.sub(replacement_regex, supplied_param, out) out = re.sub(replacement_regex, supplied_param, out)
@ -995,9 +994,8 @@ class Sanic:
) )
elif self.debug: elif self.debug:
response = HTTPResponse( response = HTTPResponse(
"Error while handling error: {}\nStack: {}".format( f"Error while "
e, format_exc() f"handling error: {e}\nStack: {format_exc()}",
),
status=500, status=500,
) )
else: else:
@ -1437,7 +1435,7 @@ class Sanic:
proto = "http" proto = "http"
if ssl is not None: if ssl is not None:
proto = "https" proto = "https"
logger.info("Goin' Fast @ {}://{}:{}".format(proto, host, port)) logger.info(f"Goin' Fast @ {proto}://{host}:{port}")
return server_settings return server_settings

View File

@ -151,7 +151,7 @@ class Blueprint:
future.middleware, future.middleware,
route_names, route_names,
*future.args, *future.args,
**future.kwargs **future.kwargs,
) )
else: else:
app.register_named_middleware(future.middleware, route_names) app.register_named_middleware(future.middleware, route_names)
@ -376,7 +376,7 @@ class Blueprint:
""" """
name = kwargs.pop("name", "static") name = kwargs.pop("name", "static")
if not name.startswith(self.name + "."): if not name.startswith(self.name + "."):
name = "{}.{}".format(self.name, name) name = f"{self.name}.{name}"
kwargs.update(name=name) kwargs.update(name=name)
strict_slashes = kwargs.get("strict_slashes") strict_slashes = kwargs.get("strict_slashes")

View File

@ -51,7 +51,7 @@ class Config(dict):
try: try:
return self[attr] return self[attr]
except KeyError as ke: except KeyError as ke:
raise AttributeError("Config has no '{}'".format(ke.args[0])) raise AttributeError(f"Config has no '{ke.args[0]}'")
def __setattr__(self, attr, value): def __setattr__(self, attr, value):
self[attr] = value self[attr] = value

View File

@ -171,7 +171,7 @@ class Unauthorized(SanicException):
challenge = ", ".join(values) challenge = ", ".join(values)
self.headers = { self.headers = {
"WWW-Authenticate": "{} {}".format(scheme, challenge).rstrip() "WWW-Authenticate": f"{scheme} {challenge}".rstrip()
} }

View File

@ -72,7 +72,7 @@ def kill_process_children_unix(pid):
:param pid: PID of parent process (process ID) :param pid: PID of parent process (process ID)
:return: Nothing :return: Nothing
""" """
root_process_path = "/proc/{pid}/task/{pid}/children".format(pid=pid) root_process_path = f"/proc/{pid}/task/{pid}/children"
if not os.path.isfile(root_process_path): if not os.path.isfile(root_process_path):
return return
with open(root_process_path) as children_list_file: with open(root_process_path) as children_list_file:

View File

@ -130,9 +130,8 @@ class Request:
self.endpoint = None self.endpoint = None
def __repr__(self): def __repr__(self):
return "<{0}: {1} {2}>".format( class_name = self.__class__.__name__
self.__class__.__name__, self.method, self.path return f"<{class_name}: {self.method} {self.path}>"
)
def body_init(self): def body_init(self):
""".. deprecated:: 20.3""" """.. deprecated:: 20.3"""
@ -527,7 +526,7 @@ class Request:
): ):
netloc = host netloc = host
else: else:
netloc = "{}:{}".format(host, port) netloc = f"{host}:{port}"
return self.app.url_for( return self.app.url_for(
view_name, _external=True, _scheme=scheme, _server=netloc, **kwargs view_name, _external=True, _scheme=scheme, _server=netloc, **kwargs

View File

@ -299,7 +299,7 @@ async def file(
out_stream = await f.read(_range.size) out_stream = await f.read(_range.size)
headers[ headers[
"Content-Range" "Content-Range"
] = "bytes {0.start}-{0.end}/{0.total}".format(_range) ] = f"bytes {_range.start}-{_range.end}/{_range.total}"
status = 206 status = 206
else: else:
out_stream = await f.read() out_stream = await f.read()
@ -341,9 +341,11 @@ async def file_stream(
filename = filename or path.split(location)[-1] filename = filename or path.split(location)[-1]
mime_type = mime_type or guess_type(filename)[0] or "text/plain" mime_type = mime_type or guess_type(filename)[0] or "text/plain"
if _range: if _range:
headers["Content-Range"] = "bytes {0.start}-{0.end}/{0.total}".format( start = _range.start
_range end = _range.end
) total = _range.total
headers["Content-Range"] = f"bytes {start}-{end}/{total}"
status = 206 status = 206
async def _streaming_fn(response): async def _streaming_fn(response):

View File

@ -109,7 +109,7 @@ class Router:
name, pattern = parameter_string.split(":", 1) name, pattern = parameter_string.split(":", 1)
if not name: if not name:
raise ValueError( raise ValueError(
"Invalid parameter syntax: {}".format(parameter_string) f"Invalid parameter syntax: {parameter_string}"
) )
default = (str, pattern) default = (str, pattern)
@ -143,7 +143,7 @@ class Router:
routes = [] routes = []
if version is not None: if version is not None:
version = re.escape(str(version).strip("/").lstrip("v")) version = re.escape(str(version).strip("/").lstrip("v"))
uri = "/".join(["/v{}".format(version), uri.lstrip("/")]) uri = "/".join([f"/v{version}", uri.lstrip("/")])
# add regular version # add regular version
routes.append(self._add(uri, methods, handler, host, name)) routes.append(self._add(uri, methods, handler, host, name))
@ -203,8 +203,8 @@ class Router:
else: else:
if not isinstance(host, Iterable): if not isinstance(host, Iterable):
raise ValueError( raise ValueError(
"Expected either string or Iterable of " f"Expected either string or Iterable of "
"host strings, not {!r}".format(host) f"host strings, not {host!r}"
) )
for host_ in host: for host_ in host:
@ -225,8 +225,7 @@ class Router:
if name in parameter_names: if name in parameter_names:
raise ParameterNameConflicts( raise ParameterNameConflicts(
"Multiple parameter named <{name}> " f"Multiple parameter named <{name}> " f"in route uri {uri}"
"in route uri {uri}".format(name=name, uri=uri)
) )
parameter_names.add(name) parameter_names.add(name)
@ -240,23 +239,23 @@ class Router:
elif re.search(r"/", pattern): elif re.search(r"/", pattern):
properties["unhashable"] = True properties["unhashable"] = True
return "({})".format(pattern) return f"({pattern})"
pattern_string = re.sub(self.parameter_pattern, add_parameter, uri) pattern_string = re.sub(self.parameter_pattern, add_parameter, uri)
pattern = re.compile(r"^{}$".format(pattern_string)) pattern = re.compile(fr"^{pattern_string}$")
def merge_route(route, methods, handler): def merge_route(route, methods, handler):
# merge to the existing route when possible. # merge to the existing route when possible.
if not route.methods or not methods: if not route.methods or not methods:
# method-unspecified routes are not mergeable. # method-unspecified routes are not mergeable.
raise RouteExists("Route already registered: {}".format(uri)) raise RouteExists(f"Route already registered: {uri}")
elif route.methods.intersection(methods): elif route.methods.intersection(methods):
# already existing method is not overloadable. # already existing method is not overloadable.
duplicated = methods.intersection(route.methods) duplicated = methods.intersection(route.methods)
duplicated_methods = ",".join(list(duplicated))
raise RouteExists( raise RouteExists(
"Route already registered: {} [{}]".format( f"Route already registered: {uri} [{duplicated_methods}]"
uri, ",".join(list(duplicated))
)
) )
if isinstance(route.handler, CompositionView): if isinstance(route.handler, CompositionView):
view = route.handler view = route.handler
@ -296,9 +295,9 @@ class Router:
name = name.split("_static_", 1)[-1] name = name.split("_static_", 1)[-1]
if hasattr(handler, "__blueprintname__"): if hasattr(handler, "__blueprintname__"):
handler_name = "{}.{}".format( bp_name = handler.__blueprintname__
handler.__blueprintname__, name or handler.__name__
) handler_name = f"{bp_name}.{name or handler.__name__}"
else: else:
handler_name = name or getattr(handler, "__name__", None) handler_name = name or getattr(handler, "__name__", None)
@ -411,7 +410,7 @@ class Router:
# Check against known static routes # Check against known static routes
route = self.routes_static.get(url) route = self.routes_static.get(url)
method_not_supported = MethodNotSupported( method_not_supported = MethodNotSupported(
"Method {} not allowed for URL {}".format(method, url), f"Method {method} not allowed for URL {url}",
method=method, method=method,
allowed_methods=self.get_supported_methods(url), allowed_methods=self.get_supported_methods(url),
) )
@ -441,7 +440,7 @@ class Router:
# Route was found but the methods didn't match # Route was found but the methods didn't match
if route_found: if route_found:
raise method_not_supported raise method_not_supported
raise NotFound("Requested URL {} not found".format(url)) raise NotFound(f"Requested URL {url} not found")
kwargs = { kwargs = {
p.name: p.cast(value) p.name: p.cast(value)

View File

@ -114,7 +114,7 @@ class HttpProtocol(asyncio.Protocol):
router=None, router=None,
state=None, state=None,
debug=False, debug=False,
**kwargs **kwargs,
): ):
self.loop = loop self.loop = loop
self.app = app self.app = app
@ -349,9 +349,7 @@ class HttpProtocol(asyncio.Protocol):
self.transport.write(b"HTTP/1.1 100 Continue\r\n\r\n") self.transport.write(b"HTTP/1.1 100 Continue\r\n\r\n")
else: else:
self.write_error( self.write_error(
HeaderExpectationFailed( HeaderExpectationFailed(f"Unknown Expect: {expect}")
"Unknown Expect: {expect}".format(expect=expect)
)
) )
def on_body(self, body): def on_body(self, body):
@ -458,13 +456,9 @@ class HttpProtocol(asyncio.Protocol):
extra["host"] = "UNKNOWN" extra["host"] = "UNKNOWN"
if self.request is not None: if self.request is not None:
if self.request.ip: if self.request.ip:
extra["host"] = "{0}:{1}".format( extra["host"] = f"{self.request.ip}:{self.request.port}"
self.request.ip, self.request.port
)
extra["request"] = "{0} {1}".format( extra["request"] = f"{self.request.method} {self.request.url}"
self.request.method, self.request.url
)
else: else:
extra["request"] = "nil" extra["request"] = "nil"
@ -501,9 +495,7 @@ class HttpProtocol(asyncio.Protocol):
) )
keep_alive = False keep_alive = False
except Exception as e: except Exception as e:
self.bail_out( self.bail_out(f"Writing response failed, connection closed {e!r}")
"Writing response failed, connection closed {}".format(repr(e))
)
finally: finally:
if not keep_alive: if not keep_alive:
self.transport.close() self.transport.close()
@ -554,9 +546,7 @@ class HttpProtocol(asyncio.Protocol):
) )
keep_alive = False keep_alive = False
except Exception as e: except Exception as e:
self.bail_out( self.bail_out(f"Writing response failed, connection closed {e!r}")
"Writing response failed, connection closed {}".format(repr(e))
)
finally: finally:
if not keep_alive: if not keep_alive:
self.transport.close() self.transport.close()
@ -587,7 +577,7 @@ class HttpProtocol(asyncio.Protocol):
) )
except Exception as e: except Exception as e:
self.bail_out( self.bail_out(
"Writing error failed, connection closed {}".format(repr(e)), f"Writing error failed, connection closed {e!r}",
from_error=True, from_error=True,
) )
finally: finally:
@ -902,7 +892,7 @@ def serve(
reuse_port=reuse_port, reuse_port=reuse_port,
sock=sock, sock=sock,
backlog=backlog, backlog=backlog,
**asyncio_server_kwargs **asyncio_server_kwargs,
) )
if run_async: if run_async:

View File

@ -134,7 +134,7 @@ def register(
# special prefix for static files # special prefix for static files
if not name.startswith("_static_"): if not name.startswith("_static_"):
name = "_static_{}".format(name) name = f"_static_{name}"
app.route( app.route(
uri, uri,

View File

@ -110,11 +110,9 @@ class SanicTestClient:
): ):
url = uri url = uri
else: else:
uri = uri if uri.startswith("/") else "/{uri}".format(uri=uri) uri = uri if uri.startswith("/") else f"/{uri}"
scheme = "ws" if method == "websocket" else "http" scheme = "ws" if method == "websocket" else "http"
url = "{scheme}://{host}:{port}{uri}".format( url = f"{scheme}://{host}:{port}{uri}"
scheme=scheme, host=host, port=port, uri=uri
)
# Tests construct URLs using PORT = None, which means random port not # Tests construct URLs using PORT = None, which means random port not
# known until this function is called, so fix that here # known until this function is called, so fix that here
url = url.replace(":None/", f":{port}/") url = url.replace(":None/", f":{port}/")
@ -135,7 +133,7 @@ class SanicTestClient:
self.app.listeners["after_server_start"].pop() self.app.listeners["after_server_start"].pop()
if exceptions: if exceptions:
raise ValueError("Exception during request: {}".format(exceptions)) raise ValueError(f"Exception during request: {exceptions}")
if gather_request: if gather_request:
try: try:
@ -143,17 +141,13 @@ class SanicTestClient:
return request, response return request, response
except BaseException: # noqa except BaseException: # noqa
raise ValueError( raise ValueError(
"Request and response object expected, got ({})".format( f"Request and response object expected, got ({results})"
results
)
) )
else: else:
try: try:
return results[-1] return results[-1]
except BaseException: # noqa except BaseException: # noqa
raise ValueError( raise ValueError(f"Request object expected, got ({results})")
"Request object expected, got ({})".format(results)
)
def get(self, *args, **kwargs): def get(self, *args, **kwargs):
return self._sanic_endpoint_test("get", *args, **kwargs) return self._sanic_endpoint_test("get", *args, **kwargs)
@ -199,7 +193,7 @@ class SanicASGITestClient(httpx.AsyncClient):
def __init__( def __init__(
self, self,
app, app,
base_url: str = "http://{}".format(ASGI_HOST), base_url: str = f"http://{ASGI_HOST}",
suppress_exceptions: bool = False, suppress_exceptions: bool = False,
) -> None: ) -> None:
app.__class__.__call__ = app_call_with_return app.__class__.__call__ = app_call_with_return
@ -230,7 +224,7 @@ class SanicASGITestClient(httpx.AsyncClient):
async def websocket(self, uri, subprotocols=None, *args, **kwargs): async def websocket(self, uri, subprotocols=None, *args, **kwargs):
scheme = "ws" scheme = "ws"
path = uri path = uri
root_path = "{}://{}".format(scheme, ASGI_HOST) root_path = f"{scheme}://{ASGI_HOST}"
headers = kwargs.get("headers", {}) headers = kwargs.get("headers", {})
headers.setdefault("connection", "upgrade") headers.setdefault("connection", "upgrade")

View File

@ -96,14 +96,10 @@ class CompositionView:
handler.is_stream = stream handler.is_stream = stream
for method in methods: for method in methods:
if method not in HTTP_METHODS: if method not in HTTP_METHODS:
raise InvalidUsage( raise InvalidUsage(f"{method} is not a valid HTTP method.")
"{} is not a valid HTTP method.".format(method)
)
if method in self.handlers: if method in self.handlers:
raise InvalidUsage( raise InvalidUsage(f"Method {method} is already registered.")
"Method {} is already registered.".format(method)
)
self.handlers[method] = handler self.handlers[method] = handler
def __call__(self, request, *args, **kwargs): def __call__(self, request, *args, **kwargs):