Skip to content

Commit

Permalink
fix: use black + isort on all files
Browse files Browse the repository at this point in the history
  • Loading branch information
raphael0202 committed Nov 15, 2023
1 parent 8791d8a commit 877f3c6
Show file tree
Hide file tree
Showing 8 changed files with 92 additions and 80 deletions.
10 changes: 6 additions & 4 deletions alembic/env.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from logging.config import fileConfig

from sqlalchemy import engine_from_config
from sqlalchemy import pool
from sqlalchemy import engine_from_config, pool

from alembic import context
from app import models
Expand All @@ -15,7 +14,9 @@

# this will overwrite the ini-file sqlalchemy.url path
# with the path given in the config of the main code
config.set_main_option("sqlalchemy.url", sqlalchemy_url.render_as_string(hide_password=False))
config.set_main_option(
"sqlalchemy.url", sqlalchemy_url.render_as_string(hide_password=False)
)

# Interpret the config file for Python logging.
# This line sets up loggers basically.
Expand Down Expand Up @@ -71,7 +72,8 @@ def run_migrations_online() -> None:

with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata,
connection=connection,
target_metadata=target_metadata,
)

with context.begin_transaction():
Expand Down
33 changes: 18 additions & 15 deletions alembic/versions/20231112_1203_01907c7134ee_create_user_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,14 @@
Create Date: 2023-11-12 12:03:26.333539
"""
from typing import Sequence
from typing import Union
from typing import Sequence, Union

import sqlalchemy as sa

from alembic import op


# revision identifiers, used by Alembic.
revision: str = '01907c7134ee'
revision: str = "01907c7134ee"
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
Expand All @@ -23,21 +21,26 @@
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
'users',
sa.Column('user_id', sa.String(), nullable=False),
sa.Column('token', sa.String(), nullable=True),
sa.Column('last_used', sa.DateTime(timezone=True), nullable=True),
sa.Column('created', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),
sa.PrimaryKeyConstraint('user_id'),
"users",
sa.Column("user_id", sa.String(), nullable=False),
sa.Column("token", sa.String(), nullable=True),
sa.Column("last_used", sa.DateTime(timezone=True), nullable=True),
sa.Column(
"created",
sa.DateTime(timezone=True),
server_default=sa.text("now()"),
nullable=True,
),
sa.PrimaryKeyConstraint("user_id"),
)
op.create_index(op.f('ix_users_token'), 'users', ['token'], unique=True)
op.create_index(op.f('ix_users_user_id'), 'users', ['user_id'], unique=False)
op.create_index(op.f("ix_users_token"), "users", ["token"], unique=True)
op.create_index(op.f("ix_users_user_id"), "users", ["user_id"], unique=False)
# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_users_user_id'), table_name='users')
op.drop_index(op.f('ix_users_token'), table_name='users')
op.drop_table('users')
op.drop_index(op.f("ix_users_user_id"), table_name="users")
op.drop_index(op.f("ix_users_token"), table_name="users")
op.drop_table("users")
# ### end Alembic commands ###
53 changes: 30 additions & 23 deletions alembic/versions/20231112_1827_43571a31006d_create_price_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,46 +5,53 @@
Create Date: 2023-11-12 18:27:49.656734
"""
from typing import Sequence
from typing import Union
from typing import Sequence, Union

import sqlalchemy as sa

from alembic import op


# revision identifiers, used by Alembic.
revision: str = '43571a31006d'
down_revision: Union[str, None] = '01907c7134ee'
revision: str = "43571a31006d"
down_revision: Union[str, None] = "01907c7134ee"
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(
'prices',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('product_code', sa.String(), nullable=True),
sa.Column('price', sa.Numeric(precision=10, scale=2), nullable=True),
sa.Column('currency', sa.String(length=3), nullable=True),
sa.Column('location_osm_id', sa.BigInteger(), nullable=True),
sa.Column('location_osm_type', sa.String(length=255), nullable=True),
sa.Column('date', sa.Date(), nullable=True),
sa.Column('owner', sa.String(), nullable=True),
sa.Column('created', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),
sa.PrimaryKeyConstraint('id'),
"prices",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("product_code", sa.String(), nullable=True),
sa.Column("price", sa.Numeric(precision=10, scale=2), nullable=True),
sa.Column("currency", sa.String(length=3), nullable=True),
sa.Column("location_osm_id", sa.BigInteger(), nullable=True),
sa.Column("location_osm_type", sa.String(length=255), nullable=True),
sa.Column("date", sa.Date(), nullable=True),
sa.Column("owner", sa.String(), nullable=True),
sa.Column(
"created",
sa.DateTime(timezone=True),
server_default=sa.text("now()"),
nullable=True,
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_prices_id"), "prices", ["id"], unique=False)
op.create_index(
op.f("ix_prices_location_osm_id"), "prices", ["location_osm_id"], unique=False
)
op.create_index(
op.f("ix_prices_product_code"), "prices", ["product_code"], unique=False
)
op.create_index(op.f('ix_prices_id'), 'prices', ['id'], unique=False)
op.create_index(op.f('ix_prices_location_osm_id'), 'prices', ['location_osm_id'], unique=False)
op.create_index(op.f('ix_prices_product_code'), 'prices', ['product_code'], unique=False)
# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_prices_product_code'), table_name='prices')
op.drop_index(op.f('ix_prices_location_osm_id'), table_name='prices')
op.drop_index(op.f('ix_prices_id'), table_name='prices')
op.drop_table('prices')
op.drop_index(op.f("ix_prices_product_code"), table_name="prices")
op.drop_index(op.f("ix_prices_location_osm_id"), table_name="prices")
op.drop_index(op.f("ix_prices_id"), table_name="prices")
op.drop_table("prices")
# ### end Alembic commands ###
34 changes: 16 additions & 18 deletions app/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,17 @@
from typing import Annotated

import requests
from fastapi import Depends
from fastapi import FastAPI
from fastapi import HTTPException
from fastapi import Request
from fastapi import Response
from fastapi import status
from fastapi.responses import HTMLResponse
from fastapi.responses import PlainTextResponse
from fastapi.security import OAuth2PasswordBearer
from fastapi.security import OAuth2PasswordRequestForm
from fastapi import Depends, FastAPI, HTTPException, Request, Response, status
from fastapi.responses import HTMLResponse, PlainTextResponse
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from fastapi.templating import Jinja2Templates
from openfoodfacts.utils import get_logger

from app import crud
from app import schemas
from app import crud, schemas
from app.config import settings
from app.db import session
from app.utils import init_sentry


logger = get_logger(level=settings.log_level.to_int())

description = """
Expand Down Expand Up @@ -56,7 +47,7 @@ async def create_token(user_id: str):


async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):
if token and '__U' in token:
if token and "__U" in token:
current_user: schemas.UserBase = crud.update_user_last_used_field(db, token=token) # type: ignore
if current_user:
return current_user
Expand Down Expand Up @@ -91,7 +82,9 @@ def main_page(request: Request):


@app.post("/auth")
async def authentication(form_data: Annotated[OAuth2PasswordRequestForm, Depends()], response: Response):
async def authentication(
form_data: Annotated[OAuth2PasswordRequestForm, Depends()], response: Response
):
"""
Authentication: provide username/password and get a bearer token in return
Expand All @@ -115,17 +108,22 @@ async def authentication(form_data: Annotated[OAuth2PasswordRequestForm, Depends
crud.create_user(db, user=user) # type: ignore
return {"access_token": token, "token_type": "bearer"}
elif r.status_code == 403:
await asyncio.sleep(2) # prevents brute-force
await asyncio.sleep(2) # prevents brute-force
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Bearer"},
)
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Server error")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Server error"
)


@app.post("/prices", response_model=schemas.PriceBase)
async def create_price(price: schemas.PriceCreate, current_user: schemas.UserBase = Depends(get_current_user)):
async def create_price(
price: schemas.PriceCreate,
current_user: schemas.UserBase = Depends(get_current_user),
):
db_price = crud.create_price(db, price=price, user=current_user) # type: ignore
return db_price

Expand Down
10 changes: 5 additions & 5 deletions app/crud.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
from sqlalchemy.orm import Session
from sqlalchemy.sql import func

from app.models import Price
from app.models import User
from app.schemas import PriceCreate
from app.schemas import UserBase
from app.models import Price, User
from app.schemas import PriceCreate, UserBase


def get_user(db: Session, user_id: str):
Expand Down Expand Up @@ -33,7 +31,9 @@ def create_user(db: Session, user: UserBase):
def update_user_last_used_field(db: Session, token: str):
db_user = get_user_by_token(db, token=token)
if db_user:
db.query(User).filter(User.user_id == db_user.user_id).update({"last_used": func.now()})
db.query(User).filter(User.user_id == db_user.user_id).update(
{"last_used": func.now()}
)
db.commit()
db.refresh(db_user)
return db_user
Expand Down
8 changes: 1 addition & 7 deletions app/models.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,4 @@
from sqlalchemy import BigInteger
from sqlalchemy import Column
from sqlalchemy import Date
from sqlalchemy import DateTime
from sqlalchemy import Integer
from sqlalchemy import Numeric
from sqlalchemy import String
from sqlalchemy import BigInteger, Column, Date, DateTime, Integer, Numeric, String
from sqlalchemy.sql import func
from sqlalchemy_utils import force_auto_coercion
from sqlalchemy_utils.types.choice import ChoiceType
Expand Down
11 changes: 3 additions & 8 deletions app/schemas.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
from datetime import date
from datetime import datetime

from pydantic import BaseModel
from pydantic import ConfigDict
from pydantic import Field
from pydantic import field_serializer
from pydantic import field_validator
from datetime import date, datetime

from pydantic import BaseModel, ConfigDict, Field, field_serializer, field_validator
from sqlalchemy_utils import Currency

from app.enums import PriceLocationOSMType
Expand Down
13 changes: 13 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,16 @@ pytest = "^7.4.3"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"

[tool.black]
include = '\.pyi?$'
exclude = '''
/(
\.git
| \.mypy_cache
| \.venv
)/
'''

[tool.mypy]
ignore_missing_imports = true

0 comments on commit 877f3c6

Please sign in to comment.