Repository navigation
Implement ASGI application with fibonacci, factorial, and mean endpoints #63
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
K0l0b04ek
wants to merge
5
commits into
L1mple:main
Choose a base branch
from
K0l0b04ek:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
b39890c
Implement ASGI application with fibonacci, factorial, and mean endpoints
K0l0b04ek cc5eb00
Merge branch 'L1mple:main' into main
K0l0b04ek 172918a
Realized HW2 without additional task
K0l0b04ek 97b40c1
Merge branch 'L1mple:main' into main
K0l0b04ek 9dc8337
hw3 "deployed and dashboarded"
K0l0b04ek File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,128 @@ | ||
| import json | ||
| from urllib.parse import parse_qs | ||
| from typing import Any, Awaitable, Callable | ||
|
|
||
|
|
||
| BAD_REQUEST = None, 400 | ||
| UNPROCESSABLE_ENTITY = None, 422 | ||
| SUCCEFULL = lambda result: ({"result": result}, 200) | ||
|
|
||
|
|
||
| async def check_integer(n_str): | ||
| try: | ||
| n = int(n_str) | ||
| except (ValueError, TypeError): | ||
| return None | ||
| return n | ||
|
|
||
|
|
||
| async def fibonacci(request): | ||
| n = await check_integer(request['path_params']['n']) | ||
| if n is None: | ||
| return UNPROCESSABLE_ENTITY | ||
| if n < 0: | ||
| return BAD_REQUEST | ||
| def fib(n): | ||
| if n <= 1: | ||
| return n | ||
| a, b = 0, 1 | ||
| for _ in range(2, n + 1): | ||
| a, b = b, a + b | ||
| return b | ||
| result = fib(n) | ||
| return SUCCEFULL(result) | ||
|
|
||
|
|
||
| async def factorial(request): | ||
| query_params = request['query_params'] | ||
| if 'n' not in query_params: | ||
| return UNPROCESSABLE_ENTITY | ||
| n = await check_integer(query_params['n']) | ||
| if n is None: | ||
| return UNPROCESSABLE_ENTITY | ||
| if n < 0: | ||
| return BAD_REQUEST | ||
| result = 1 | ||
| for i in range(1, n + 1): | ||
| result *= i | ||
| return SUCCEFULL(result) | ||
|
|
||
|
|
||
| async def mean(request): | ||
| body = request.get('body') | ||
| if body is None or body == '': | ||
| return UNPROCESSABLE_ENTITY | ||
| try: | ||
| data = json.loads(body) | ||
| except (json.JSONDecodeError, TypeError): | ||
| return UNPROCESSABLE_ENTITY | ||
| if not isinstance(data, list): | ||
| return UNPROCESSABLE_ENTITY | ||
| if len(data) == 0: | ||
| return BAD_REQUEST | ||
| try: | ||
| numbers = [float(x) for x in data] | ||
| except (TypeError, ValueError): | ||
| return UNPROCESSABLE_ENTITY | ||
| result = sum(numbers) / len(numbers) | ||
| return SUCCEFULL(result) | ||
|
|
||
|
|
||
| async def send_json_response(send, status_code, data): | ||
| json_bytes = json.dumps(data, ensure_ascii=False).encode('utf-8') | ||
| await send({ | ||
| 'type': 'http.response.start', | ||
| 'status': status_code, | ||
| 'headers': [ | ||
| [b'content-type', b'application/json; charset=utf-8'], | ||
| [b'content-length', str(len(json_bytes)).encode('ascii')], | ||
| ], | ||
| }) | ||
| await send({ | ||
| 'type': 'http.response.body', | ||
| 'body': json_bytes, | ||
| }) | ||
|
|
||
|
|
||
| def parse_path(path): | ||
| path = path.rstrip('/') | ||
| parts = path.split('/') | ||
| if len(parts) == 3 and parts[1] == 'fibonacci': | ||
| return 'fibonacci', {'n': parts[2]} | ||
| if len(parts) == 2 and parts[1] == 'factorial': | ||
| return 'factorial', {} | ||
| if len(parts) == 2 and parts[1] == 'mean': | ||
| return 'mean', {} | ||
| return None, {} | ||
|
|
||
|
|
||
| async def read_body(receive): | ||
| body = b'' | ||
| while True: | ||
| message = await receive() | ||
| body += message.get('body', b'') | ||
| if not message.get('more_body', False): | ||
| break | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. можно дополнительно обрабатывать disconnect |
||
| return body | ||
|
|
||
|
|
||
| async def handle_lifespan(receive, send): | ||
| 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'}) | ||
| return | ||
|
|
||
|
|
||
| HANDLERS = { | ||
| 'fibonacci': fibonacci, | ||
| 'factorial': factorial, | ||
| 'mean': mean, | ||
| } | ||
|
|
||
|
|
||
| async def application( | ||
| scope: dict[str, Any], | ||
| receive: Callable[[], Awaitable[dict[str, Any]]], | ||
|
|
@@ -12,7 +134,35 @@ async def application( | |
| receive: Корутина для получения сообщений от клиента | ||
| send: Корутина для отправки сообщений клиенту | ||
| """ | ||
| # TODO: Ваша реализация здесь | ||
| if scope["type"] == "lifespan": | ||
| await handle_lifespan(receive, send) | ||
| return | ||
| if scope["type"] != "http": | ||
| return | ||
| path = scope['path'] | ||
| method = scope['method'] | ||
| query_string = scope['query_string'] | ||
| query_params = {k: v[0] for k, v in parse_qs(query_string.decode('utf-8')).items()} | ||
| body_bytes = await read_body(receive) | ||
| body = body_bytes.decode('utf-8') if len(body_bytes) > 0 else None | ||
| endpoint, path_params = parse_path(path) | ||
| if endpoint is None: | ||
| await send_json_response(send, 404, {'error': 'Not Found'}) | ||
| return | ||
| request = { | ||
| 'path': path, | ||
| 'method': method, | ||
| 'query_params': query_params, | ||
| 'path_params': path_params, | ||
| 'body': body, | ||
| } | ||
| handler = HANDLERS[endpoint] | ||
| result, status_code = await handler(request) | ||
| if result is None: | ||
| await send_json_response(send, status_code, {'error': 'Invalid request'}) | ||
| else: | ||
| await send_json_response(send, status_code, result) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| import uvicorn | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| FROM python:3.12 AS base | ||
|
|
||
| ARG PYTHONFAULTHANDLER=1 \ | ||
| PYTHONUNBUFFERED=1 \ | ||
| PYTHONHASHSEED=random \ | ||
| PIP_NO_CACHE_DIR=on \ | ||
| PIP_DISABLE_PIP_VERSION_CHECK=on \ | ||
| PIP_DEFAULT_TIMEOUT=500 | ||
|
|
||
| RUN apt-get update && apt-get install -y gcc | ||
| RUN python -m pip install --upgrade pip | ||
|
|
||
| WORKDIR $APP_ROOT/src | ||
| COPY . ./ | ||
|
|
||
| ENV VIRTUAL_ENV=$APP_ROOT/src/.venv \ | ||
| PATH=$APP_ROOT/src/.venv/bin:$PATH | ||
|
|
||
| RUN pip install -r requirements.txt | ||
|
|
||
| FROM base AS local | ||
|
|
||
| CMD ["uvicorn", "shop_api.main:app", "--port", "8080", "--host", "0.0.0.0"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| version: "3" | ||
|
|
||
| services: | ||
|
|
||
| local: | ||
| build: | ||
| context: . | ||
| dockerfile: ./Dockerfile | ||
| target: local | ||
| restart: always | ||
| ports: | ||
| - 8080:8080 | ||
|
|
||
| grafana: | ||
| image: grafana/grafana:latest | ||
| ports: | ||
| - 3000:3000 | ||
| restart: always | ||
|
|
||
| prometheus: | ||
| image: prom/prometheus | ||
| volumes: | ||
| - ./settings/prometheus/:/etc/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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -7,3 +7,5 @@ pytest>=7.4.0 | |
| pytest-asyncio>=0.21.0 | ||
| httpx>=0.27.2 | ||
| Faker>=37.8.0 | ||
|
|
||
| prometheus-fastapi-instrumentator | ||
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| global: | ||
| scrape_interval: 10s | ||
| evaluation_interval: 10s | ||
|
|
||
| scrape_configs: | ||
| - job_name: shop-api-local | ||
| metrics_path: /metrics | ||
| static_configs: | ||
| - targets: | ||
| - local:8080 |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
можно это импортировать из http.HTTPStatus