Skip to content

Commit 71322e9

Browse files
author
Alan Christie
committed
feat: Better use of response model
1 parent d9da43a commit 71322e9

File tree

1 file changed

+36
-21
lines changed

1 file changed

+36
-21
lines changed

app/app.py

Lines changed: 36 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,11 @@
55
import os
66
import sqlite3
77
from logging.config import dictConfig
8-
from typing import Any, Dict
8+
from typing import Any, Dict, List
99

1010
import aio_pika
1111
import shortuuid
12-
from fastapi import FastAPI, HTTPException, Response, WebSocket, status
12+
from fastapi import FastAPI, HTTPException, WebSocket, status
1313
from pydantic import BaseModel
1414

1515
# Configure logging
@@ -95,6 +95,27 @@ class EventStreamPostRequestBody(BaseModel):
9595
routing_key: str
9696

9797

98+
class EventStreamPostResponse(BaseModel):
99+
"""/event-stream/ POST response."""
100+
101+
id: int
102+
location: str
103+
104+
105+
class EventStreamItem(BaseModel):
106+
"""An individual event stream (returned in the GET response)."""
107+
108+
id: int
109+
location: str
110+
routing_key: str
111+
112+
113+
class EventStreamGetResponse(BaseModel):
114+
"""/event-stream/ POST response."""
115+
116+
event_streams: List[EventStreamItem]
117+
118+
98119
# Endpoints for the 'public-facing' event-stream web-socket API ------------------------
99120

100121

@@ -175,8 +196,8 @@ async def _get_from_queue(routing_key: str):
175196
# Endpoints for the 'internal' event-stream management API -----------------------------
176197

177198

178-
@app_internal.post("/event-stream/")
179-
def post_es(request_body: EventStreamPostRequestBody, response: Response):
199+
@app_internal.post("/event-stream/", status_code=status.HTTP_201_CREATED)
200+
def post_es(request_body: EventStreamPostRequestBody) -> EventStreamPostResponse:
180201
"""Create a new event-stream returning the endpoint location.
181202
182203
The AS provides a routing key to this endpoint and expects a event stream location
@@ -189,8 +210,6 @@ def post_es(request_body: EventStreamPostRequestBody, response: Response):
189210
"""
190211
# Generate am new (difficult to guess) UUID for the event stream...
191212
uuid_str: str = shortuuid.uuid()
192-
# And construct the location we'll be listening on...
193-
location: str = _get_location(uuid_str)
194213

195214
# Create a new ES record.
196215
# An ID is assigned automatically -
@@ -211,15 +230,12 @@ def post_es(request_body: EventStreamPostRequestBody, response: Response):
211230

212231
_LOGGER.info("Created %s", es)
213232

214-
response.status_code = status.HTTP_201_CREATED
215-
return {
216-
"id": es[0],
217-
"location": location,
218-
}
233+
# And construct the location we'll be listening on...
234+
return EventStreamPostResponse(id=es[0], location=_get_location(uuid_str))
219235

220236

221-
@app_internal.get("/event-stream/")
222-
def get_es():
237+
@app_internal.get("/event-stream/", status_code=status.HTTP_200_OK)
238+
def get_es() -> EventStreamGetResponse:
223239
"""Returns a list of the details of all existing event-streams,
224240
their IDs, locations, and routing keys."""
225241

@@ -229,16 +245,18 @@ def get_es():
229245
all_es = cursor.execute("SELECT * FROM es").fetchall()
230246
db.close()
231247

232-
event_streams = []
248+
event_streams: List[EventStreamItem] = []
233249
for es in all_es:
234250
location: str = _get_location(es[1])
235-
event_streams.append({"id": es[0], "location": location, "routing_key": es[2]})
251+
event_streams.append(
252+
EventStreamItem(id=es[0], location=location, routing_key=es[2])
253+
)
236254

237-
return {"event-streams": event_streams}
255+
return EventStreamGetResponse(event_streams=event_streams)
238256

239257

240-
@app_internal.delete("/event-stream/{es_id}")
241-
def delete_es(es_id: int, response: Response):
258+
@app_internal.delete("/event-stream/{es_id}", status_code=status.HTTP_204_NO_CONTENT)
259+
def delete_es(es_id: int):
242260
"""Destroys an existing event-stream."""
243261

244262
_LOGGER.info("Deleting event stream %s...", es_id)
@@ -262,6 +280,3 @@ def delete_es(es_id: int, response: Response):
262280
db.close()
263281

264282
_LOGGER.info("Deleted %s", es_id)
265-
266-
response.status_code = status.HTTP_204_NO_CONTENT
267-
return {}

0 commit comments

Comments
 (0)