FastAPI에 모델 (Model) 적용
2023. 3. 29. 00:13ㆍ코딩/잡 공부
FastAPI에 모델 (Model) 적용
sqlacodegen을 이용하면 모델 생성 알아서 해줌
pip install sqlacodegen
sqlacodegen mysql+pymysql://<user>:<password>@<host>:<port>/<db> > "./models.py"
결과
# coding: utf-8
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = Base.metadata
class User(Base):
__tablename__ = 'user'
UID = Column(Integer, primary_key=True)
loginID = Column(String(45), nullable=False)
loginPW = Column(String(45), nullable=False)
class Character(Base):
__tablename__ = 'character'
CID = Column(Integer, primary_key=True)
User_UID = Column(ForeignKey('user.UID'), nullable=False, index=True)
Level = Column(Integer, nullable=False)
Exp = Column(Integer, nullable=False)
Max_HP = Column(Integer, nullable=False)
HP = Column(Integer)
STR = Column(Integer)
Location = Column(String(100))
user = relationship('User')
class Item(Base):
__tablename__ = 'item'
Item_ID = Column(Integer, primary_key=True, nullable=False)
Item_Name = Column(String(45))
Character_CID = Column(ForeignKey('character.CID'), primary_key=True, nullable=False, index=True)
character = relationship('Character')
class Skill(Base):
__tablename__ = 'skill'
SID = Column(Integer, primary_key=True, nullable=False)
Character_CID = Column(ForeignKey('character.CID'), primary_key=True, nullable=False, index=True)
Someting = Column(String(45))
character = relationship('Character')
ORM이용하여 해당 모델에서 Transaction을 적용 시켜 보자
예시)
아이디: kikirubbingbbb 비번: kyoukyou 로 회원 가입 → Post
아이디: kikirubbingbbb 비번: kyoukyou 로 로그인 → Get
uid 1이 캐릭터 생성
uid 1이 cid 1으로 접속
캐릭터 cid1이 한대 맞아서 Hp가 3이 깎임
//캐릭터 cid1이 몬스터를 잡고 Exp 10 획득 - 생략(캐시 때 설명)
//캐릭터 cid1이 몬스터를 잡고 아이템 1, sword@획득 - 생략
//캐릭터 cid1이 맵 그리스 아테네 (3.1.34) 로 이동 - 생략
캐릭터 cid1 삭제
from fastapi import FastAPI
from fastapi_sqlalchemy import DBSessionMiddleware
from fastapi_sqlalchemy import db
from models import User, Character
#import redis
#import json
HOSTNAME = 'localhost'
PORT = 3306
USERNAME = 'root'
PASSWORD = ''
DBNAME = 'mydb3'
MYSQL_URL = f'mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DBNAME}'
app = FastAPI()
app.add_middleware(DBSessionMiddleware, db_url=MYSQL_URL)
#cache = redis.Redis(host='localhost', port=6379, db=0)
@app.get("/")
def root():
return {"hello this is World Time CRUD API!!"}
@app.get("/user")
def get_loginToken(user_id, user_password):
query = db.session.query(User).filter(User.loginID == user_id, User.loginPW == user_password)
return query.first()
@app.post("/user")
def set_loginToken(user_id, user_password):
user_uid = db.session.query(User).count() + 1
user = User(UID = user_uid, loginID = str(user_id), loginPW = str(user_password))
db.session.add(user)
db.session.commit()
return
@app.post("/user/{user_uid}/Character")
def make_new_Character(user_uid):
cid = db.session.query(Character).count() + 1
db.session.add(Character(CID = cid,User_UID = user_uid, Level = 1, Exp = 0,Max_HP = 10,HP = 10,STR = 5,Location = "Korea/Seoul/(0.0.0)"))
db.session.commit()
return cid
@app.get("/user/{user_uid}/Character")
def get_Character(user_uid,c_id):
query = db.session.query(Character).filter(Character.CID == c_id, Character.User_UID == user_uid)
return query.all()
@app.put("/user/{user_uid}/Character")
def Descrease_hp(user_uid, c_id, hp):
curret_hp = db.session.query(Character).filter(Character.CID == c_id, Character.User_UID == user_uid).first().HP
query = db.session.query(Character).filter(Character.CID == c_id, Character.User_UID == user_uid).update({'HP':curret_hp - int(hp)})
db.session.commit()
return query
@app.delete("/user/{user_uid}/Character")
def delete_c(user_uid,c_id):
db.session.query(Character).filter(Character.CID == c_id, Character.User_UID == user_uid).delete()
db.session.commit()
return
결과
해당 cid를 넣어주면
hp를 깎자
캐릭터를 지우자
'코딩 > 잡 공부' 카테고리의 다른 글
구글 플레이 Developer API로 apk / aab 업로드 (0) | 2023.03.29 |
---|---|
윈도우 디팬던시 트러블 슈팅 해결 툴 (Window dependency tool) (0) | 2023.03.29 |
게임과 웹의 캐시 패턴 차이점 (0) | 2023.03.29 |
FastAPI로 CRUD, ORM sqlalchemy 사용, 캐쉬 예시 예제 (0) | 2023.03.28 |
ORM 뜻, 설명, 장단점 (0) | 2023.03.28 |