をビルドして洗濯物APIをFastAPIを使用してmongodb - 1


データベース技術としてMongoDBのサポートとFastAPIを使用してランドリーCRUD APIを構築!私は多くの場合、保護、最も信頼性の高いバックアップシステム、どこからでもデータに簡単にアクセスを提供するために私のプロジェクトでMongoDBのようなクラウドストレージを使用し、最も重要なのは、アクセスの低コストです.

目次

  • Basic CRUD in a Laundry API
  • Installing FastAPI
  • Setting up MongoDB Atlas
  • Building each API Endpoints
  • グラブあなたのポップコーンは、快適に座ってみましょう🚀
    でも待ちます.MongoDBを使用して基本的な知識がありますか?Pythonでプログラムを書きましたか.はい!それから、あなたはここで続く良い合うものです.なんとも言えないパニックにならないでください、私はあなたにこの記事のあらゆる一回のステップを単純化することによってカバーしました.

    MongoDB ?


    MongoDBは何ですか?またはどのように使用されている?
    MongoDBはSQLを必要としないドキュメント指向のデータベースプログラムであり、JSON形式のデータを格納する.

    FastAPI ?


    FastAPIは、PythonとのAPIを構築するための近代的な、高速なフレームワークです.私は速く単語を大胆にしなければならないことに注意してください!名前は“fastapi”を意味するように、それは非常に高速かつ簡単にコードを作成し、自動的にあなたのAPIのswaggerドキュメントを生成します.それは甘い権利だ!閉じるこの動画はお気に入りから削除されています.
    飲み物を手に入れて、動きましょう🚀

    ランドリーAPIで

    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アトラスの設定

    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
  • サインアップの後、プロジェクトを作成します
  • アトラスを作成するクラスタをクリックします.
    新しいクラスタは、供給に1 - 3分かかる
  • クラスタが作成された後、あなたのアプリケーションにクラウドストレージを接続する方法の詳細については';接続';をクリックしてください!
  • どこからでも接続できるようにクラウドストレージアクセス許可を設定!
  • データベースのユーザー名とパスワードを設定し、接続メソッドを選択します.
  • このAPIについては、“アプリケーションを接続”を選択し、それを使用するドライバとしてPythonを選択した後に接続文字列をコピーしてください!
  • あなたの接続文字列を維持し、我々のAPI開発でそれを使用します!データベースのユーザ名とパスワードを忘れないでください
    我々は正常に作成し、設定MongoDBアトラス!我々は今ランドリー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つの記事は基本的に私たちはクルージング作品を学ぶために、どのように実装されている!次の記事では、専門的に我々のコードとフォルダを構成する方法を学びます!プロのコードを構成するだけでどのようにコードを再利用することを意味!良いプログラムの品質は、コード、クラス、関数などを再利用する能力です.
    ログインエンドポイントを実装する:Python初心者のために、我々はログインとサインアップのためのパッケージを使用していません!
    アップデートmain.py 以下のコードを持つファイル( login endpointで更新)
    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
    星レポと私に従ってください!
    ハッピーラーニング🎉🎉🎉