Add linters config

This commit is contained in:
2022-01-01 20:48:39 +03:00
parent a7cfff3170
commit f062b41ce8
16 changed files with 179 additions and 60 deletions

View File

@@ -1,20 +1,22 @@
from logging.config import fileConfig
import os
import sys
from alembic import context
import sys, os
from sqlalchemy.engine import create_engine
from core.db import DATABASE_URL
myPath = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, myPath + '/../../')
sys.path.insert(0, myPath + "/../../")
config = context.config
from app.models import BaseMeta
target_metadata = BaseMeta.metadata
@@ -52,9 +54,7 @@ def run_migrations_online():
connectable = create_engine(DATABASE_URL)
with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()

View File

@@ -9,24 +9,31 @@ from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '3bbf7cb4eaa2'
down_revision = '5a32159504fd'
revision = "3bbf7cb4eaa2"
down_revision = "5a32159504fd"
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.alter_column('uploaded_files', 'upload_time',
existing_type=postgresql.TIMESTAMP(timezone=True),
nullable=True)
op.alter_column(
"uploaded_files",
"upload_time",
existing_type=postgresql.TIMESTAMP(timezone=True),
nullable=True,
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.alter_column('uploaded_files', 'upload_time',
existing_type=postgresql.TIMESTAMP(timezone=True),
nullable=False)
op.alter_column(
"uploaded_files",
"upload_time",
existing_type=postgresql.TIMESTAMP(timezone=True),
nullable=False,
)
# ### end Alembic commands ###

View File

@@ -10,7 +10,7 @@ import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '5a32159504fd'
revision = "5a32159504fd"
down_revision = None
branch_labels = None
depends_on = None
@@ -18,17 +18,18 @@ depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('uploaded_files',
sa.Column('id', sa.BigInteger(), nullable=True),
sa.Column('backend', sa.String(length=16), nullable=False),
sa.Column('data', sa.JSON(), nullable=False),
sa.Column('upload_time', sa.DateTime(timezone=True), nullable=False),
sa.PrimaryKeyConstraint('id')
op.create_table(
"uploaded_files",
sa.Column("id", sa.BigInteger(), nullable=True),
sa.Column("backend", sa.String(length=16), nullable=False),
sa.Column("data", sa.JSON(), nullable=False),
sa.Column("upload_time", sa.DateTime(timezone=True), nullable=False),
sa.PrimaryKeyConstraint("id"),
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('uploaded_files')
op.drop_table("uploaded_files")
# ### end Alembic commands ###

View File

@@ -6,4 +6,6 @@ from core.config import env_config
async def check_token(api_key: str = Security(default_security)):
if api_key != env_config.API_KEY:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Wrong api key!")
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail="Wrong api key!"
)

View File

@@ -1,5 +1,5 @@
from enum import Enum
from datetime import datetime
from enum import Enum
import ormar
@@ -12,8 +12,8 @@ class BaseMeta(ormar.ModelMeta):
class UploadBackends(str, Enum):
aiogram = 'aiogram'
telethon = 'telethon'
aiogram = "aiogram"
telethon = "telethon"
class UploadedFile(ormar.Model):

View File

@@ -1,11 +1,12 @@
from typing import Optional
from io import BytesIO
from typing import Optional
from fastapi import UploadFile
from telegram_files_storage import AiogramFilesStorage, TelethonFilesStorage
from core.config import env_config
from app.models import UploadedFile, UploadBackends
from core.config import env_config
class FileUploader:
@@ -67,7 +68,9 @@ class FileUploader:
storage = self.get_telethon_storage()
self.upload_data = await storage.upload(bytes_io, caption=self.caption) # type: ignore
self.upload_data = await storage.upload(
bytes_io, caption=self.caption
) # type: ignore
self.upload_backend = UploadBackends.telethon
return True
@@ -82,12 +85,18 @@ class FileUploader:
async def prepare(cls):
if env_config.BOT_TOKENS:
cls.AIOGRAM_STORAGES: list[AiogramFilesStorage] = [
AiogramFilesStorage(env_config.TELEGRAM_CHAT_ID, token) for token in env_config.BOT_TOKENS
AiogramFilesStorage(env_config.TELEGRAM_CHAT_ID, token)
for token in env_config.BOT_TOKENS
]
if env_config.TELETHON_APP_CONFIG and env_config.TELETHON_SESSIONS:
cls.TELETHON_STORAGES: list[TelethonFilesStorage] = [
TelethonFilesStorage(env_config.TELEGRAM_CHAT_ID, env_config.TELETHON_APP_CONFIG.APP_ID, env_config.TELETHON_APP_CONFIG.API_HASH, session)
TelethonFilesStorage(
env_config.TELEGRAM_CHAT_ID,
env_config.TELETHON_APP_CONFIG.APP_ID,
env_config.TELETHON_APP_CONFIG.API_HASH,
session,
)
for session in env_config.TELETHON_SESSIONS
]
@@ -99,7 +108,9 @@ class FileUploader:
if not cls.AIOGRAM_STORAGES:
raise ValueError("Aiogram storage not exist!")
cls._aiogram_storage_index = (cls._aiogram_storage_index + 1) % len(cls.AIOGRAM_STORAGES)
cls._aiogram_storage_index = (cls._aiogram_storage_index + 1) % len(
cls.AIOGRAM_STORAGES
)
return cls.AIOGRAM_STORAGES[cls._aiogram_storage_index]
@@ -108,12 +119,16 @@ class FileUploader:
if not cls.TELETHON_STORAGES:
raise ValueError("Telethon storage not exists!")
cls._telethon_storage_index = (cls._telethon_storage_index + 1) % len(cls.TELETHON_STORAGES)
cls._telethon_storage_index = (cls._telethon_storage_index + 1) % len(
cls.TELETHON_STORAGES
)
return cls.TELETHON_STORAGES[cls._telethon_storage_index]
@classmethod
async def upload(cls, file: UploadFile, caption: Optional[str] = None) -> Optional[UploadedFile]:
async def upload(
cls, file: UploadFile, caption: Optional[str] = None
) -> Optional[UploadedFile]:
uploader = cls(file, caption)
upload_result = await uploader._upload()

View File

@@ -1,19 +1,17 @@
from typing import Optional
from fastapi import File, UploadFile, Depends, Form
from starlette import status
from fastapi import APIRouter, HTTPException
from fastapi import File, UploadFile, Depends, Form, APIRouter, HTTPException
from starlette import status
from app.depends import check_token
from app.models import UploadedFile as UploadedFileDB
from app.serializers import UploadedFile, CreateUploadedFile
from app.services.file_uploader import FileUploader
from app.depends import check_token
router = APIRouter(
prefix="/api/v1/files",
dependencies=[Depends(check_token)],
tags=["files"]
prefix="/api/v1/files", dependencies=[Depends(check_token)], tags=["files"]
)
@@ -22,9 +20,13 @@ async def get_files():
return await UploadedFileDB.objects.all()
@router.get("/{file_id}", response_model=UploadedFile, responses={
404: {},
})
@router.get(
"/{file_id}",
response_model=UploadedFile,
responses={
404: {},
},
)
async def get_file(file_id: int):
uploaded_file = await UploadedFileDB.objects.get_or_none(id=file_id)
@@ -36,9 +38,7 @@ async def get_file(file_id: int):
@router.post("/", response_model=UploadedFile)
async def create_file(data: CreateUploadedFile):
return await UploadedFileDB.objects.create(
**data.dict()
)
return await UploadedFileDB.objects.create(**data.dict())
@router.post("/upload/", response_model=UploadedFile)
@@ -46,9 +46,7 @@ async def upload_file(file: UploadFile = File({}), caption: Optional[str] = Form
return await FileUploader.upload(file, caption=caption)
@router.delete("/{file_id}", response_model=UploadedFile, responses={
400: {}
})
@router.delete("/{file_id}", response_model=UploadedFile, responses={400: {}})
async def delete_file(file_id: int):
uploaded_file = await UploadedFileDB.objects.get_or_none(id=file_id)