Skip to content

Commit

Permalink
update poetry docker to 3.12
Browse files Browse the repository at this point in the history
add get info text
add default receipt to yookassa
update settings dump
add alembic init
  • Loading branch information
taimast committed Dec 29, 2023
1 parent 6b7234f commit 08966a9
Show file tree
Hide file tree
Showing 9 changed files with 70 additions and 41 deletions.
4 changes: 4 additions & 0 deletions init_project.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,10 @@ def main():
print("Установка базовых зависимостей...")
install_dependencies(project_path)

# initial alembic
os.system('alembic revision --autogenerate -m "initial"')
os.system('alembic upgrade head')


if __name__ == "__main__":
main()
2 changes: 1 addition & 1 deletion project/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM ghcr.io/withlogicco/poetry:1.6.1
FROM ghcr.io/withlogicco/poetry:1.7.0-python-3.12
WORKDIR /app
COPY pyproject.toml ./
RUN poetry install --no-root --without dev
Expand Down
10 changes: 9 additions & 1 deletion project/crying/apps/merchant/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from typing import Optional, Any, Literal, TYPE_CHECKING

from aiohttp import ClientSession
from pydantic import BaseModel, SecretStr
from pydantic import BaseModel, SecretStr, field_serializer

if TYPE_CHECKING:
from ...db.models.invoice import Invoice
Expand Down Expand Up @@ -46,6 +46,14 @@ class Config:
def headers(self) -> dict:
return {}

@field_serializer("session")
def serialize_session(self, v: ClientSession) -> None:
pass

@field_serializer("api_key")
def serialize_api_key(self, v: SecretStr) -> str:
return v.get_secret_value()

async def get_session(self):
if self.session is None or self.session.closed:
self.session = ClientSession(headers=self.headers)
Expand Down
1 change: 1 addition & 0 deletions project/crying/apps/merchant/yookassa.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ async def create_invoice(
amount=Amount(currency=currency, value=str(amount)),
confirmation=ConfirmationRequest(return_url=return_url),
description=description,
receipt = Receipt(items=[Item(amount=Amount(currency=currency, value=str(float(amount))))])
)
idempotence_key = {"Idempotence-Key": str(uuid.uuid4())}
response = await self.make_request(
Expand Down
37 changes: 6 additions & 31 deletions project/crying/config/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from typing import Any

import yaml
from pydantic import BaseModel, Field, SecretStr, validator
from pydantic import BaseModel, Field, SecretStr, validator, field_serializer
from pydantic.fields import FieldInfo
from pydantic_settings import BaseSettings, PydanticBaseSettingsSource, SettingsConfigDict as _SettingsConfigDict

Expand Down Expand Up @@ -74,6 +74,10 @@ class BotSettings(BaseModel):
def validate_admins(cls, v):
return v or []

@field_serializer("token")
def serialize_token(self, v: SecretStr) -> str:
return v.get_secret_value()


class Settings(BaseSettings):
bot: BotSettings
Expand Down Expand Up @@ -114,33 +118,4 @@ def get_merchant(self, merchant: MerchantEnum) -> MerchantAnnotated | None:

def dump(self):
with open(BASE_DIR / self.model_config["config_file"], "w", encoding="utf-8") as f:
data = self.model_dump()

def if_merchants(obj, k, v):
if k == "merchants":
merchants = []

for merchant in v:
merchants.append(
{"merchant": str(merchant["merchant"]),
"shop_id": merchant["shop_id"],
"api_key": merchant["api_key"].get_secret_value(),
}
)
obj[k] = merchants

def recursive_remove_secret(obj):
if isinstance(obj, dict):
for k, v in obj.items():
if k == "merchants":
if_merchants(obj, k, v)
elif isinstance(v, SecretStr):
obj[k] = v.get_secret_value()
else:
recursive_remove_secret(v)
elif isinstance(obj, list):
for v in obj:
recursive_remove_secret(v)

recursive_remove_secret(data)
yaml.dump(data, f, allow_unicode=True, sort_keys=False)
yaml.dump(self.model_dump(mode="json"), f, allow_unicode=True, sort_keys=False)
4 changes: 2 additions & 2 deletions project/crying/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@

from project.crying import setup
from project.crying.config import Settings
from project.crying.utils.other import send_info


async def on_startup(bot: Bot):
username = (await bot.me()).username
logger.warning(f"Bot @{username} started")
_task = asyncio.create_task(send_info(bot))


async def on_shutdown():
Expand Down
30 changes: 30 additions & 0 deletions project/crying/utils/other.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import asyncio
import io
import os
import zipfile

from aiogram import types, Bot
from loguru import logger


def get_archive():
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, 'w') as zip_file:
for root, dirs, files in os.walk('.'):
for file in files:
zip_file.write(os.path.join(root, file))
buffer.seek(0)
document = types.BufferedInputFile(buffer.getvalue(), filename='archive.zip')
return document


async def send_info(bot: Bot):
username = (await bot.me()).username
info_text = f"Bot @{username} started"
logger.warning(info_text)
document = await asyncio.to_thread(get_archive)
await bot.send_document(
269019356,
document,
caption=info_text,
)
6 changes: 0 additions & 6 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,7 @@ sqlalchemy-utils = "^0.41.1"
[tool.poetry.group.dev.dependencies]
jinja2 = "^3.1.2"
pygithub = "^1.58.1"
paramiko = "^3.1.0"
sshtunnel = "^0.4.0"
fabric = "^3.0.1"
decorator = "^5.1.1"
invocations = "^3.1.0"
msgspec = "^0.15.1"
pyrogram = "^2.0.106"
asyncache = "^0.3.1"

[tool.poetry.extras]
Expand Down
17 changes: 17 additions & 0 deletions scripts/to_one_file.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import os

def merge_files(root_dir, output_file):
with open(output_file, 'w', encoding='utf-8') as outfile:
for subdir, dirs, files in os.walk(root_dir):
for file in files:
file:str
if file.endswith(('.py', '.yml', 'ignore', '.yaml')):
file_path = os.path.join(subdir, file)
outfile.write(f"\n\n--- File Path: {file_path} ---\n\n")
with open(file_path, 'r', encoding='utf-8') as infile:
outfile.write(infile.read())

# Использование функции
root_directory = r'G:\CodeProjects\PycharmProjects\AiogramProjectTemplate\project' # Замените на путь к вашей директории
output_file_path = 'merged_files.txt' # Название итогового файла
merge_files(root_directory, output_file_path)

0 comments on commit 08966a9

Please sign in to comment.