-
Notifications
You must be signed in to change notification settings - Fork 3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[MongoDB] 환경 설정, 코드 #19
Labels
📚 documentation
Improvements or additions to documentation
Comments
init.py 파일from motor.motor_asyncio import AsyncIOMotorClient
from odmantic import AIOEngine
# from app.config import MONGO_DB_NAME, MONGO_URL
MONGO_DB_NAME = 'baekdb'
MONGO_URL = 'mongodb+srv://baek:[email protected]/test'
class MongoDB:
def __init__(self):
self.client = None
self.engine = None
def connect(self):
self.client = AsyncIOMotorClient(MONGO_URL)
self.engine = AIOEngine(motor_client=self.client, database=MONGO_DB_NAME)
print("DB와 성공적으로 연결이 되었습니다.")
def close(self):
self.client.close()
mongodb = MongoDB() image.pyfrom odmantic import Model
class ImageModel(Model):
inputimage: str # 사용자가 업로드한 사진
cloudimage: str # 어떤 구름 사진을 선택했는지
class Config:
collection = "users" main.py 파일에 import 목록from fastapi import FastAPI, UploadFile, File, Response
import io
from io import BytesIO
from typing import List, Union, Optional, Dict, Any
from app.my_predict import get_prediction
from PIL import Image
import PIL
### db 관련 추가 import
from app.models import mongodb
from app.models.image import ImageModel
app = FastAPI() db에 데이터 저장 및 가져오기 (테스팅)
### 업로드한 이미지 db에 넣고 빼오기 테스트
save_image = ImageModel(inputimage='img_byte_arr', cloudimage='cloud2')
print(await mongodb.engine.save(save_image)) # db에 저장
# 데이터 가져오기
cloud_images = await mongodb.engine.find(ImageModel)
print('db에 있는 데이터 :', cloud_images)
# for문으로 하나씩 빼면 될 듯
for i in cloud_images:
print(i.inputimage) |
경륜님 main.py에서 @app.on_event("startup") 같은 |
@app.on_event("startup")
def on_app_start():
"""before app starts"""
mongodb.connect()
@app.on_event("shutdown")
def on_app_shutdown():
"""after app shutdown"""
mongodb.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Background
Content
install packages
app 폴더 안에 models 폴더 생성
__init__.py
,image.py
(db 데이터 관련 파일)이 있으면 됩니다.참고자료 : https://github.com/amamov/teaching-async-python/tree/main/6-%EC%8B%A4%EC%A0%84-%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8-%EC%BD%9C%EB%A0%89%ED%84%B0%EC%8A%A4/6/app
The text was updated successfully, but these errors were encountered: