-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Sourcery Starbot ⭐ refactored Alc-Alc/starlite #1
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -48,12 +48,7 @@ async def retrieve_user_handler(token: "Token", connection: "ASGIConnection[Any, | |
@post("/login") | ||
async def login_handler(data: "User") -> "Response[User]": | ||
MOCK_DB[str(data.id)] = data | ||
response = jwt_cookie_auth.login(identifier=str(data.id), response_body=data) | ||
|
||
# you can do whatever you want to update the response instance here | ||
# e.g. response.set_cookie(...) | ||
|
||
return response | ||
return jwt_cookie_auth.login(identifier=str(data.id), response_body=data) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
This removes the following comments ( why? ):
|
||
|
||
|
||
# We also have some other routes, for example: | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -48,26 +48,14 @@ async def retrieve_user_handler(token: "Token", connection: "ASGIConnection[Any, | |
@post("/login") | ||
async def login_handler(request: "Request[Any, Any, Any]", data: "User") -> "Response[OAuth2Login]": | ||
MOCK_DB[str(data.id)] = data | ||
# if we do not define a response body, the login process will return a standard OAuth2 login response. Note the `Response[OAuth2Login]` return type. | ||
response = oauth2_auth.login(identifier=str(data.id)) | ||
|
||
# you can do whatever you want to update the response instance here | ||
# e.g. response.set_cookie(...) | ||
|
||
return response | ||
return oauth2_auth.login(identifier=str(data.id)) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
This removes the following comments ( why? ):
|
||
|
||
|
||
@post("/login_custom") | ||
async def login_custom_response_handler(data: "User") -> "Response[User]": | ||
MOCK_DB[str(data.id)] = data | ||
|
||
# If you'd like to define a custom response body, use the `response_body` parameter. Note the `Response[User]` return type. | ||
response = oauth2_auth.login(identifier=str(data.id), response_body=data) | ||
|
||
# you can do whatever you want to update the response instance here | ||
# e.g. response.set_cookie(...) | ||
|
||
return response | ||
return oauth2_auth.login(identifier=str(data.id), response_body=data) | ||
Comment on lines
-64
to
+58
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
This removes the following comments ( why? ):
|
||
|
||
|
||
# We also have some other routes, for example: | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -26,7 +26,7 @@ async def get_user( | |
token: str = Parameter(header="X-API-KEY"), | ||
cookie: str = Parameter(cookie="my-cookie-param"), | ||
) -> User: | ||
if not (token == VALID_TOKEN and cookie == VALID_COOKIE_VALUE): | ||
if token != VALID_TOKEN or cookie != VALID_COOKIE_VALUE: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
raise NotAuthorizedException | ||
return User.parse_obj(USER_DB[user_id]) | ||
|
||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -55,10 +55,10 @@ async def get_company(company_id: int, async_session: AsyncSession) -> Company: | |
If a company with that ID does not exist, return a 404 response | ||
""" | ||
result = await async_session.scalars(select(Company).where(Company.id == company_id)) | ||
company: Optional[Company] = result.one_or_none() | ||
if not company: | ||
if company := result.one_or_none(): | ||
return company | ||
else: | ||
raise HTTPException(detail=f"Company with ID {company_id} not found", status_code=HTTP_404_NOT_FOUND) | ||
return company | ||
Comment on lines
-58
to
-61
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
|
||
|
||
app = Starlite( | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -46,10 +46,12 @@ def get_user(user_id: int, db_session: Session) -> User: | |
|
||
If a user with that ID does not exist, return a 404 response | ||
""" | ||
user: Optional[User] = db_session.scalars(select(User).where(User.id == user_id)).one_or_none() | ||
if not user: | ||
if user := db_session.scalars( | ||
select(User).where(User.id == user_id) | ||
).one_or_none(): | ||
return user | ||
else: | ||
raise HTTPException(detail=f"User with ID {user} not found", status_code=HTTP_404_NOT_FOUND) | ||
return user | ||
Comment on lines
-49
to
-52
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
|
||
|
||
app = Starlite( | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -64,10 +64,12 @@ def get_user(user_id: int, db_session: Session) -> UserModel: | |
|
||
If a user with that ID does not exist, return a 404 response | ||
""" | ||
user: Optional[User] = db_session.scalars(select(User).where(User.id == user_id)).one_or_none() | ||
if not user: | ||
if user := db_session.scalars( | ||
select(User).where(User.id == user_id) | ||
).one_or_none(): | ||
return UserModel.from_orm(user) | ||
else: | ||
raise HTTPException(detail=f"User with ID {user} not found", status_code=HTTP_404_NOT_FOUND) | ||
return UserModel.from_orm(user) | ||
Comment on lines
-67
to
-70
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
|
||
|
||
app = Starlite( | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -50,10 +50,12 @@ def get_company(company_id: str, db_session: Session) -> Company: | |
|
||
If a company with that ID does not exist, return a 404 response | ||
""" | ||
company: Optional[Company] = db_session.scalars(select(Company).where(Company.id == company_id)).one_or_none() | ||
if not company: | ||
if company := db_session.scalars( | ||
select(Company).where(Company.id == company_id) | ||
).one_or_none(): | ||
return company | ||
else: | ||
raise HTTPException(detail=f"Company with ID {company_id} not found", status_code=HTTP_404_NOT_FOUND) | ||
return company | ||
Comment on lines
-53
to
-56
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
|
||
|
||
app = Starlite( | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -56,13 +56,7 @@ class UserLoginPayload(BaseModel): | |
async def retrieve_user_handler( | ||
session: Dict[str, Any], connection: "ASGIConnection[Any, Any, Any, Any]" | ||
) -> Optional[User]: | ||
# we retrieve the user instance based on session data | ||
|
||
user_id = session.get("user_id") | ||
if user_id: | ||
return MOCK_DB.get(user_id) | ||
|
||
return None | ||
return MOCK_DB.get(user_id) if (user_id := session.get("user_id")) else None | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
This removes the following comments ( why? ):
|
||
|
||
|
||
@post("/login") | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -85,10 +85,11 @@ def add_route_to_trie( | |
""" | ||
current_node = root_node | ||
|
||
is_mount = hasattr(route, "route_handler") and getattr(route.route_handler, "is_mount", False) # pyright: ignore | ||
has_path_parameters = bool(route.path_parameters) | ||
|
||
if is_mount: # pyright: ignore | ||
if is_mount := hasattr(route, "route_handler") and getattr( | ||
route.route_handler, "is_mount", False | ||
): | ||
Comment on lines
-88
to
+92
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
This removes the following comments ( why? ):
|
||
current_node = add_mount_route( | ||
current_node=current_node, | ||
mount_routes=mount_routes, | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -143,7 +143,9 @@ def parse_path_to_route( | |
remaining_path = path[match.end() :] | ||
# since we allow regular handlers under static paths, we must validate that the request does not match | ||
# any such handler. | ||
if not mount_node.children or not any(sub_route in path for sub_route in mount_node.children): # type: ignore | ||
if not mount_node.children or all( | ||
sub_route not in path for sub_route in mount_node.children | ||
): # type: ignore | ||
Comment on lines
-146
to
+148
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
asgi_app, handler = parse_node_handlers(node=mount_node, method=method) | ||
remaining_path = remaining_path or "/" | ||
if not mount_node.is_static: | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -31,8 +31,7 @@ def validate_node(node: RouteTrieNode) -> None: | |
node.is_mount | ||
and node.children | ||
and any( | ||
v | ||
for v in chain.from_iterable( | ||
chain.from_iterable( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
list(child.path_parameters.values()) | ||
if isinstance(child.path_parameters, dict) | ||
else child.path_parameters | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -453,8 +453,11 @@ def _validate_raw_kwargs( | |
f"Make sure to use distinct keys for your dependencies, path parameters and aliased parameters." | ||
) | ||
|
||
used_reserved_kwargs = {*parameter_names, *path_parameters, *dependency_keys}.intersection(RESERVED_KWARGS) | ||
if used_reserved_kwargs: | ||
if used_reserved_kwargs := { | ||
*parameter_names, | ||
*path_parameters, | ||
*dependency_keys, | ||
}.intersection(RESERVED_KWARGS): | ||
Comment on lines
-456
to
+460
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
raise ImproperlyConfiguredException( | ||
f"Reserved kwargs ({', '.join(RESERVED_KWARGS)}) cannot be used for dependencies and parameter arguments. " | ||
f"The following kwargs have been used: {', '.join(used_reserved_kwargs)}" | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -60,7 +60,9 @@ def create_parameter_definition( | |
field_alias=field_alias, | ||
default_value=default_value, | ||
is_required=signature_field.is_required | ||
and (default_value is None and not (signature_field.is_optional or signature_field.is_any)), | ||
and default_value is None | ||
and not signature_field.is_optional | ||
and not signature_field.is_any, | ||
Comment on lines
-63
to
+65
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
is_sequence=signature_field.is_non_string_sequence, | ||
) | ||
|
||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -123,7 +123,7 @@ def parse_multipart_form(body: bytes, boundary: bytes, multipart_form_part_limit | |
line_index = line_end_index + 2 | ||
colon_index = form_line.index(":") | ||
current_idx = colon_index + 2 | ||
form_header_field = form_line[0:colon_index].lower() | ||
form_header_field = form_line[:colon_index].lower() | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
form_header_value, form_parameters = parse_content_header(form_line[current_idx:]) | ||
|
||
if form_header_field == "content-disposition": | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -12,7 +12,6 @@ | |
if TYPE_CHECKING: | ||
from starlite.plugins import OpenAPISchemaPluginProtocol | ||
|
||
if TYPE_CHECKING: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Lines
|
||
from starlite._signature.models import SignatureField | ||
|
||
try: | ||
|
@@ -158,10 +157,7 @@ def create_collection_constrained_field_schema( | |
create_schema(field=sub_field, generate_examples=False, plugins=plugins, schemas=schemas) | ||
for sub_field in children | ||
] | ||
if len(items) > 1: | ||
schema.items = Schema(one_of=items) | ||
else: | ||
schema.items = items[0] | ||
schema.items = Schema(one_of=items) if len(items) > 1 else items[0] | ||
Comment on lines
-161
to
+160
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
else: | ||
from starlite._signature.models import SignatureField | ||
|
||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -50,12 +50,14 @@ def normalize_typescript_namespace(value: str, allow_quoted: bool) -> str: | |
Returns: | ||
A normalized value | ||
""" | ||
if not allow_quoted and not (value[0].isalpha() or value[0] in {"_", "$"}): | ||
if ( | ||
not allow_quoted | ||
and not value[0].isalpha() | ||
and value[0] not in {"_", "$"} | ||
): | ||
raise ValueError(f"invalid typescript namespace {value}") | ||
if allow_quoted: | ||
if allowed_key_re.fullmatch(value): | ||
return value | ||
return f'"{value}"' | ||
return value if allowed_key_re.fullmatch(value) else f'"{value}"' | ||
Comment on lines
-53
to
+60
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
return invalid_namespace_re.sub("", value) | ||
|
||
|
||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -24,15 +24,12 @@ | |
|
||
def _as_string(value: Any) -> str: | ||
if isinstance(value, str): | ||
return '"' + value + '"' | ||
return f'"{value}"' | ||
|
||
if isinstance(value, bool): | ||
return "true" if value else "false" | ||
|
||
if value is None: | ||
return "null" | ||
|
||
return str(value) | ||
return "null" if value is None else str(value) | ||
Comment on lines
-27
to
+32
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
|
||
|
||
class TypeScriptElement(ABC): | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -48,10 +48,14 @@ def parse_cookie_string(cookie_string: str) -> dict[str, str]: | |
Returns: | ||
A string keyed dictionary of values | ||
""" | ||
output: dict[str, str] = {} | ||
cookies = [cookie.split("=", 1) if "=" in cookie else ("", cookie) for cookie in cookie_string.split(";")] | ||
for k, v in filter(lambda x: x[0] or x[1], ((k.strip(), v.strip()) for k, v in cookies)): | ||
output[k] = unquote(unquote_cookie(v)) | ||
output: dict[str, str] = { | ||
k: unquote(unquote_cookie(v)) | ||
for k, v in filter( | ||
lambda x: x[0] or x[1], | ||
((k.strip(), v.strip()) for k, v in cookies), | ||
) | ||
} | ||
Comment on lines
-51
to
+58
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
return output | ||
|
||
|
||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -139,7 +139,11 @@ def is_required(self) -> bool: | |
if isinstance(self.kwarg_model, ParameterKwarg) and self.kwarg_model.required is not None: | ||
return self.kwarg_model.required | ||
|
||
return not (self.is_optional or self.is_any) and (self.is_empty or self.default_value is None) | ||
return ( | ||
not self.is_optional | ||
and not self.is_any | ||
and (self.is_empty or self.default_value is None) | ||
) | ||
Comment on lines
-142
to
+146
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
|
||
@property | ||
def is_literal(self) -> bool: | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -166,9 +166,7 @@ def parse_fn_signature( | |
) | ||
|
||
if isinstance(parameter.default, DependencyKwarg) and parameter.name not in dependency_name_set: | ||
if not parameter.optional and ( | ||
isinstance(parameter.default, DependencyKwarg) and parameter.default.default is Empty | ||
): | ||
if not parameter.optional and parameter.default.default is Empty: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
raise ImproperlyConfiguredException( | ||
f"Explicit dependency '{parameter.name}' for '{fn_name}' has no default value, " | ||
f"or provided dependency." | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -291,12 +291,10 @@ def _autodiscover_app(cwd: Path) -> LoadedApp: | |
|
||
def _format_is_enabled(value: Any) -> str: | ||
"""Return a coloured string `"Enabled" if ``value`` is truthy, else "Disabled".""" | ||
if value: | ||
return "[green]Enabled[/]" | ||
return "[red]Disabled[/]" | ||
return "[green]Enabled[/]" if value else "[red]Disabled[/]" | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
|
||
|
||
def show_app_info(app: Starlite) -> None: # pragma: no cover | ||
def show_app_info(app: Starlite) -> None: # pragma: no cover | ||
Comment on lines
-299
to
+297
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
"""Display basic information about the application and its configuration.""" | ||
|
||
table = Table(show_header=False) | ||
|
@@ -324,12 +322,10 @@ def show_app_info(app: Starlite) -> None: # pragma: no cover | |
|
||
if app.static_files_config: | ||
static_files_configs = app.static_files_config | ||
static_files_info = [] | ||
for static_files in static_files_configs: | ||
static_files_info.append( | ||
f"path=[yellow]{static_files.path}[/] dirs=[yellow]{', '.join(map(str, static_files.directories))}[/] " | ||
f"html_mode={_format_is_enabled(static_files.html_mode)}", | ||
) | ||
static_files_info = [ | ||
f"path=[yellow]{static_files.path}[/] dirs=[yellow]{', '.join(map(str, static_files.directories))}[/] html_mode={_format_is_enabled(static_files.html_mode)}" | ||
for static_files in static_files_configs | ||
] | ||
table.add_row("Static files", "\n".join(static_files_info)) | ||
|
||
if app.serialization_plugins: | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -184,9 +184,7 @@ def cookies(self) -> dict[str, str]: | |
""" | ||
if self._cookies is Empty: | ||
cookies: dict[str, str] = {} | ||
cookie_header = self.headers.get("cookie") | ||
|
||
if cookie_header: | ||
if cookie_header := self.headers.get("cookie"): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
cookies = parse_cookie_string(cookie_header) | ||
|
||
self._cookies = self.scope["_cookies"] = cookies # type: ignore[typeddict-unknown-key] | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function
login_handler
refactored with the following changes:inline-immediately-returned-variable
)This removes the following comments ( why? ):