Skip to content
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

Open
baekkr95 opened this issue May 30, 2022 · 3 comments
Open

[MongoDB] 환경 설정, 코드 #19

baekkr95 opened this issue May 30, 2022 · 3 comments
Labels
📚 documentation Improvements or additions to documentation

Comments

@baekkr95
Copy link
Contributor

baekkr95 commented May 30, 2022

Background

  • mongo db 연결부터 데이터 사용 코드 공유

Content

install packages

  • pip install odmantic
  • pip install "pymongo[srv]"

app 폴더 안에 models 폴더 생성

image

  • 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

@baekkr95 baekkr95 added the 📚 documentation Improvements or additions to documentation label May 30, 2022
@baekkr95
Copy link
Contributor Author

baekkr95 commented May 30, 2022

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.py

from 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에서 사용하는 변수가 inputimage과 cloudimage라고 치면,
     ### 업로드한 이미지 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)

@omocomo
Copy link
Member

omocomo commented May 31, 2022

경륜님 main.py에서 @app.on_event("startup") 같은
db를 시작하고 끝내는 부분이 있었던 것 같은데 해당 부분 공유 가능할까요?

@baekkr95
Copy link
Contributor Author

경륜님 main.py에서 @app.on_event("startup") 같은 db를 시작하고 끝내는 부분이 있었던 것 같은데 해당 부분 공유 가능할까요?

main.py 맨 밑에 넣었습니다.

@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
Labels
📚 documentation Improvements or additions to documentation
Projects
None yet
Development

No branches or pull requests

2 participants