Skip to content

Commit

Permalink
Merge pull request #156 from MikiEremiki/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
MikiEremiki authored Mar 14, 2024
2 parents 9b9795d + 8d98065 commit ff3cc26
Show file tree
Hide file tree
Showing 41 changed files with 2,220 additions and 567 deletions.
31 changes: 31 additions & 0 deletions .github/workflows/fastapi_image.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
name: ci

on:
push:
branches:
- main

jobs:
build:
runs-on: ubuntu-latest
steps:
-
name: Checkout
uses: actions/checkout@v4
-
name: Login to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
-
name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
-
name: Build and push
uses: docker/build-push-action@v5
with:
context: .
dockerfile: Dockerfile-server
push: true
tags: ${{ secrets.DOCKER_USERNAME }}/baby_domik_fastapi:latest
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,5 @@ config/*
settings.py
/src/utilities/pickle/ud_ids/
/src/utilities/pickle/user_ids
**/sql_files/
docker-compose-*
3 changes: 1 addition & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,4 @@ WORKDIR /app/src
RUN --mount=type=bind,source=requirements.txt,target=requirements.txt \
python -m pip install -r requirements.txt

COPY /src .
CMD python3 -m bot run
COPY /src .
11 changes: 11 additions & 0 deletions Dockerfile-server
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
FROM python:3.12-slim as base

ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1

WORKDIR /app

RUN --mount=type=bind,source=requirements-server.txt,target=requirements-server.txt \
python -m pip install -r requirements-server.txt

COPY /src/api/fastapi_nats.py .
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ ___

`docker image pull mikieremiki/baby_domik_bot`

Для создания автомиграции
`alembic -c 'config/alembic.ini' revision
--autogenerate -m 'init'`

Для запуска миграции
`docker compose --profile migration up -d`

Expand All @@ -32,6 +36,9 @@ ___

`alembic -c 'config/alembic.ini' downgrade base`

`.\.venv\Scripts\alembic -c 'config/alembic.ini' upgrade +1`
- запуск из PS

Альтернативные варианты:
- можно подключится к контейнеру бота и из под него
сделать миграции
Expand Down
74 changes: 65 additions & 9 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ services:
context: .
image: baby_domik:v1
restart: always
# depends_on:
# postgres:
# condition: service_healthy
depends_on:
postgres:
condition: service_healthy
networks:
- network
environment:
Expand All @@ -20,6 +20,8 @@ services:
- ./config/settings.py:/app/src/settings/settings.py
- ./src/db/data:/app/src/db/data
- ./src/log/archive:/app/src/log/archive
command: faststream run bot:fast_stream

postgres:
profiles: [ "all", "db" ]
container_name: postgres
Expand All @@ -34,11 +36,11 @@ services:
networks:
- network
healthcheck:
test: [ "CMD", "pg_isready", "-U", "$POSTGRES_USER", "-d",
"$POSTGRES_DB" ]
test: [ "CMD", "pg_isready", "-U", "$POSTGRES_USER", "-d", "$POSTGRES_DB" ]
interval: 10s
timeout: 5s
retries: 5

migration:
profiles: [ "migration" ]
container_name: migration
Expand All @@ -57,8 +59,9 @@ services:
environment:
- CONFIG_PATH=${CONFIG_PATH:-config/}
working_dir: /app
command: [ "alembic", "-c", "config/alembic.ini", "upgrade", "head" ]
# command: [ "alembic", "-c", "config/alembic.ini", "downgrade", "base" ]
command: [ "alembic", "-c", "config/alembic.ini", "upgrade", "+1" ]
# command: [ "alembic", "-c", "config/alembic.ini", "downgrade", "-1" ]

pgadmin:
profiles: [ "pgadmin" ]
container_name: pgadmin
Expand All @@ -74,11 +77,64 @@ services:
networks:
- network

nats:
profiles: [ "nats", "1" ]
container_name: nats
image: nats:2.10.11-alpine
restart: unless-stopped
ports:
- '4222:4222'
- '6222:6222'
- '8222:8222'
volumes:
- nats:/nats
- ./config/server.conf:/etc/nats/server.conf
networks:
- network
command: 'nats-server -c /etc/nats/server.conf'

nats-cli:
profiles: [ "nats-cli" ]
container_name: nats-cli
image: natsio/nats-box
restart: unless-stopped
networks:
- network
command: [ "tail", "-f", "/dev/null" ]

fastapi_server:
profiles: [ "fastapi", "1" ]
container_name: fastapi_server
build:
context: .
dockerfile: Dockerfile-server
image: baby_domik_fastapi:v1
restart: unless-stopped
networks:
- network
depends_on:
- nats

nginx:
profiles: [ "nginx", "1" ]
container_name: nginx
image: nginx:latest
restart: unless-stopped
ports:
- "443:443"
volumes:
- ./config/nginx.conf:/etc/nginx/nginx.conf
- ./config/server.crt:/etc/nginx/server.crt
- ./config/server.key:/etc/nginx/server.key
networks:
- network
depends_on:
- fastapi_server

volumes:
db:
# data:
# logs:
pgadmin:
nats:

networks:
network:
Expand Down
3 changes: 3 additions & 0 deletions requirements-server.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
uvicorn
fastapi
faststream[nats]
10 changes: 8 additions & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,16 @@ google-auth-oauthlib
psycopg
psycopg-binary
pydantic
pydantic_core
pydantic-settings
pytest
python-telegram-bot[ext]~=20.7
python-telegram-bot[ext]~=20.8
PyYAML
requests
sqlalchemy
typing_extensions
typing_extensions
yookassa~=3.0.1
uvicorn
fastapi
faststream
nats-py==2.6.0
25 changes: 25 additions & 0 deletions src/api/broker_nats.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from faststream import Logger
from faststream.nats import JStream, NatsMessage, NatsBroker
from telegram.ext import Application
from yookassa.domain.notification import WebhookNotificationFactory

from settings.settings import nats_url


def connect_to_nats(app: Application,
webhook_notification_factory: WebhookNotificationFactory):
broker = NatsBroker(nats_url)
stream = JStream(name="baby_domik", max_msgs=100, max_age=60*60*24*7)

@broker.subscriber("bot", stream=stream, durable='yookassa')
async def nats_handler(
data: dict,
logger: Logger,
nats_message: NatsMessage,
):
logger.info(f'{data=}')
notification = webhook_notification_factory.create(data)
# print(f'{nats_message=}')
await app.update_queue.put(notification)

return broker
50 changes: 50 additions & 0 deletions src/api/fastapi_nats.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import asyncio
from dataclasses import dataclass

import uvicorn
from fastapi import FastAPI, Response
from faststream.nats.fastapi import NatsRouter, Logger, NatsBroker

router = NatsRouter('nats://nats:4222')


@dataclass
class WebhookNotification:
type: str
event: str
object: dict


@router.get("/")
async def hello_http():
return "Hello, HTTP!"


@router.post("/yookassa")
async def post_notification(
message: WebhookNotification,
logger: Logger,
broker: NatsBroker
):
logger.info(message)
await broker.publish(message, 'bot', stream="baby_domik")
return Response(status_code=200)


app = FastAPI(lifespan=router.lifespan_context)
app.include_router(router, tags=["main requests"])


async def main():
webserver = uvicorn.Server(
config=uvicorn.Config(
app=app,
host='0.0.0.0',
port=8443,
)
)
await webserver.serve()


if __name__ == "__main__":
asyncio.run(main())
42 changes: 42 additions & 0 deletions src/api/yookassa_connect.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from yookassa.domain import models
from settings.settings import URL_BOT


def create_param_payment(
price: [str, int],
description: str,
return_url: str = URL_BOT,
*,
quantity: str = "1",
payment_method_type: str = "sbp", # "yoo_money"
payment_mode: str = "full_payment",
payment_subject: str = "service",
**kwargs,
) -> dict:
return {
"amount": models.Amount(value=price, currency="RUB"),
"payment_method_data": {
"type": payment_method_type
},
"confirmation": {
"type": "redirect",
"return_url": return_url
},
"capture": True,
'receipt': {
"customer": {
'email': '[email protected]'
},
"items": [
{
"description": description,
"quantity": quantity,
"amount": models.Amount(value=price, currency="RUB"),
"vat_code": "1",
"payment_mode": payment_mode,
"payment_subject": payment_subject,
}
]
},
'metadata': kwargs
}
Loading

0 comments on commit ff3cc26

Please sign in to comment.