Skip to content
Open

Hw3 #115

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
88 changes: 87 additions & 1 deletion hw1/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,93 @@ async def application(
receive: Корутина для получения сообщений от клиента
send: Корутина для отправки сообщений клиенту
"""
# TODO: Ваша реализация здесь
if scope["type"] == "lifespan":
while True:
message = await receive()
await send({"type": f"{message['type']}.complete"})

path = scope["path"].rstrip("/")
status = 404
result = None

if scope["method"] == "GET":
if path == "/factorial":
kvs = scope["query_string"].decode()
n = None
for kv in kvs.split("&"):
if "=" in kv:
k, v = kv.split("=", 1)
if k == "n":
n = v
status, result = compute_number(n, factorial)
elif path.startswith("/fibonacci/"):
status, result = compute_number(path.removeprefix("/fibonacci/"), fibonacci)
elif path == "/mean":
raw_bytes = await read_bytes(receive)
status, result = mean(raw_bytes)

await answer(send, status, result)


def compute_number(raw: str | None, func: Callable[[int], int]) -> tuple[int, int | None]:
try:
n = int(raw)
except (TypeError, ValueError):
return 422, None
if n < 0:
return 400, None
return 200, func(n)


def factorial(n: int) -> int:
ans = 1
for i in range(n):
ans *= (i + 1)
return ans


def fibonacci(n: int) -> int:
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a


def mean(body: bytes) -> tuple[int, float | None]:
try:
text = body.decode().strip()
numbers = [float(item) for item in text[1:-1].split(",") if item.strip()]
except ValueError:
return 422, None
if not numbers:
return 400, None
res = sum(numbers) / len(numbers)
return 200, res


async def read_bytes(receive: Callable[[], Awaitable[dict[str, Any]]]) -> bytes:
body = b""
has_more = True
while has_more:
message = await receive()
body += message.get("body", b"")
has_more = message.get("more_body", False)
return body


async def answer(send, status, result):
await send(
{
"type": "http.response.start",
"status": status,
"headers": [[b"content-type", b"application/json"]],
}
)
body = b""
if status == 200:
body = f'{{"result": {result}}}'.encode()
await send({"type": "http.response.body", "body": body})


if __name__ == "__main__":
import uvicorn
Expand Down
40 changes: 40 additions & 0 deletions hw2/grpc_example/ping_pb2.py

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 17 additions & 0 deletions hw2/grpc_example/ping_pb2.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from typing import ClassVar as _ClassVar, Optional as _Optional

DESCRIPTOR: _descriptor.FileDescriptor

class PingRequest(_message.Message):
__slots__ = ("message",)
MESSAGE_FIELD_NUMBER: _ClassVar[int]
message: str
def __init__(self, message: _Optional[str] = ...) -> None: ...

class PongResponse(_message.Message):
__slots__ = ("message",)
MESSAGE_FIELD_NUMBER: _ClassVar[int]
message: str
def __init__(self, message: _Optional[str] = ...) -> None: ...
140 changes: 140 additions & 0 deletions hw2/grpc_example/ping_pb2_grpc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
import warnings

import ping_pb2 as ping__pb2

GRPC_GENERATED_VERSION = '1.84.0'
GRPC_VERSION = grpc.__version__
_version_not_supported = False

try:
from grpc._utilities import first_version_is_lower
_version_not_supported = first_version_is_lower(GRPC_VERSION, GRPC_GENERATED_VERSION)
except ImportError:
_version_not_supported = True

if _version_not_supported:
raise RuntimeError(
f'The grpc package installed is at version {GRPC_VERSION},'
+ ' but the generated code in ping_pb2_grpc.py depends on'
+ f' grpcio>={GRPC_GENERATED_VERSION}.'
+ f' Please upgrade your grpc module to grpcio>={GRPC_GENERATED_VERSION}'
+ f' or downgrade your generated code using grpcio-tools<={GRPC_VERSION}.'
)


class ExampleStub:
"""Missing associated documentation comment in .proto file."""

def __init__(self, channel):
"""Constructor.

Args:
channel: A grpc.Channel.
"""
self.Ping = channel.unary_unary(
'/example.Example/Ping',
request_serializer=ping__pb2.PingRequest.SerializeToString,
response_deserializer=ping__pb2.PongResponse.FromString,
_registered_method=True)
self.PingStream = channel.stream_stream(
'/example.Example/PingStream',
request_serializer=ping__pb2.PingRequest.SerializeToString,
response_deserializer=ping__pb2.PongResponse.FromString,
_registered_method=True)


class ExampleServicer:
"""Missing associated documentation comment in .proto file."""

def Ping(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')

def PingStream(self, request_iterator, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')


def add_ExampleServicer_to_server(servicer, server):
rpc_method_handlers = {
'Ping': grpc.unary_unary_rpc_method_handler(
servicer.Ping,
request_deserializer=ping__pb2.PingRequest.FromString,
response_serializer=ping__pb2.PongResponse.SerializeToString,
),
'PingStream': grpc.stream_stream_rpc_method_handler(
servicer.PingStream,
request_deserializer=ping__pb2.PingRequest.FromString,
response_serializer=ping__pb2.PongResponse.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'example.Example', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
server.add_registered_method_handlers('example.Example', rpc_method_handlers)


# This class is part of an EXPERIMENTAL API.
class Example:
"""Missing associated documentation comment in .proto file."""

@staticmethod
def Ping(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(
request,
target,
'/example.Example/Ping',
ping__pb2.PingRequest.SerializeToString,
ping__pb2.PongResponse.FromString,
options,
channel_credentials,
insecure,
call_credentials,
compression,
wait_for_ready,
timeout,
metadata,
_registered_method=True)

@staticmethod
def PingStream(request_iterator,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.stream_stream(
request_iterator,
target,
'/example.Example/PingStream',
ping__pb2.PingRequest.SerializeToString,
ping__pb2.PongResponse.FromString,
options,
channel_credentials,
insecure,
call_credentials,
compression,
wait_for_ready,
timeout,
metadata,
_registered_method=True)
22 changes: 22 additions & 0 deletions hw2/hw/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
FROM python:3.13-slim AS base

ENV PYTHONFAULTHANDLER=1 \
PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
PYTHONHASHSEED=random \
PIP_NO_CACHE_DIR=on \
PIP_DISABLE_PIP_VERSION_CHECK=on \
PIP_DEFAULT_TIMEOUT=500

WORKDIR /app

COPY requirements.txt ./
RUN python -m pip install --upgrade pip && pip install -r requirements.txt

COPY shop_api ./shop_api

FROM base AS local

EXPOSE 8080

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

shop-api:
build:
context: .
dockerfile: ./Dockerfile
target: local
restart: always
ports:
- "8081:8080"

prometheus:
image: prom/prometheus:latest
volumes:
- ./settings/prometheus/:/etc/prometheus/
- 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"
ports:
- "9090:9090"
restart: always
depends_on:
- shop-api

grafana:
image: grafana/grafana:latest
environment:
GF_SECURITY_ADMIN_USER: admin
GF_SECURITY_ADMIN_PASSWORD: admin
GF_USERS_ALLOW_SIGN_UP: "false"
volumes:
- ./settings/grafana/provisioning/:/etc/grafana/provisioning/
- ./settings/grafana/dashboards/:/var/lib/grafana/dashboards/
- grafana-data:/var/lib/grafana
ports:
- "3000:3000"
restart: always
depends_on:
- prometheus

volumes:
prometheus-data:
grafana-data:
Binary file added hw2/hw/img/grafana.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added hw2/hw/img/prometheus.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 2 additions & 0 deletions hw2/hw/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
fastapi>=0.117.1
uvicorn>=0.24.0

prometheus-fastapi-instrumentator>=7.0.0

# Зависимости для тестирования
pytest>=7.4.0
pytest-asyncio>=0.21.0
Expand Down
Loading
Loading