Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
135 changes: 132 additions & 3 deletions hw1/app.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from typing import Any, Awaitable, Callable

import json
import math
from urllib.parse import parse_qs

async def application(
scope: dict[str, Any],
Expand All @@ -12,8 +14,135 @@ async def application(
receive: Корутина для получения сообщений от клиента
send: Корутина для отправки сообщений клиенту
"""
# TODO: Ваша реализация здесь

if scope['type'] == 'lifespan':
while True:
message = await receive()
if message['type'] == 'lifespan.startup':
await send({'type': 'lifespan.startup.complete'})
elif message['type'] == 'lifespan.shutdown':
await send({'type': 'lifespan.shutdown.complete'})
break
return

if scope['type'] != 'http':
return

method = scope['method']
path = scope['path']
query_string = scope.get('query_string', b'').decode('utf-8')
query_params = parse_qs(query_string)

async def send_response(status_code, body):
await send({
'type':'http.response.start',
'status': status_code,
'headers': [
[b'content-type', b'application/json'],
],
})
await send({
'type': 'http.response.body',
'body': json.dumps(body).encode('utf-8'),
})

async def receive_body():
body = b''
while True:
message = await receive()
if message['type'] == 'http.request':
body += message.get('body', b'')
if not message.get('more_body', False):
break
if body:
try:
return json.loads(body.decode('utf-8'))
except json.JSONDecodeError:
return None
return None

if method != 'GET':
await send_response(404, {})
return

try:
if path == '/factorial':
if 'n' not in query_params or not query_params['n'][0]:
await send_response(422, {})
return

try:
n = int(query_params['n'][0])
if n < 0:
await send_response(400, {})
return

result = math.factorial(n)
await send_response(200, {'result': result})
return
except ValueError:
await send_response(422, {})
return

elif path.startswith('/fibonacci/'):
try:
n_str = path[11:]
if not n_str:
await send_response(422, {})
return
n = int(n_str)

if n < 0:
await send_response(400, {})
return
if n == 0:
await send_response(200, {'result': 0})
return
elif n == 1:
await send_response(200, {'result': 1})
return
else:
a, b = 0, 1
for _ in range(2, n + 1):
a, b = b, a + b
await send_response(200, {'result': b})
return

except Exception:
await send_response(422, {})
return

elif path == '/mean':
body = await receive_body()

if body is None:
await send_response(422, {})
return

if not isinstance(body, list):
await send_response(400, {})
return

if len(body) == 0:
await send_response(400, {})
return
try:
numbers = [float(x) for x in body]
mean_value = sum(numbers) / len(numbers)
await send_response(200, {'result': mean_value})
return
except (ValueError, TypeError):
await send_response(400, {})
return

else:
await send_response(404, {})
return

except Exception:
await send_response(500, {})
return

if __name__ == "__main__":
import uvicorn
uvicorn.run("app:application", host="0.0.0.0", port=8000, reload=True)
uvicorn.run("app:application", host="0.0.0.0", port=8000, reload=True)
26 changes: 26 additions & 0 deletions hw2/hw/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
__pycache__
*.pyc
*.pyo
*.pyd
.Python
*.so
*.egg
*.egg-info
dist
build
.git
.gitignore
.env
.venv
env/
venv/
ENV/
.pytest_cache
.coverage
htmlcov/
*.log
.DS_Store
Thumbs.db
README.md
docker-compose.yml
Dockerfile
21 changes: 21 additions & 0 deletions hw2/hw/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@

FROM python:3.13-slim

WORKDIR /app

RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*

COPY requirements.txt .

RUN pip install --no-cache-dir -r requirements.txt

RUN pip install --no-cache-dir prometheus-client prometheus-fastapi-instrumentator

COPY shop_api/ ./shop_api/

EXPOSE 8000


ENV PYTHONUNBUFFERED=1

CMD ["uvicorn", "shop_api.main:app", "--host", "0.0.0.0", "--port", "8000"]
65 changes: 65 additions & 0 deletions hw2/hw/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
version: '3.8'

services:
shop-api:
build:
context: .
dockerfile: Dockerfile
container_name: shop-api
ports:
- "8000:8000"
networks:
- monitoring
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 10s

prometheus:
image: prom/prometheus:latest
container_name: prometheus
ports:
- "9090:9090"
volumes:
- ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml
- prometheus-data:/prometheus
command:
- '--config.file=/etc/prometheus/prometheus.yml'
- '--storage.tsdb.path=/prometheus'
- '--web.console.libraries=/usr/share/prometheus/console_libraries'
- '--web.console.templates=/usr/share/prometheus/consoles'
networks:
- monitoring
restart: unless-stopped
depends_on:
- shop-api

grafana:
image: grafana/grafana:latest
container_name: grafana
ports:
- "3000:3000"
volumes:
- grafana-data:/var/lib/grafana
- ./grafana/provisioning:/etc/grafana/provisioning
- ./grafana/dashboards:/var/lib/grafana/dashboards
environment:
- GF_SECURITY_ADMIN_USER=admin
- GF_SECURITY_ADMIN_PASSWORD=admin
- GF_USERS_ALLOW_SIGN_UP=false
networks:
- monitoring
restart: unless-stopped
depends_on:
- prometheus

networks:
monitoring:
driver: bridge

volumes:
prometheus-data:
grafana-data:
Loading