Skip to content
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

Mc pydantic #206

Merged
merged 5 commits into from
Dec 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
from resources.Callback import namespace_auth
from resources.DataRequests import namespace_data_requests
from resources.GithubDataRequests import namespace_github
from resources.HomepageSearchCache import namespace_homepage_search_cache
from resources.LinkToGithub import namespace_link_to_github
from resources.LoginWithGithub import namespace_login_with_github
from resources.Map import namespace_map
Expand Down Expand Up @@ -109,9 +108,7 @@
def create_app() -> Flask:
psycopg2_connection = initialize_psycopg_connection()
config.connection = psycopg2_connection
api = Api()
for namespace in NAMESPACES:
api.add_namespace(namespace)
api = get_api_with_namespaces()
app = Flask(__name__)
app.json = UpdatedJSONProvider(app)

Expand All @@ -132,6 +129,13 @@
return app


def get_api_with_namespaces():

Check warning on line 132 in app.py

View workflow job for this annotation

GitHub Actions / flake8

[flake8] app.py#L132 <103>

Missing docstring in public function
Raw output
./app.py:132:1: D103 Missing docstring in public function
api = Api()
for namespace in NAMESPACES:
api.add_namespace(namespace)
return api


if __name__ == "__main__":
app = create_app()
app.run(host=os.getenv("FLASK_RUN_HOST", "127.0.0.1"))
4 changes: 2 additions & 2 deletions database_client/db_client_dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from dataclasses import dataclass
from typing import Any, Callable, Optional

from pydantic import BaseModel
from sqlalchemy.sql.expression import UnaryExpression
from sqlalchemy.schema import Column
from sqlalchemy.sql.expression import asc, desc, BinaryExpression
Expand All @@ -16,8 +17,7 @@
}


@dataclass
class OrderByParameters:
class OrderByParameters(BaseModel):
"""
Contains parameters for an order_by clause
"""
Expand Down
7 changes: 4 additions & 3 deletions database_client/subquery_logic.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
from dataclasses import dataclass
from functools import partialmethod
from typing import Optional

from pydantic import BaseModel
from sqlalchemy.orm import defaultload, joinedload
from sqlalchemy.sql.base import ExecutableOption

from database_client.models import convert_to_column_reference
from middleware.enums import Relations


@dataclass
class SubqueryParameters:
class SubqueryParameters(BaseModel):
"""
Contains parameters for executing a subquery
"""

relation_name: str
linking_column: str
columns: list[str] = None
columns: Optional[list[str]] = None

def set_columns(self, columns: list[str]) -> None:
self.columns = columns
Expand Down
9 changes: 9 additions & 0 deletions manual_tests/test_api_spec.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import json

Check warning on line 1 in manual_tests/test_api_spec.py

View workflow job for this annotation

GitHub Actions / flake8

[flake8] manual_tests/test_api_spec.py#L1 <100>

Missing docstring in public module
Raw output
./manual_tests/test_api_spec.py:1:1: D100 Missing docstring in public module

from app import get_api_with_namespaces, create_app


def test_api_spec():

Check warning on line 6 in manual_tests/test_api_spec.py

View workflow job for this annotation

GitHub Actions / flake8

[flake8] manual_tests/test_api_spec.py#L6 <103>

Missing docstring in public function
Raw output
./manual_tests/test_api_spec.py:6:1: D103 Missing docstring in public function
app = create_app()

Check warning on line 7 in manual_tests/test_api_spec.py

View workflow job for this annotation

GitHub Actions / flake8

[flake8] manual_tests/test_api_spec.py#L7 <841>

local variable 'app' is assigned to but never used
Raw output
./manual_tests/test_api_spec.py:7:5: F841 local variable 'app' is assigned to but never used
api = get_api_with_namespaces()
print(json.dumps(api.__schema__))
35 changes: 21 additions & 14 deletions middleware/access_logic.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
from dataclasses import dataclass
from http import HTTPStatus
from typing import Optional

from flask import request
from flask_jwt_extended import get_jwt_identity, verify_jwt_in_request
from flask_jwt_extended.exceptions import NoAuthorizationError
from flask_restx import abort
from jwt import ExpiredSignatureError
from pydantic import BaseModel

from database_client.database_client import DatabaseClient
from middleware.SimpleJWT import SimpleJWT, JWTPurpose
Expand All @@ -16,11 +17,11 @@
InvalidAPIKeyException,
InvalidAuthorizationHeaderException,
)
from middleware.flask_response_manager import FlaskResponseManager
from middleware.primary_resource_logic.permissions_logic import get_user_permissions


@dataclass
class AuthenticationInfo:
class AuthenticationInfo(BaseModel):
"""
A dataclass providing information on how the user was authenticated
"""
Expand Down Expand Up @@ -62,19 +63,16 @@
return access_type in self.allowed_access_methods


@dataclass
class AccessInfoBase:
pass
class AccessInfoBase(BaseModel):

Check warning on line 66 in middleware/access_logic.py

View workflow job for this annotation

GitHub Actions / flake8

[flake8] middleware/access_logic.py#L66 <101>

Missing docstring in public class
Raw output
./middleware/access_logic.py:66:1: D101 Missing docstring in public class
access_type: AccessTypeEnum


@dataclass
class AccessInfoPrimary(AccessInfoBase):
"""
A dataclass providing information on how the endpoint was accessed
"""

user_email: str
access_type: AccessTypeEnum
user_id: Optional[int] = None
permissions: list[PermissionsEnum] = None

Expand All @@ -84,17 +82,15 @@
return self.user_id


@dataclass
class PasswordResetTokenAccessInfo(AccessInfoBase):
access_type = AccessTypeEnum.RESET_PASSWORD
access_type: AccessTypeEnum = AccessTypeEnum.RESET_PASSWORD
user_id: int
user_email: str
reset_token: str


@dataclass
class ValidateEmailTokenAccessInfo(AccessInfoBase):
access_type = AccessTypeEnum.VALIDATE_EMAIL
access_type: AccessTypeEnum = AccessTypeEnum.VALIDATE_EMAIL
validate_email_token: str


Expand All @@ -104,7 +100,11 @@
try:
verify_jwt_in_request()
return get_jwt_identity()
except Exception:
except NoAuthorizationError:
FlaskResponseManager.abort(
HTTPStatus.BAD_REQUEST, message="Token is missing"
)
except Exception as e:

Check warning on line 107 in middleware/access_logic.py

View workflow job for this annotation

GitHub Actions / flake8

[flake8] middleware/access_logic.py#L107 <841>

local variable 'e' is assigned to but never used
Raw output
./middleware/access_logic.py:107:9: F841 local variable 'e' is assigned to but never used
return None

@staticmethod
Expand Down Expand Up @@ -160,14 +160,21 @@
try:
return headers["Authorization"]
except (KeyError, TypeError):
raise InvalidAuthorizationHeaderException
FlaskResponseManager.abort(
code=HTTPStatus.BAD_REQUEST, message="Authorization header missing"
)


def get_key_from_authorization_header(
authorization_header: str, scheme: str = "Basic"
) -> str:
try:
authorization_header_parts = authorization_header.split(" ")
if len(authorization_header_parts) != 2:
FlaskResponseManager.abort(
code=HTTPStatus.BAD_REQUEST,
message="Improperly formatted authorization header",
)
if authorization_header_parts[0] != scheme:
raise InvalidAPIKeyException
return authorization_header_parts[1]
Expand Down
9 changes: 4 additions & 5 deletions middleware/column_permission_logic.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
from dataclasses import dataclass
from enum import Enum
from http import HTTPStatus
from typing import Optional

from flask_restx import abort
from pydantic import BaseModel, ConfigDict

from database_client.database_client import DatabaseClient
from database_client.enums import RelationRoleEnum, ColumnPermissionEnum
Expand Down Expand Up @@ -112,8 +110,9 @@
return RelationRoleEnum.STANDARD


@dataclass
class RelationRoleParameters:
class RelationRoleParameters(BaseModel):

Check warning on line 113 in middleware/column_permission_logic.py

View workflow job for this annotation

GitHub Actions / flake8

[flake8] middleware/column_permission_logic.py#L113 <101>

Missing docstring in public class
Raw output
./middleware/column_permission_logic.py:113:1: D101 Missing docstring in public class
model_config = ConfigDict(arbitrary_types_allowed=True)

relation_role_function_with_params: DeferredFunction = DeferredFunction(
function=get_relation_role,
)
Expand Down
10 changes: 5 additions & 5 deletions middleware/custom_dataclasses.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
from dataclasses import dataclass
from typing import Optional

from pydantic import BaseModel

from database_client.enums import EntityType, EventType
from middleware.enums import CallbackFunctionsEnum


@dataclass
class GithubUserInfo:
class GithubUserInfo(BaseModel):
"""
Information about a Github user
"""

user_id: str
user_id: int
user_email: str


Expand All @@ -25,8 +26,7 @@ class FlaskSessionCallbackInfo:
callback_params: dict


@dataclass
class OAuthCallbackInfo:
class OAuthCallbackInfo(BaseModel):
"""
Contains information returned by OAuth in the callback logic
"""
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from typing import Optional

from flask import Response
from pydantic import BaseModel

Check warning on line 4 in middleware/dynamic_request_logic/get_related_resource_logic.py

View workflow job for this annotation

GitHub Actions / flake8

[flake8] middleware/dynamic_request_logic/get_related_resource_logic.py#L4 <401>

'pydantic.BaseModel' imported but unused
Raw output
./middleware/dynamic_request_logic/get_related_resource_logic.py:4:1: F401 'pydantic.BaseModel' imported but unused

from database_client.database_client import DatabaseClient
from database_client.db_client_dataclasses import WhereMapping
Expand Down
3 changes: 1 addition & 2 deletions middleware/location_logic.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from dataclasses import asdict
from typing import Union

from database_client.database_client import DatabaseClient
Expand All @@ -19,7 +18,7 @@ def get_location_id(
location_info_dict = location_info
location_info = LocationInfoDTO(**location_info)
else:
location_info_dict = asdict(location_info)
location_info_dict = dict(location_info)

location_info_where_mappings = WhereMapping.from_dict(location_info_dict)
# Get location id
Expand Down
2 changes: 1 addition & 1 deletion middleware/primary_resource_logic/agencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def validate_and_add_location_info(
def create_agency(
db_client: DatabaseClient, dto: AgenciesPostDTO, access_info: AccessInfoPrimary
) -> Response:
entry_data = asdict(dto.agency_info)
entry_data = dict(dto.agency_info)
deferred_function = optionally_get_location_info_deferred_function(
db_client=db_client,
jurisdiction_type=dto.agency_info.jurisdiction_type,
Expand Down
7 changes: 0 additions & 7 deletions middleware/primary_resource_logic/archives_queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,6 @@
]


@dataclass
class ArchivesQueryData:
id: Optional[str] = None
broken_source_url_as_of: Optional[str] = None
last_cached: Optional[str] = None


def archives_get_query(
db_client: DatabaseClient,
) -> List[Dict[str, Any]]:
Expand Down
Loading
Loading