Skip to content
Closed
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
6 changes: 3 additions & 3 deletions app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
Initial project v16
"""

x = [1,2,3]
a = 1+1
b = 1 + 1
x = [1, 2, 3]
a = 1 + 1
b = 1 + 1
4 changes: 3 additions & 1 deletion app/api/depends.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,7 @@ async def get_db() -> Database:
return Database(session)


async def get_current_user(token: str = Depends(oauth2_scheme), db: Database = Depends(get_db)):
async def get_current_user(
token: str = Depends(oauth2_scheme), db: Database = Depends(get_db)
):
return await auth.authorization(token, db)
5 changes: 4 additions & 1 deletion app/api/users/endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,10 @@ async def new(user: UserSchemeAdd, db: Database = Depends(depends.get_db)):


@router.post("/token", response_model=UserTokenScheme)
async def token(form_data: auth.OAuth2PasswordRequestForm = Depends(), db: Database = Depends(depends.get_db)):
async def token(
form_data: auth.OAuth2PasswordRequestForm = Depends(),
db: Database = Depends(depends.get_db),
):
"""
Получение токена доступа для пользователя.
"""
Expand Down
8 changes: 3 additions & 5 deletions app/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
Ядро FastAPI приложения.
"""

from .settings import settings

__all__ = (
"settings",
)
from .settings import settings

__all__ = ("settings",)
10 changes: 5 additions & 5 deletions app/core/auth/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
from .security import verify_password, get_password_hash, create_access_token

__all__ = (
'authorization',
'OAuth2PasswordRequestForm',
'verify_password',
'get_password_hash',
'create_access_token'
"authorization",
"OAuth2PasswordRequestForm",
"verify_password",
"get_password_hash",
"create_access_token",
)
16 changes: 8 additions & 8 deletions app/core/auth/oauth2.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@

class OAuth2PasswordRequestForm:
def __init__(
self,
*,
grant_type: Annotated[Union[str, None], Form(pattern="password")] = None,
username: Annotated[str, Form()],
password: Annotated[str, Form()],
scope: Annotated[str, Form()] = "",
client_id: Annotated[Union[str, None], Form()] = None,
client_secret: Annotated[Union[str, None], Form()] = None,
self,
*,
grant_type: Annotated[Union[str, None], Form(pattern="password")] = None,
username: Annotated[str, Form()],
password: Annotated[str, Form()],
scope: Annotated[str, Form()] = "",
client_id: Annotated[Union[str, None], Form()] = None,
client_secret: Annotated[Union[str, None], Form()] = None,
):
"""
Представляет форму запроса пароля OAuth 2.0.
Expand Down
5 changes: 1 addition & 4 deletions app/core/auth/security.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,6 @@ def create_access_token(username: str):
Returns:
str: Закодированный JWT токен в виде строки.
"""
data = dict(
username=username,
exp=datetime.utcnow() + timedelta(minutes=120)
)
data = dict(username=username, exp=datetime.utcnow() + timedelta(minutes=120))
encoded_jwt = jwt.encode(data, settings.APP_AUTH_SECRET, algorithm="HS256")
return encoded_jwt
6 changes: 4 additions & 2 deletions app/core/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,10 @@ class Settings(BaseSettings):

@property
def pg_dns(self):
return (f"postgresql+asyncpg://{self.POSTGRES_USER}:{self.POSTGRES_PASSWORD}@",
f"{self.POSTGRES_HOST}:{self.POSTGRES_PORT}/{self.POSTGRES_DATABASE}")
return (
f"postgresql+asyncpg://{self.POSTGRES_USER}:{self.POSTGRES_PASSWORD}@",
f"{self.POSTGRES_HOST}:{self.POSTGRES_PORT}/{self.POSTGRES_DATABASE}",
)


settings = Settings()
6 changes: 3 additions & 3 deletions app/database/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from .models import Base

__all__ = (
'Database',
'engine',
'Base',
"Database",
"engine",
"Base",
)
54 changes: 27 additions & 27 deletions app/database/database.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
from typing import Optional

from sqlalchemy.engine.url import URL
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession
from sqlalchemy.ext.asyncio import create_async_engine as _create_async_engine
from app.core import settings
from .repositories import UserRepo
def create_async_engine(url: URL | str) -> AsyncEngine:
return _create_async_engine(url=url, echo=False, pool_pre_ping=True)
engine = create_async_engine(settings.pg_dns)
class Database:
session: AsyncSession
user: UserRepo
def __init__(
self,
session: AsyncSession,
user: Optional[UserRepo] = None,
):
self.session = session
self.user = user or UserRepo(session=session)
from sqlalchemy.engine.url import URL
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession
from sqlalchemy.ext.asyncio import create_async_engine as _create_async_engine

from app.core import settings
from .repositories import UserRepo


def create_async_engine(url: URL | str) -> AsyncEngine:
return _create_async_engine(url=url, echo=False, pool_pre_ping=True)


engine = create_async_engine(settings.pg_dns)


class Database:
session: AsyncSession

user: UserRepo

def __init__(
self,
session: AsyncSession,
user: Optional[UserRepo] = None,
):
self.session = session
self.user = user or UserRepo(session=session)
4 changes: 2 additions & 2 deletions app/database/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@
from .user import User

__all__ = (
'Base',
'User',
"Base",
"User",
)
14 changes: 6 additions & 8 deletions app/database/models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@

metadata = MetaData(
naming_convention={
'ix': 'ix_%(column_0_label)s',
'uq': 'uq_%(table_name)s_%(column_0_name)s',
'ck': 'ck_%(table_name)s_%(constraint_name)s',
'fk': 'fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s',
'pk': 'pk_%(table_name)s',
"ix": "ix_%(column_0_label)s",
"uq": "uq_%(table_name)s_%(column_0_name)s",
"ck": "ck_%(table_name)s_%(constraint_name)s",
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
"pk": "pk_%(table_name)s",
}
)

Expand All @@ -26,6 +26,4 @@ def __tablename__(cls):

__allow_unmapped__ = False

id: Mapped[int] = mapped_column(
Integer, autoincrement=True, primary_key=True
)
id: Mapped[int] = mapped_column(Integer, autoincrement=True, primary_key=True)
4 changes: 1 addition & 3 deletions app/database/repositories/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,4 @@

from .user import UserRepo

__all__ = (
'UserRepo',
)
__all__ = ("UserRepo",)
13 changes: 10 additions & 3 deletions app/database/repositories/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

from ..models import Base

AbstractModel = TypeVar('AbstractModel')
AbstractModel = TypeVar("AbstractModel")


class Repository(Generic[AbstractModel]):
Expand All @@ -29,7 +29,10 @@ async def get_by_where(self, whereclause) -> AbstractModel | None:
return (await self.session.execute(statement)).unique().scalar_one_or_none()

async def get_many(
self, whereclause: Optional [List[Any]] = None, limit: Optional[int] = None, order_by=None
self,
whereclause: Optional[List[Any]] = None,
limit: Optional[int] = None,
order_by=None,
):
statement = sa.select(self.type_model).limit(limit).order_by(order_by)
if whereclause:
Expand All @@ -41,7 +44,11 @@ async def delete(self, whereclause) -> None:
await self.session.execute(statement)

async def update(self, ident: int, **values):
statement = sa.update(self.type_model).values(**values).where(self.type_model.id == ident)
statement = (
sa.update(self.type_model)
.values(**values)
.where(self.type_model.id == ident)
)
await self.session.execute(statement)

@abc.abstractmethod
Expand Down
12 changes: 6 additions & 6 deletions app/database/repositories/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ async def new(
self,
username: str | None = None,
password: str | None = None,
) -> User:
new_user = User()
new_user.username = username
new_user.password = password
) -> User:
new_user = User()
new_user.username = username
new_user.password = password

new_user = await self.session.merge(new_user)
await self.session.flush()
await self.session.flush()
return new_user

async def get_by_username(self, username: str) -> User | None:
Expand Down
3 changes: 3 additions & 0 deletions app/schemas/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ class UserScheme(BaseModel):
"""
Схема, которую возвращает бэк.
"""

id: int = 0
username: str = "username"

Expand All @@ -20,6 +21,7 @@ class UserSchemeAdd(BaseModel):
"""
Схема создания пользователя.
"""

username: str = "username"
password: str = "password"

Expand All @@ -28,6 +30,7 @@ class UserTokenScheme(BaseModel):
"""
Схема токена пользователя.
"""

access_token: str
token_type: str = "Bearer"

Expand Down
2 changes: 1 addition & 1 deletion migrations/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
# target_metadata = mymodel.Base.metadata
target_metadata = Base.metadata

config.set_main_option('sqlalchemy.url', settings.pg_dns)
config.set_main_option("sqlalchemy.url", settings.pg_dns)


# other values from the config, defined by the needs of env.py,
Expand Down
15 changes: 8 additions & 7 deletions migrations/versions/9fc63c3797b9_.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,25 @@


# revision identifiers, used by Alembic.
revision: str = '9fc63c3797b9'
revision: str = "9fc63c3797b9"
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('user',
sa.Column('username', sa.String(), nullable=False),
sa.Column('password', sa.String(), nullable=False),
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.PrimaryKeyConstraint('id', name=op.f('pk_user'))
op.create_table(
"user",
sa.Column("username", sa.String(), nullable=False),
sa.Column("password", sa.String(), nullable=False),
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.PrimaryKeyConstraint("id", name=op.f("pk_user")),
)
# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('user')
op.drop_table("user")
# ### end Alembic commands ###