Compare commits

...
8 Commits
8 changed files with 284 additions and 25 deletions

No files matched your search

+4
View File
@@ -7,13 +7,17 @@ Docker, Docker-compose
### Percona 설치
./percona-server
.env.original 파일 보고 변수 원하는대로 바꿔 .env로 저장
```
docker compose -f docker-compose.percona.yml up -d
```
### API Server 켜기
./api-server
해당 폴더에도 따로 .env.original이 있으니 percona와 동일하게 변경하고 .env로 저장
Percona 서버를 사용하지 않을 시 해당하는 서버에 맞게 저장
```
+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())
+44 -14
View File
@@ -1,39 +1,69 @@
from fastapi import FastAPI, status
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})
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.post("/user/update", status_code=status.HTTP_200_OK)
@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.post("/user/delete", status_code=status.HTTP_204_NO_CONTENT)
@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")
@app.post("/blog/create", status_code=status.HTTP_201_CREATED)
async def create_blog(params: BlogCreateForm):
pass
@app.post("/blog/read")
async def read_blog(params: BlogReadForm):
pass
@app.post("/blog/update")
async def update_blog(params: BlogUpdateForm):
pass
@app.post("/blog/delete")
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):
pass
await sql.delete_blog_from_id(params.blog_id)
return
+174 -3
View File
@@ -34,7 +34,6 @@ async def create_user(user_name:str, phone_number:str=None):
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="user already exist")
user_id = cur.lastrowid
print(user_id)
await cnx.commit()
return user_id
@@ -54,7 +53,7 @@ async def get_user_info_from_id(user_id:int):
raise HTTPException(status.HTTP_404_NOT_FOUND)
return user_info
async def get_user_id_from_name(user_name:str):
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 = '''
@@ -106,6 +105,17 @@ async def update_user_phone_from_id(user_id:int, phone_number:str=None):
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
@@ -114,13 +124,174 @@ async def delete_user_from_id(user_id:int):
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="user already exist")
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
+3 -7
View File
@@ -16,20 +16,16 @@ class UserDeleteForm(BaseModel):
class BlogCreateForm(BaseModel):
owner:int
blog_owner:int
blog_title:str
blog_content:str
class BlogReadForm(BaseModel):
owner:int
class BlogReadFromIdForm(BaseModel):
blog_id:int
class BlogUpdateForm(BaseModel):
owner:int
class BlogUpdateContentFromIdForm(BaseModel):
blog_id:int
blog_title:str
blog_content:str
class BlogDeleteForm(BaseModel):
owner:int
blog_id:int
+2 -1
View File
@@ -1,4 +1,5 @@
dotenv
fastapi
uvicorn[standard]
mysql-connector-python
mysql-connector-python
faker
+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);