Compare commits

..
10 Commits
16 changed files with 557 additions and 0 deletions

No files matched your search

+1
View File
@@ -123,6 +123,7 @@ celerybeat.pid
# Environments
.env
.venv
.venv/
env/
venv/
ENV/
+25
View File
@@ -1,2 +1,27 @@
# aio2o-fastapi-sample
# Requirement
Docker, Docker-compose
## install
### Percona 설치
./percona-server
.env.original 파일 보고 변수 원하는대로 바꿔 .env로 저장
```
docker compose -f docker-compose.percona.yml up -d
```
### API Server 켜기
./api-server
해당 폴더에도 따로 .env.original이 있으니 percona와 동일하게 변경하고 .env로 저장
Percona 서버를 사용하지 않을 시 해당하는 서버에 맞게 저장
```
docker compose -f docker-compose.yml build
docker compose -f docker-compose.yml up -d
```
+10
View File
@@ -0,0 +1,10 @@
FROM python:3.12
RUN apt-get update && apt-get install -y locales
RUN locale-gen ko_KR.UTF-8
RUN apt-get update && apt-get install git -y
WORKDIR /app
COPY ./requirements.txt /requirements.txt
RUN pip install --no-cache-dir --upgrade -r /requirements.txt
+5
View File
@@ -0,0 +1,5 @@
MYSQL_HOST="percona-server"
MYSQL_USER="aio2o"
MYSQL_PASSWORD="yourpasswordhere"
MYSQL_ROOT_PASSWORD="yourrootpasswordhere"
MYSQL_DATABASE="yourdbnamehere"
+32
View File
@@ -0,0 +1,32 @@
import asyncio
from faker import Faker
import module.mysql_utils as sql
from module.pydantic_models import *
fake = Faker('ko_KR')
unique_num = 1
INSERT_NUM = 1000
class UserFactory:
unique_num = 0
@classmethod
def generate_user_name(cls):
cls.unique_num += 1
return f"{fake.name()}{cls.unique_num:04d}"
@classmethod
def generate_phone_number(cls):
return fake.phone_number()
@classmethod
def create(cls):
return (cls.generate_user_name(), cls.generate_phone_number())
async def main():
await sql.truncate_user_table() # clear user table
for i in range(INSERT_NUM):
await sql.create_user(*UserFactory.create())
# await asyncio.gather(*[sql.create_user(*UserFactory.create()) for i in range(INSERT_NUM)]) # 커넥션 INSERT NUM개수만큼 생기는 문제 Semaphore 등으로 해결해야 쓸수있음
return
if __name__ == "__main__":
asyncio.run(main())
+69
View File
@@ -0,0 +1,69 @@
from contextlib import asynccontextmanager
from fastapi import FastAPI, status, Depends
from fastapi.responses import JSONResponse
from module.pydantic_models import *
import module.mysql_utils as sql
app = FastAPI()
async def startup():
table_list = await sql.get_table_list()
print(table_list)
if 'user_table' not in table_list:
await sql.create_user_table()
print("user_table created")
else:
print("user_table already exist")
if 'blog_table'not in table_list:
await sql.create_blog_table()
print("blog_table created")
else:
print("blog_table already exist")
@asynccontextmanager
async def lifespan(app : FastAPI):
await startup()
yield
app = FastAPI(lifespan=lifespan)
@app.post("/user/create", status_code=status.HTTP_201_CREATED)
async def create_user(params: UserCreateForm):
user_id = await sql.create_user(params.user_name, params.phone_number)
return JSONResponse(content={'user_id' : user_id}, status_code=status.HTTP_201_CREATED)
@app.post("/user/read", status_code=status.HTTP_200_OK)
async def read_user(params: UserReadFromIdForm):
user_info = await sql.get_user_info_from_id(params.user_id)
return JSONResponse(content=user_info)
@app.patch("/user/update", status_code=status.HTTP_200_OK)
async def update_user(params: UserUpdatePhoneNumberFromIdForm):
updated_data = await sql.update_user_phone_from_id(params.user_id, params.phone_number)
return updated_data
@app.delete("/user/delete", status_code=status.HTTP_204_NO_CONTENT)
async def delete_user(params: UserDeleteForm):
await sql.delete_user_from_id(params.user_id)
return
@app.post("/blog/create", status_code=status.HTTP_201_CREATED)
async def create_blog(params: BlogCreateForm):
blog_id = await sql.create_blog(params.blog_owner, params.blog_title, params.blog_content)
return JSONResponse(content={'blog_id' : blog_id}, status_code=status.HTTP_201_CREATED)
@app.post("/blog/read", status_code=status.HTTP_200_OK)
async def read_blog(params: BlogReadFromIdForm):
blog_info = await sql.get_blog_info_from_id(params.blog_id)
return JSONResponse(content=blog_info)
@app.patch("/blog/update", status_code=status.HTTP_200_OK)
async def update_blog(params: BlogUpdateContentFromIdForm):
updated_data = await sql.update_blog_content_from_id(params.blog_id, params.blog_content)
return updated_data
@app.delete("/blog/delete", status_code=status.HTTP_204_NO_CONTENT)
async def delete_blog(params: BlogDeleteForm):
await sql.delete_blog_from_id(params.blog_id)
return
+297
View File
@@ -0,0 +1,297 @@
import asyncio
import os
import pydantic
from dotenv import load_dotenv
from mysql.connector.aio import connect
from mysql.connector.errors import IntegrityError
from fastapi import HTTPException, status
load_dotenv(verbose=True)
async def get_cnx():
cnx = await connect(
host = os.getenv("MYSQL_HOST"),
user = os.getenv("MYSQL_USER"),
password = os.getenv("MYSQL_PASSWORD"),
database = os.getenv("MYSQL_DATABASE"),
)
return cnx
async def create_user(user_name:str, phone_number:str=None):
async with await get_cnx() as cnx:
async with await cnx.cursor() as cur:
query = '''
INSERT INTO user_table (user_name, phone_number)
VALUES (%(user_name)s, %(phone_number)s)
'''
data = {
"user_name" : user_name,
"phone_number" : phone_number
}
try:
await cur.execute(query, data)
except IntegrityError as e:
await cnx.rollback()
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="user already exist")
user_id = cur.lastrowid
await cnx.commit()
return user_id
async def get_user_info_from_id(user_id:int):
async with await get_cnx() as cnx:
async with await cnx.cursor() as cur:
query = '''
SELECT user_name, phone_number FROM user_table
WHERE user_id=%(user_id)s
'''
data = {"user_id" : user_id}
await cur.execute(query, data)
user_info = await cur.fetchone()
await cnx.commit()
if not user_info:
raise HTTPException(status.HTTP_404_NOT_FOUND)
return user_info
async def get_user_id_from_name(user_name:str):
async with await get_cnx() as cnx:
async with await cnx.cursor() as cur:
query = '''
SELECT user_id FROM user_table
WHERE user_name=%(user_name)s
'''
data = {"user_name" : user_name}
await cur.execute(query, data)
user_info = await cur.fetchone()
await cnx.commit()
if not user_info:
raise HTTPException(status.HTTP_404_NOT_FOUND)
return user_info["user_id"]
async def update_user_phone_from_id(user_id:int, phone_number:str=None):
async with await get_cnx() as cnx:
async with await cnx.cursor() as cur:
count_query = '''
SELECT count(*)
FROM user_table
WHERE user_id = %(user_id)s
'''
await cur.execute(count_query, {'user_id' : user_id})
found_rows = await cur.fetchone()
if found_rows[0] == 0:
await cnx.rollback()
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
query = '''
UPDATE user_table
SET phone_number = %(phone_number)s
WHERE user_id = %(user_id)s
'''
data = {
"user_id" : user_id,
"phone_number" : phone_number
}
await cur.execute(query, data)
if cur.rowcount == 0:
await cnx.rollback()
raise HTTPException(status_code=status.HTTP_204_NO_CONTENT)
await cnx.commit()
return data
async def delete_user_from_id(user_id:int):
async with await get_cnx() as cnx:
async with await cnx.cursor() as cur:
count_query = '''
SELECT count(*)
FROM user_table
WHERE user_id = %(user_id)s
'''
await cur.execute(count_query, {'user_id' : user_id})
found_rows = await cur.fetchone()
if found_rows[0] == 0:
await cnx.rollback()
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
query = '''
DELETE
FROM user_table
WHERE user_id = %(user_id)s
'''
data = {
"user_id" : user_id
}
await cur.execute(query, data)
await cnx.commit()
return
async def create_blog(blog_owner:int, blog_title:str, blog_content:str = None):
async with await get_cnx() as cnx:
async with await cnx.cursor() as cur:
query = '''
INSERT INTO blog_table (blog_title, blog_content, blog_owner)
VALUES (%(blog_title)s, %(blog_content)s, %(blog_owner)s)
'''
data = {
"blog_owner" : blog_owner,
"blog_title" : blog_title,
"blog_content" : blog_content
}
try:
await cur.execute(query, data)
except IntegrityError as e:
await cnx.rollback()
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="blog already exist")
blog_id = cur.lastrowid
await cnx.commit()
return blog_id
async def get_blog_info_from_id(blog_id:int):
async with await get_cnx() as cnx:
async with await cnx.cursor() as cur:
query = '''
SELECT blog_owner, blog_title, blog_content FROM blog_table
WHERE blog_id=%(blog_id)s
'''
data = {"blog_id" : blog_id}
await cur.execute(query, data)
user_info = await cur.fetchone()
await cnx.commit()
if not user_info:
raise HTTPException(status.HTTP_404_NOT_FOUND)
return user_info
async def update_blog_content_from_id(blog_id:int, blog_content:str=None):
async with await get_cnx() as cnx:
async with await cnx.cursor() as cur:
count_query = '''
SELECT count(*)
FROM blog_table
WHERE blog_id = %(blog_id)s
'''
await cur.execute(count_query, {'blog_id' : blog_id})
found_rows = await cur.fetchone()
if found_rows[0] == 0:
await cnx.rollback()
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
query = '''
UPDATE blog_table
SET blog_content = %(blog_content)s
WHERE blog_id = %(blog_id)s
'''
data = {
"blog_id" : blog_id,
"blog_content" : blog_content
}
await cur.execute(query, data)
if cur.rowcount == 0:
await cnx.rollback()
raise HTTPException(status_code=status.HTTP_204_NO_CONTENT)
await cnx.commit()
return data
async def delete_blog_from_id(blog_id:int):
async with await get_cnx() as cnx:
async with await cnx.cursor() as cur:
count_query = '''
SELECT count(*)
FROM blog_table
WHERE blog_id = %(blog_id)s
'''
await cur.execute(count_query, {'blog_id' : blog_id})
found_rows = await cur.fetchone()
if found_rows[0] == 0:
await cnx.rollback()
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
query = '''
DELETE
FROM blog_table
WHERE blog_id = %(blog_id)s
'''
data = {
"blog_id" : blog_id
}
await cur.execute(query, data)
await cnx.commit()
return
async def truncate_user_table():
async with await get_cnx() as cnx:
async with await cnx.cursor() as cur:
query = '''
TRUNCATE TABLE user_table
'''
await cur.execute(query)
await cnx.commit()
return
async def get_table_list():
async with await get_cnx() as cnx:
async with await cnx.cursor() as cur:
query = '''
SHOW TABLES
'''
await cur.execute(query)
table_list = [result[0] for result in await cur.fetchall()]
await cnx.commit()
return table_list
async def create_user_table():
async with await get_cnx() as cnx:
async with await cnx.cursor() as cur:
query = '''
-- 테이블 생성 SQL - user_table
CREATE TABLE user_table
(
`user_id` INT NOT NULL AUTO_INCREMENT,
`user_name` VARCHAR(20) NOT NULL,
`phone_number` VARCHAR(20) NULL,
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (user_id)
);
-- Unique Index 설정 SQL - user_table(user_name)
CREATE UNIQUE INDEX UQ_user_table_1
ON user_table(user_name);
'''
await cur.execute(query)
await cnx.commit()
return
async def create_blog_table():
async with await get_cnx() as cnx:
async with await cnx.cursor() as cur:
query = '''
-- 테이블 생성 SQL - blog_table
CREATE TABLE blog_table
(
`blog_id` INT NOT NULL AUTO_INCREMENT,
`blog_title` VARCHAR(50) NOT NULL,
`blog_content` TEXT NULL,
`blog_owner` INT NOT NULL,
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (blog_id)
);
'''
await cur.execute(query)
await cnx.commit()
return
+31
View File
@@ -0,0 +1,31 @@
from pydantic import BaseModel
class UserCreateForm(BaseModel):
user_name:str
phone_number:str
class UserReadFromIdForm(BaseModel):
user_id:int
class UserUpdatePhoneNumberFromIdForm(BaseModel):
user_id:int
phone_number:str
class UserDeleteForm(BaseModel):
user_id:int
class BlogCreateForm(BaseModel):
blog_owner:int
blog_title:str
blog_content:str
class BlogReadFromIdForm(BaseModel):
blog_id:int
class BlogUpdateContentFromIdForm(BaseModel):
blog_id:int
blog_content:str
class BlogDeleteForm(BaseModel):
blog_id:int
+18
View File
@@ -0,0 +1,18 @@
services:
fastapi:
build: .
container_name: fastapi-server
command: uvicorn main:app --host 0.0.0.0 --port 8080 --reload
ports:
- 8080:8080
networks:
- test_app_network
volumes:
- ./app:/app
networks:
test_app_network:
name: test_app_network
driver: bridge
external: true
+3
View File
@@ -0,0 +1,3 @@
#!/bin/bash
docker exec -it fastapi-server /bin/bash
+5
View File
@@ -0,0 +1,5 @@
dotenv
fastapi
uvicorn[standard]
mysql-connector-python
faker
+4
View File
@@ -0,0 +1,4 @@
MYSQL_USER="aio2o"
MYSQL_PASSWORD="yourpasswordhere"
MYSQL_ROOT_PASSWORD="yourrootpasswordhere"
MYSQL_DATABASE="yourdbnamehere"
+29
View File
@@ -0,0 +1,29 @@
services:
mysql:
image: percona/percona-server:8.0
container_name: percona-server
ports:
- "3306:3306"
environment:
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
MYSQL_DATABASE: ${MYSQL_DATABASE}
MYSQL_USER: ${MYSQL_USER}
MYSQL_PASSWORD: ${MYSQL_PASSWORD}
volumes:
- percona-data:/var/lib/mysql # Database data
- percona-logs:/var/log/mysql # MySQL logs
- percona-backups:/backups # XtraBackup output (optional, for future use)
restart: unless-stopped
networks:
- test_app_network
volumes:
percona-data:
percona-logs:
percona-backups:
networks:
test_app_network:
name: test_app_network
driver: bridge
+3
View File
@@ -0,0 +1,3 @@
#!/bin/bash
docker exec -it percona-server mysql -u aio2o -p
+11
View File
@@ -0,0 +1,11 @@
-- 테이블 생성 SQL - blog_table
CREATE TABLE blog_table
(
`blog_id` INT NOT NULL AUTO_INCREMENT,
`blog_title` VARCHAR(50) NOT NULL,
`blog_content` TEXT NULL,
`blog_owner` INT NOT NULL,
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (blog_id)
);
+14
View File
@@ -0,0 +1,14 @@
-- 테이블 생성 SQL - user_table
CREATE TABLE user_table
(
`user_id` INT NOT NULL AUTO_INCREMENT,
`user_name` VARCHAR(20) NOT NULL,
`phone_number` VARCHAR(20) NULL,
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (user_id)
);
-- Unique Index 설정 SQL - user_table(user_name)
CREATE UNIQUE INDEX UQ_user_table_1
ON user_table(user_name);