Skip to content

Commit fef3e91

Browse files
committed
Users, Posts 를 MVC 분리
1 parent 75f909c commit fef3e91

11 files changed

Lines changed: 90 additions & 36 deletions

File tree

.gitignore

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,6 @@
99
__pycache__
1010

1111
# testcode
12-
.pytest_cache
12+
.pytest_cache
13+
.coverage
14+
cov_html

Makefile

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
GREEN=\033[1;32;40m
2+
RED=\033[1;31;40m
3+
NC=\033[0m # No Color
4+
5+
test:
6+
@bash -c "echo -e \"${GREEN}[pytest 시작]${NC}\""
7+
pipenv run pytest app/tests --cov-report=html:cov_html --cov-report=term --cov=app

app/api/database.py

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,33 @@
11
"""
22
Create db
33
"""
4-
4+
from flask import jsonify
5+
from flask import make_response
6+
from http import HTTPStatus
57
from flask_sqlalchemy import SQLAlchemy
8+
from sqlalchemy.exc import IntegrityError
69
from flask_marshmallow import Marshmallow
710

811
DB = SQLAlchemy()
9-
MA = Marshmallow()
12+
MA = Marshmallow()
13+
14+
class CRUD:
15+
body = ''
16+
status_code = HTTPStatus.NOT_IMPLEMENTED
17+
18+
def add(self, resource, schema):
19+
try:
20+
DB.session.add(resource)
21+
DB.session.commit()
22+
self.body = jsonify(schema.dump(resource).data)
23+
self.status_code = HTTPStatus.OK
24+
except IntegrityError as err:
25+
DB.session.rollback()
26+
err_meg = str(err)
27+
self.body = jsonify({'error' : err_meg, 'type' : 'IntegrityError'})
28+
if "Duplicate entry" in err_meg:
29+
self.status_code = HTTPStatus.CONFLICT
30+
else:
31+
self.status_code = HTTPStatus.BAD_REQUEST
32+
return make_response(self.body, self.status_code)
33+

app/posts/models.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,12 @@
22
Posts model file
33
"""
44

5-
from app.api.database import DB, MA
5+
from app.api.database import DB, MA, CRUD
66
from marshmallow import Schema, fields, validate
77
from app.users.models import Users, UsersSchema
88
from sqlalchemy.sql import text
99

10-
class Posts(DB.Model):
10+
class Posts(DB.Model, CRUD):
1111
__tablename__ = 'posts'
1212
__table_args__ = {'mysql_collate': 'utf8_general_ci'}
1313

app/posts/views.py

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,10 @@ def get(self):
3131
try:
3232
posts = Posts.query.all()
3333
body = jsonify(POSTS_SCHEMA.dump(posts, many=True).data)
34-
code = HTTPStatus.OK
34+
if posts:
35+
code = HTTPStatus.OK
36+
else:
37+
code = HTTPStatus.NOT_FOUND
3538
except SQLAlchemyError as err:
3639
body = jsonify({'message' : str(err)})
3740
code = HTTPStatus.INTERNAL_SERVER_ERROR
@@ -42,24 +45,19 @@ def get(self):
4245
def post(self):
4346
args_ = self.parser.parse_args()
4447
post = Posts(author_id=args_['author_id'], title=args_['title'], body=args_['body'])
45-
try:
46-
DB.session.add(post)
47-
DB.session.commit()
48-
body = jsonify({'post', POSTS_SCHEMA.dump(post).data})
49-
code = HTTPStatus.OK
50-
except SQLAlchemyError as err:
51-
body = jsonify({'message' : str(err)})
52-
code = HTTPStatus.INTERNAL_SERVER_ERROR
53-
return make_response(body, code.value)
48+
return post.add(post, POSTS_SCHEMA)
5449

5550
@API.route('/<int:reqno>')
5651
class PostItem(Resource):
5752
def get(self, reqno):
5853
try:
5954
post = DB.session.query(Posts).outerjoin(
6055
Users, Users.user_id == Posts.author_id).filter(Posts.id==reqno).first()
61-
body = jsonify({'post' : POSTS_SCHEMA.dump(post).data})
62-
code = HTTPStatus.OK
56+
body = POSTS_SCHEMA.dump(post).data
57+
if post:
58+
code = HTTPStatus.OK
59+
else:
60+
code = HTTPStatus.NOT_FOUND
6361
except SQLAlchemyError as err:
6462
body = jsonify({'message' : str(err)})
6563
code = HTTPStatus.INTERNAL_SERVER_ERROR

app/tests/conftest.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import pytest
2+
from app import create_app # flask application factory
3+
4+
@pytest.fixture(scope='session')
5+
def flask_app():
6+
app = create_app()
7+
app_context = app.app_context()
8+
app_context.push()
9+
yield app
10+
app_context.pop()

app/tests/test_models.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
from app.posts.models import Posts
2+
from app.users.models import Users
3+
4+
def test_posts_init():
5+
test_post = Posts("a", "b", "c")
6+
assert type(test_post.author_id) is str
7+
assert type(test_post.title) is str
8+
assert type(test_post.body) is str
9+
10+
def test_users_init():
11+
test_user = Users("a", "b", "c")
12+
assert type(test_user.user_id) is str
13+
assert type(test_user.user_password) is str
14+
assert type(test_user.user_email) is str

app/tests/test_practice.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,5 +18,3 @@ def test_practice():
1818
except ValueError as err:
1919
message = str(err)
2020
print(message)
21-
print(result)
22-
assert False

app/tests/test_request.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
from http import HTTPStatus
2+
from app import create_app
3+
4+
def test_url(flask_app):
5+
with flask_app.test_client() as client:
6+
response = client.get('/posts')
7+
assert response.status_code == HTTPStatus.OK

app/users/models.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@
22
Users models file
33
"""
44
from sqlalchemy.sql import text
5-
from app.api.database import DB, MA
5+
from app.api.database import DB, MA, CRUD
66
from flask_sqlalchemy import SQLAlchemy
77
from marshmallow import Schema, fields, validate
88

9-
class Users(DB.Model):
9+
class Users(DB.Model, CRUD):
1010
__tablename__ = 'users'
1111
__table_args__ = {'mysql_collate': 'utf8_general_ci'}
1212

@@ -16,7 +16,7 @@ class Users(DB.Model):
1616
user_email = DB.Column(DB.String(255), nullable=False)
1717
created = DB.Column(DB.TIMESTAMP, server_default=text("CURRENT_TIMESTAMP"), nullable=False)
1818

19-
def __init__(self, user_id, user_password, user_email):
19+
def __init__(self, user_id : str, user_password : str, user_email : str):
2020
self.user_id = user_id
2121
self.user_password = user_password
2222
self.user_email = user_email

0 commit comments

Comments
 (0)