MongoDB를 사용하여 FastAPI로 세탁 CRUD API 빌드 - 1

13408 단어 mongodbpython
MongoDB를 데이터베이스 기술로 지원하는 FastAPI를 사용하여 Laundry CRUD API 구축! 나는 프로젝트에서 MongoDB와 같은 클라우드 스토리지를 사용하여 보호, 가장 안정적인 백업 시스템, 어디서나 데이터에 쉽게 액세스할 수 있으며 가장 중요한 것은 액세스 비용이 저렴하다는 것입니다.

목차


  • Basic CRUD in a Laundry API
  • Installing FastAPI
  • Setting up MongoDB Atlas
  • Building each API Endpoints

  • 팝콘 들고 편하게 앉아서 가자🚀

    하지만 잠깐... MongoDB를 사용하는 기본 지식이 있습니까? 파이썬으로 프로그램을 작성해 보셨나요? 경우 예!! 그럼 당신은 여기에서 계속하기에 적합합니다. 아니오! 당황하지 마세요. 이 기사의 모든 단계를 단순화하여 다루었습니다.

    몽고DB??



    MongoDB가 무엇인지 궁금하십니까? 또는 어떻게 사용되고 있습니까?
    MongoDB는 SQL이 필요하지 않고 JSON과 같은 형식으로 데이터를 저장하는 문서 지향 데이터베이스 프로그램입니다.

    FastAPI??



    FastAPI는 Python으로 API를 구축하기 위한 최신의 빠른 프레임워크입니다. 단어를 빠르게 굵게 표시해야 했습니다! 이름에서 "FastAPI"를 의미하므로 매우 빠르고 쉽게 코딩할 수 있으며 자동으로 API에 대한 훌륭한 문서를 생성합니다. 달콤하지요! 나는 당신이 이것을 좋아할 것이라는 것을 압니다.

    한 잔 하고 한 모금, 움직이자🚀

    Laundry API의 기본 CRUD

    A laundry service API should require the following basic CRUD(Create Read Update Delete) functions in managing bookings of services(laundry pickups, Updating status of service, canceling pickups, and so on).

    Since this article is part one in building a laundry service API, we will focus on login/signup API endpoints(with no authentications yet).

    Endpoints to be built in this article includes:

    • Login
    • signup
    • update-profile
    • book-service
    • update-pickup

    FastAPI 설치

    After highlighting the endpoints we're working on in this article, let's install FastAPI! You should have VSCode and your preferred browser ready(I use Chrome).

    Firstly, open a folder(preferably on your desktop making it easy to locate), name it "laundryAPI".
    Open the folder with VSCode and create a file "main.py"

    Now open your VSCode Terminal and type this:
    Note: You can create a virtual environment but not necessary
    pip install fastapi

    You will need an ASGI server for production such as Uvicorn:
    pip install uvicorn

    After successfully installing FastAPI, let's write our first API program for our root endpoint(homepage):
    In the main.py, type the following code;

    from typing import Optional
    
    from fastapi import FastAPI
    
    app = FastAPI()
    
    
    @app.get("/")
    def index():
        return {"message": "Hello World"}
    
    Let's run and test our API:
    type this in the terminal to run the code;
    uvicorn main:app --reload
    Our API should be running on
    http://127.0.0.1:8000

    API를 성공적으로 구축했습니다 🎉🎉

    MongoDB Atlas 설정

    We successfully wrote our first FastAPI program! You see how fast and easy it is? Very fast!! I know you like that! Now, let's set up our MongoDB Atlas to store our laundry service data.

  • Signup for a free MongoDB cloud storage here
  • 가입 후 프로젝트를 만들고 이름을 'laundrystore'로 지정합니다.


  • 클러스터 구축을 클릭하여 Atlas:무료 아틀라스를 생성하십시오!
    새 클러스터를 프로비저닝하는 데 1~3분이 소요됩니다.
  • 클러스터가 생성된 후 클라우드 저장소를 앱에 연결하는 방법에 대한 자세한 내용을 보려면 '연결'을 클릭하십시오!
  • 어디서나 연결할 수 있도록 클라우드 저장소 액세스 권한을 설정하십시오!
  • 데이터베이스 사용자 이름과 암호를 설정하고 연결 방법을 선택하십시오!


  • 이 API의 경우 "애플리케이션 연결"을 선택하고 Python을 드라이버로 선택한 후 제공되는 연결 문자열을 복사하여 사용하십시오!

  • 연결 문자열을 유지하면 API 개발에 사용할 것입니다! 데이터베이스 사용자 이름과 암호를 잊지 마십시오.
    MongoDB Atlas를 성공적으로 만들고 설정했습니다! 이제 Laundry API용 클라우드 스토리지가 있습니다.

    각 API 끝점 구축

    Let's work on the endpoints highlighted for this part one article:
    starting with the signup endpoint!

    In this article, we will be using schematics to organize and validate our data model types and structures.

    Install schematics:
    pip install schematics

    create a settings.py file and type the following code:

    # MongoDB attributes
    mongodb_uri = 'mongodb+srv://kenny:[email protected]/<usersdata>?retryWrites=true&w=majority'
    port = 8000
    

    Note that I replaced some strings in the connection string we copied from MongoDB with the database username and password we created

    create a connection.py file and type the following code:

    from pymongo import MongoClient
    import settings
    
    client = MongoClient(settings.mongodb_uri, settings.port)
    db = client['usersdata']
    

    This is basically a connection file that creates a connection with MongoClient! Also, a database called 'usersdata'

    Now, update your main.py file with the following code:

    from typing import Optional
    
    from fastapi import FastAPI
    import connection
    from bson import ObjectId
    from schematics.models import Model
    from schematics.types import StringType, EmailType
    
    
    class User(Model):
        user_id = ObjectId()
        email = EmailType(required=True)
        name = StringType(required=True)
        password = StringType(required=True)
    
    # An instance of class User
    newuser = User()
    
    # funtion to create and assign values to the instanse of class User created
    def create_user(email, username, password):
        newuser.user_id = ObjectId()
        newuser.email = email
        newuser.name = username
        newuser.password = password
        return dict(newuser)
    
    app = FastAPI()
    
    
    # Our root endpoint
    @app.get("/")
    def index():
        return {"message": "Hello World"}
    
    # Signup endpoint with the POST method
    @app.post("/signup/{email}/{username}/{password}")
    def signup(email, username: str, password: str):
        user_exists = False
        data = create_user(email, username, password)
    
        # Covert data to dict so it can be easily inserted to MongoDB
        dict(data)
    
        # Checks if an email exists from the collection of users
        if connection.db.users.find(
            {'email': data['email']}
            ).count() > 0:
            user_exists = True
            print("USer Exists")
            return {"message":"User Exists"}
        # If the email doesn't exist, create the user
        elif user_exists == False:
            connection.db.users.insert_one(data)
            return {"message":"User Created","email": data['email'], "name": data['name'], "pass": data['password']}
    

    -I will explain what we did there, but that is simply an implementation of the signup endpoint without hashing our password values!
    -We will also learn how to hash our passwords before storing them into the cloud!
    -The Signup endpoint simply creates a new user into the MongoDB storage and returns information about the user-created or either returns a piece of information that the user exists!

    Type uvicorn main:app --reload to run the code!

    Now visit http://127.0.0.1:8000/docs 브라우저에서 FastAPI swagger UI를 사용하여 API를 테스트합니다.

    이 파트 1 기사는 기본적으로 CRUD 작업과 그것이 구현되는 방법에 대해 배우기 위한 것입니다! 다음 기사에서는 코드와 폴더를 전문적으로 구성하는 방법을 배웁니다! 코드를 전문적으로 구조화한다는 것은 단순히 코드를 재사용하는 방법을 의미합니다! 좋은 프로그램의 품질은 코드, 클래스, 함수 등을 재사용하는 능력입니다.

    로그인 끝점 구현: Python 초보자를 위해 로그인 및 가입에 패키지를 사용하지 않습니다!
    main.py 파일을 다음 코드로 업데이트합니다(로그인 엔드포인트로 업데이트됨).

    from typing import Optional
    
    from fastapi import FastAPI
    import connection
    from bson import ObjectId
    from json import dumps
    from schematics.models import Model
    from schematics.types import StringType, EmailType
    
    
    class User(Model):
        user_id = ObjectId()
        email = EmailType(required=True)
        name = StringType(required=True)
        password = StringType(required=True)
    
    # An instance of class User
    newuser = User()
    
    # funtion to create and assign values to the instanse of class User created
    def create_user(email, username, password):
        newuser.user_id = ObjectId()
        newuser.email = email
        newuser.name = username
        newuser.password = password
        return dict(newuser)
    
    # A method to check if the email parameter exists from the users database before validation of details
    def email_exists(email):
        user_exist = True
    
        # counts the number of times the email exists, if it equals 0 it means the email doesn't exist in the database
        if connection.db.users.find(
            {'email': email}
        ).count() == 0:
            user_exist = False
            return user_exist
    
    # Reads user details from database and ready for validation
    def check_login_creds(email, password):
        if not email_exists(email):
            activeuser = connection.db.users.find(
                {'email': email}
            )
            for actuser in activeuser:
                actuser = dict(actuser)
                # Converted the user ObjectId to str! so this can be stored into a session(how login works)
                actuser['_id'] = str(actuser['_id'])    
                return actuser
    
    
    app = FastAPI()
    
    
    # Our root endpoint
    @app.get("/")
    def index():
        return {"message": "Hello World"}
    
    
    # Signup endpoint with the POST method
    @app.post("/signup/{email}/{username}/{password}")
    def signup(email, username: str, password: str):
        user_exists = False
        data = create_user(email, username, password)
    
        # Covert data to dict so it can be easily inserted to MongoDB
        dict(data)
    
        # Checks if an email exists from the collection of users
        if connection.db.users.find(
            {'email': data['email']}
            ).count() > 0:
            user_exists = True
            print("USer Exists")
            return {"message":"User Exists"}
        # If the email doesn't exist, create the user
        elif user_exists == False:
            connection.db.users.insert_one(data)
            return {"message":"User Created","email": data['email'], "name": data['name'], "pass": data['password']}
    
    # Login endpoint
    @app.get("/login/{email}/{password}")
    def login(email, password):
        def log_user_in(creds):
            if creds['email'] == email and creds['password'] == password:
                return {"message": creds['name'] + ' successfully logged in'}
            else:
                return {"message":"Invalid credentials!!"}
        # Read email from database to validate if user exists and checks if password matches
        logger = check_login_creds(email, password)
        if bool(logger) != True:
            if logger == None:
                logger = "Invalid Email"
                return {"message":logger}
        else:
            status = log_user_in(logger)
            return {"Info":status}
    


    -이 코드는 주석으로 충분히 지시하고 있습니다!
    -로그인 끝점은 check_login_creds(), email_exists(), log_user_in() 방법을 사용하여 사용자가 존재하는지 확인한 다음 사용자 세부 정보를 확인하고 값이 일치하면 사용자를 로그인합니다.



    위 이미지는 로그인 자격 증명이 올바르지 않을 때 API에서 반환된 결과를 보여줍니다!
    다음 기사에서는 API가 중단되지 않도록 오류를 처리하는 방법도 알아봅니다! 예를 들어 MongoDB에 대한 연결 시간이 초과되면 API는 500 응답 코드(응용 프로그램 오류)를 반환합니다! 응용 프로그램이 중단되지 않도록 코드에서 오류 처리를 사용하는 것이 더 전문적이고 권장됩니다!

    요약



    이 기사에서는 모든 개인이 이해할 수 있도록 최대한 단순화하려고 노력했습니다!
    API 구축에 인증, 세션 또는 복잡한 방법이 없습니다!
    코드here를 얻을 수 있습니다.

    저장소에 별표를 표시하고 저를 따라오세요!

    즐거운 배움 🎉🎉🎉

    좋은 웹페이지 즐겨찾기