-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
53 lines (40 loc) · 1.73 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
import logging
import uuid
from fastapi import FastAPI, File, Request, status, HTTPException
from pydantic import BaseModel, Field
from motor.motor_asyncio import AsyncIOMotorClient
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
log = logging.getLogger('uvicorn')
class ImageTemplate(BaseModel):
id: str = Field(default_factory=uuid.uuid4, alias="_id")
template_name: str = Field(...)
encoded_image: bytes = File(...)
class Config:
allow_population_by_field_name = True
schema_extra = {
"example": {
"id": "00010203-0405-0607-0809-0a0b0c0d0e0f",
"template_name": "Template ABC",
"encoded_image": "Image in base64"
}
}
app = FastAPI()
@app.on_event("startup")
async def startup_db_client():
app.mongodb_client = AsyncIOMotorClient('mongodb://localhost:27017')
app.mongodb = app.mongodb_client['docs']
@app.on_event("shutdown")
async def shutdown_db_client():
app.mongodb_client.close()
@app.post('/register')
async def register(request: Request, newTemplate: ImageTemplate):
task = jsonable_encoder(newTemplate)
new_task = await request.app.mongodb["receipts"].insert_one(task)
log.info('Template Name {}, With Id {} Successfully Registered'.format(newTemplate.template_name, new_task.inserted_id))
return JSONResponse(status_code=status.HTTP_201_CREATED,content=new_task.inserted_id)
@app.post('/view')
async def view(request: Request, template_name: str):
if (task := await request.app.mongodb["receipts"].find_one({"template_name": template_name})) is not None:
return task
raise HTTPException(status_code=404, detail=f"Template {template_name} not found")