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

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

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

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