File tree Expand file tree Collapse file tree 3 files changed +25
-12
lines changed
Expand file tree Collapse file tree 3 files changed +25
-12
lines changed Original file line number Diff line number Diff line change 1- # from pymongo import MongoClient
1+ from motor . motor_asyncio import AsyncIOMotorClient
22
3- # client = MongoClient("mongodb://localhost:27017/")
4- # db = client["jsoned_db"]
5- # schemas_collection = db["schemas"]
3+ from jsoned .settings import settings
64
5+ client : AsyncIOMotorClient | None = None
6+ database = None
7+ schemas_collection = None
78
8- from motor .motor_asyncio import AsyncIOMotorClient
99
10- # MongoDB Driver
11- client = AsyncIOMotorClient ("mongodb://localhost:27017" )
12- database = client .jsoned_db
13- schemas_collection = database .schemas
10+ async def connect_to_mongo ():
11+ global client , database , schemas_collection
12+
13+ client = AsyncIOMotorClient (settings .MONGO_URI )
14+ database = client .jsoned_db
15+ schemas_collection = database .schemas
16+
17+ # create index once on startup
18+ await schemas_collection .create_index ("title" , unique = True )
19+
1420
15- # Ensure that the `title` field is unique
16- schemas_collection .create_index ([("title" , 1 )], unique = True )
21+ async def close_mongo ():
22+ if client is not None :
23+ client .close ()
Original file line number Diff line number Diff line change 44from starlette .middleware .cors import CORSMiddleware
55
66from jsoned .api .api_v1 .api import api_router
7+ from jsoned .database import close_mongo , connect_to_mongo
78from jsoned .settings import settings
89
910
1011@asynccontextmanager
1112async def app_init (app : FastAPI ):
13+ await connect_to_mongo ()
14+
1215 app .include_router (api_router , prefix = settings .API_V1_STR )
1316 yield
1417
18+ await close_mongo ()
19+
1520
1621app = FastAPI (
1722 title = settings .PROJECT_NAME ,
@@ -22,7 +27,7 @@ async def app_init(app: FastAPI):
2227if settings .BACKEND_CORS_ORIGINS :
2328 app .add_middleware (
2429 CORSMiddleware ,
25- allow_origins = settings .BACKEND_CORS_ORIGINS ,
30+ allow_origins = [ str ( o ) for o in settings .BACKEND_CORS_ORIGINS ] ,
2631 allow_credentials = True ,
2732 allow_methods = ["*" ],
2833 allow_headers = ["*" ],
Original file line number Diff line number Diff line change @@ -9,6 +9,7 @@ class Settings(BaseSettings):
99 "http://localhost" ,
1010 "http://localhost:3000" ,
1111 ]
12+ MONGO_URI : AnyHttpUrl = "mongodb://localhost:27017"
1213
1314
1415settings = Settings ()
You can’t perform that action at this time.
0 commit comments