-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.py
77 lines (63 loc) · 2.04 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
'''
Generate events that go to the browser with Server Sent Events (SSE).
Materialize will push events whenever someone's bid has won an auction.
'''
import logging
from psycopg_pool import AsyncConnectionPool
from psycopg import conninfo
from sse_starlette.sse import EventSourceResponse
from fastapi import FastAPI, Request, Query
from fastapi.logger import logger
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
from config import config
from event_generator import event_generator, WinningBid
# Logging stuff
_logger = logging.getLogger('uvicorn.error')
# Connect _logger with FastAPI's logging
logger.handlers = _logger.handlers
# Init FastAPI app
app = FastAPI()
origins = [
"http://localhost",
"http://localhost:3000",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.on_event("startup")
def open_pool():
"""create database connection pool"""
app.state.pool = AsyncConnectionPool(
conninfo = conninfo.make_conninfo(
user = config["MZ_USER"],
dbname = config["MZ_DB"],
host = config["MZ_HOST"],
password = config["MZ_PASSWORD"],
port = 6875,
sslmode = 'require',
application_name = 'FastAPI',
options = config["options"],
),
max_size = 500,
min_size = 5
)
@app.on_event("shutdown")
async def close_pool():
"""close database connection pool"""
await app.state.pool.close()
@app.get("/")
async def root():
'''Shill Materialize'''
return {"message": "Hello world. Check out materialize.com!"}
@app.get("/subscribe/", response_model=WinningBid)
async def message_stream(request: Request, amount: list[int] | None = Query(default=None)):
'''Retrieve events from the event generator for SSE'''
return (EventSourceResponse(event_generator(request, app.state.pool, amount)))
if __name__ == "__main__":
logger.setLevel(_logger.level)
uvicorn.run(app, host="127.0.0.1", port=8000)