Добавлен Middleware для обработки CORS-запросов

Этот коммит содержится в:
Глеб Иваницкий 2024-08-28 21:16:01 +03:00
родитель e38883578e
Коммит 3df0db1bee

Просмотреть файл

@ -1,6 +1,7 @@
import asyncio
from typing import Callable
from fastapi import FastAPI, Response, Body
from fastapi import FastAPI, Request, Response, Path, Body
from fastapi.websockets import WebSocket, WebSocketDisconnect
from fastapi.responses import JSONResponse
@ -45,14 +46,14 @@ api = FastAPI(
scripts = [
{
'id': 1,
'id': 0,
'name': 'Текущее состояние сотрудников',
'time': '0 11 * * 1-5',
'messageNumber': '1 вопрос',
'isEnabled': True,
},
{
'id': 2,
'id': 1,
'name': 'Планы на обед',
'time': '45 11 * * 1-5',
'messageNumber': '2 вопроса',
@ -64,21 +65,25 @@ scripts = [
scripts_cm = ConnectionManager()
# TODO(Development-only headers)
cors = {
'Access-Control-Allow-Methods': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Origin': '*',
}
@api.middleware('http')
async def function(
request: Request,
callback: Callable,
):
response: Response = await callback(request)
response.headers.append('Access-Control-Allow-Methods', '*')
response.headers.append('Access-Control-Allow-Headers', '*')
response.headers.append('Access-Control-Allow-Origin', '*')
return response
@api.options(
path='/api/scripts',
path='/{path:path}',
)
async def _():
return Response(
headers=cors,
)
async def _(
path: str,
):
return Response()
@api.get(
@ -86,21 +91,19 @@ async def _():
)
async def _():
return JSONResponse(
content=scripts,
content=[
script
for script in scripts
if script is not None
],
status_code=200,
headers=cors,
)
@api.put(
@api.post(
path='/api/scripts',
)
async def _(
script_id: int = Body(
alias='id',
validation_alias='id',
serialization_alias='id',
),
name: str = Body(),
time: str = Body(),
message_number: str = Body(
@ -114,14 +117,55 @@ async def _(
serialization_alias='isEnabled',
),
):
i = script_id - 1
scripts[i]['name'] = name
scripts[i]['time'] = time
scripts[i]['messageNumber'] = message_number
scripts[i]['isEnabled'] = is_enabled
script = {
'id': len(scripts),
'name': name,
'time': time,
'messageNumber': message_number,
'isEnabled': is_enabled,
},
scripts.append(script)
return Response(
status_code=201,
headers=cors,
)
@api.put(
path='/api/scripts/{script_id}',
)
async def _(
script_id: int = Path(),
name: str = Body(),
time: str = Body(),
message_number: str = Body(
alias='messageNumber',
validation_alias='messageNumber',
serialization_alias='messageNumber',
),
is_enabled: bool = Body(
alias='isEnabled',
validation_alias='isEnabled',
serialization_alias='isEnabled',
),
):
scripts[script_id]['name'] = name
scripts[script_id]['time'] = time
scripts[script_id]['messageNumber'] = message_number
scripts[script_id]['isEnabled'] = is_enabled
return Response(
status_code=201,
)
@api.delete(
path='/api/scripts/{script_id}',
)
async def _(
script_id: int = Path(),
):
scripts[script_id] = None
return Response(
status_code=204,
)