Skip to content

Commit

Permalink
Merge pull request #5 from SVTeamJ/chore/#4
Browse files Browse the repository at this point in the history
[Chore/#4] 백엔드 초기환경 세팅 및 api 예시 구현
  • Loading branch information
ppinkypeach authored Jan 10, 2023
2 parents f6a247c + 21de7e7 commit c3a2c96
Show file tree
Hide file tree
Showing 16 changed files with 281 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .env.templete
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
MYSQL_USER=
MYSQL_PASSWORD=
MYSQL_DATABASE=
MYSQL_ROOT_PASSWORD=
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
./.env
*__pycache__*
.DS_Store
.env
35 changes: 35 additions & 0 deletions Docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,38 @@ services:
ports:
- "3000:3000"
tty: true

mysql:
container_name: taegong_mysql
image: mysql:8.0-oracle
volumes:
- mysql_data_dev:/mysql
env_file:
- ./.env
networks:
- mynet
ports:
- 3306:3306

backend:
container_name: taegong_backend
build: ./backend
environment:
MYSQL_HOST: "1234"
entrypoint: /bin/bash
command: -c "sleep 10 && uvicorn main:app --host 0.0.0.0 --reload"
ports:
- 8000:8000
networks:
- mynet
# 작업이 끝나도 종료되지 않게 하는 명령
tty: true
depends_on:
- mysql

volumes:
mysql_data_dev: null

networks:
mynet:
driver: bridge
18 changes: 18 additions & 0 deletions backend/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
FROM python:3.10-slim

ENV PYTHONUNBUFFERED 1
ENV PYTHONDONTWRITEBYTECODE 1

WORKDIR /taegong
COPY requirements.txt /taegong
RUN apt-get update \
# dependencies for building Python packages
&& apt-get install -y build-essential \
# psycopg2 dependencies
&& apt-get install -y libpq-dev
RUN pip install --upgrade pip
RUN pip install cryptography
RUN pip install -r requirements.txt

COPY . /taegong/
EXPOSE 8000
Empty file added backend/api/__init__.py
Empty file.
5 changes: 5 additions & 0 deletions backend/api/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from fastapi import APIRouter
from api.endpoints import users

api_router = APIRouter()
api_router.include_router(users.router, prefix="/users", tags=["users"])
9 changes: 9 additions & 0 deletions backend/api/dep.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from database import SessionLocal

# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
31 changes: 31 additions & 0 deletions backend/api/endpoints/users.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session

from starlette.status import HTTP_201_CREATED, HTTP_204_NO_CONTENT
from crud import user_crud
from schemas import user_schema
from api.dep import get_db

router = APIRouter()


# TODO: 에러 처리

# 유저 생성
@router.post("", status_code=HTTP_201_CREATED, response_model=user_schema.User)
def create_user_info(user: user_schema.UserCreate, db: Session = Depends(get_db)):
user_ = user_crud.create_user(db, user=user)
return user_


# 유저 상세 조회
@router.get("/{token}")
def get_user_by_id(token: str, db: Session = Depends(get_db)):
users = user_crud.get_user_by_token(db, token=token)
return users


# 유저 삭제
@router.delete("/{user_id}", status_code=HTTP_204_NO_CONTENT)
def delete_user_by_id(user_id: int, db: Session = Depends(get_db)):
user_crud.delete_user_by_id(db, user_id=user_id)
Empty file added backend/crud/__init__.py
Empty file.
56 changes: 56 additions & 0 deletions backend/crud/user_crud.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
from models import User
from schemas import user_schema
from fastapi import Response, HTTPException
from sqlalchemy.orm import Session
from starlette.responses import Response
from starlette.status import HTTP_204_NO_CONTENT, HTTP_404_NOT_FOUND


# user
# id로 user 검색
def get_user_by_token(db: Session, token: str):
user = (
db.query(User)
.filter(User.is_active == True)
.filter(User.token == token)
.first()
)
if not user:
return Response(status_code=HTTP_404_NOT_FOUND)
return user


# user 생성
def create_user(db: Session, user: user_schema.UserCreate):
existing_user = (
db.query(User)
.filter(User.phone_num == user.phone_num)
.filter(User.user_type == user.user_type)
.first()
)
if existing_user:
db_user = (
db.query(User)
.filter(User.id == existing_user.id)
.update({"token": user.token})
)
db.commit()
return db.query(User).filter(User.id == existing_user.id).first()
db_user = User(
name=user.name,
user_type=user.user_type,
gender=user.gender,
age_range=user.age_range,
phone_num=user.phone_num,
token=user.token,
)
db.add(db_user)
db.commit()
return db_user


# user 삭제
def delete_user_by_id(db: Session, user_id: int):
user = db.query(User).filter(User.id == user_id).update({"is_active": False})
db.commit()
return Response(status_code=HTTP_204_NO_CONTENT)
21 changes: 21 additions & 0 deletions backend/database.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

import os
# SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db" #host.doc
#
# ker.internal 외부에서 도커에 접속하기 위한 주소
if os.getenv('MYSQL_HOST'):
SQLALCHEMY_DATABASE_URL = "mysql+pymysql://taegong:[email protected]:3306/taegong"
else:
SQLALCHEMY_DATABASE_URL = "mysql+pymysql://taegong:taegong@localhost:3306/taegong"

engine = create_engine(
SQLALCHEMY_DATABASE_URL,
# connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)


Base = declarative_base()
27 changes: 27 additions & 0 deletions backend/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import uuid
from fastapi import FastAPI
from fastapi import UploadFile, File
from fastapi.middleware.cors import CORSMiddleware

from database import Base
from database import engine

from api.api import api_router

Base.metadata.create_all(bind=engine)

# cors
origins = [
"http://localhost",
"http://localhost:3000",
"http://localhost:8080",
]
app = FastAPI(title="TaeGong’s life",docs_url="/swagger")
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(api_router, prefix="/api")
1 change: 1 addition & 0 deletions backend/models/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .user import User
23 changes: 23 additions & 0 deletions backend/models/user.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from sqlalchemy import Boolean, Column, Integer, String
from sqlalchemy.types import TIMESTAMP
from sqlalchemy.sql import text, func

from database import Base
from sqlalchemy import func


class User(Base):
__tablename__ = "users"

id = Column(Integer, primary_key=True, index=True)
user_type = Column(Boolean, nullable=False, default=True)
name = Column(String(100), index=True)
gender = Column(String(6), index=True)
age_range = Column(String(20), index=True)
phone_num = Column(String(16), index=True)
token = Column(String(255), nullable=False, index=True)
is_active = Column(Boolean, nullable=False, default=True)
created_at = Column(TIMESTAMP, server_default=func.now())
updated_at = Column(
TIMESTAMP, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
)
12 changes: 12 additions & 0 deletions backend/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
anyio==3.6.2
click==8.1.3
fastapi==0.88.0
h11==0.14.0
idna==3.4
pydantic==1.10.4
PyMySQL==1.0.2
sniffio==1.3.0
SQLAlchemy==1.4.46
starlette==0.22.0
typing_extensions==4.4.0
uvicorn==0.20.0
35 changes: 35 additions & 0 deletions backend/schemas/user_schema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from pydantic import BaseModel


class UserBase(BaseModel):
class Config:
orm_mode = True


class User(UserBase):
id: int
user_type: int
name: str
gender: str
age_range: str
phone_num: str
token: str
is_active: bool



class UserCreate(UserBase):
name: str
gender: str
age_range: str
phone_num: str
user_type: bool
token: str


class UserRead(UserCreate):
id: int


class UserDelete(UserBase):
is_active: bool

0 comments on commit c3a2c96

Please sign in to comment.