Добавлена celery

This commit is contained in:
urec56 2024-02-09 21:00:36 +03:00
parent f13e18a27e
commit 11b1ea014f
6 changed files with 89 additions and 1 deletions

View file

@ -6,3 +6,11 @@ DB_NAME=
SECRET_KEY=
ALGORITHM=
REDIS_HOST=
REDIS_PORT=
SMTP_HOST=
SMTP_PORT=
SMTP_USER=
SMTP_PASS=

View file

@ -11,6 +11,14 @@ class Settings(BaseSettings):
SECRET_KEY: str
ALGORITHM: str
REDIS_HOST: str
REDIS_PORT: int
SMTP_HOST: str
SMTP_PORT: int
SMTP_USER: str
SMTP_PASS: str
class Config:
env_file = ".env"

View file

@ -0,0 +1,10 @@
from celery import Celery
from app.config import settings
celery = Celery(
"tasks",
broker=f'redis://{settings.REDIS_HOST}:{settings.REDIS_PORT}',
include=['app.tasks.tasks']
)

View file

@ -0,0 +1,26 @@
from email.message import EmailMessage
from pydantic import EmailStr
from app.config import settings
def create_registration_confirmation_template(
username: str,
email_to: EmailStr,
confirmation_code: str,
):
email = EmailMessage()
email["Subject"] = "Подтверждение регистрации"
email["From"] = settings.SMTP_USER
email["To"] = email_to
email.set_content(
f"""
<h1>{username}, лови аптечку</h1>
<h2>{confirmation_code}</h2>
""",
subtype="html"
)
return email

View file

@ -0,0 +1,34 @@
import smtplib
import random
import string
from pathlib import Path
from PIL import Image
from pydantic import EmailStr
from app.config import settings
from app.tasks.celery import celery
from app.tasks.email_templates import create_registration_confirmation_template
def generate_confirmation_code(length=6):
characters = string.ascii_letters + string.digits
confirmation_code = ''.join(random.choice(characters) for _ in range(length))
return confirmation_code
@celery.task
def send_registration_confirmation_email(
username: str,
email_to: EmailStr,
):
confirmation_code = generate_confirmation_code()
msg_content = create_registration_confirmation_template(
username=username, email_to=email_to, confirmation_code=confirmation_code
)
with smtplib.SMTP_SSL(settings.SMTP_HOST, settings.SMTP_PORT) as server:
server.login(settings.SMTP_USER, settings.SMTP_PASS)
server.send_message(msg_content)

View file

@ -10,6 +10,7 @@ from app.users.dao import UserDAO
from app.users.dependencies import get_current_user
from app.users.models import Users
from app.users.schemas import SUserLogin, SUserRegister, SUser, SUserName, SUserPassword
from app.tasks.tasks import send_registration_confirmation_email
router = APIRouter(
prefix="/users",
@ -45,6 +46,7 @@ async def register_user(response: Response, user_data: SUserRegister):
role=0,
black_phoenix=False
)
send_registration_confirmation_email.delay(username=user_data.username, email_to=user_data.email)
user = await authenticate_user_by_email(user_data.email, user_data.password)
access_token = create_access_token({"sub": str(user.id)})
response.set_cookie(key="black_phoenix_access_token", value=access_token, httponly=True)