Skip to content

Commit 4d0a2bb

Browse files
committed
separated api
1 parent b26a2c2 commit 4d0a2bb

7 files changed

Lines changed: 126 additions & 93 deletions

File tree

app/__init__.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from sqlalchemy.sql import text
99
from flask_marshmallow import Marshmallow
1010
from app.api.database import DB
11-
from app.users.views import API
11+
from app.api import REST_API
1212

1313
SQLALCHEMY_DATABASE_URI = \
1414
("mysql+pymysql://{USER}:{PASSWORD}@{ADDR}:{PORT}/{NAME}?charset=utf8")
@@ -17,8 +17,6 @@
1717
def create_app() -> (Flask):
1818
""" create_app() 함수를 호출해 앱을 초기화 """
1919

20-
21-
2220
""" app config part """
2321
# 나중에 config는 다 빼야 할 것 같다.
2422
app = Flask(__name__)
@@ -33,7 +31,7 @@ def create_app() -> (Flask):
3331
app.config['SQLALCHEMY_ECHO'] = True
3432
app.config['DEBUG'] = True
3533
DB.init_app(app)
36-
API.init_app(app)
34+
REST_API.init_app(app)
3735
MA.init_app(app)
3836

3937
""" return part """

app/api/__init__.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
from flask_restplus import Api
2+
from app.users.views import API as users_api
3+
from app.posts.views import API as posts_api
24

3-
API = Api(title='Board API',
4-
version='1.0',
5-
description="Board REST API"
6-
# All API metadatas
7-
)
5+
REST_API = Api()
6+
7+
REST_API.add_namespace(users_api, '/users')
8+
REST_API.add_namespace(posts_api, '/posts')

app/posts/__init__.py

Whitespace-only changes.

app/posts/models.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
from app.api.database import DB, CRUD
2+
from marshmallow import Schema, fields
3+
from flask_sqlalchemy import SQLAlchemy
4+
from marshmallow import validate
5+
from sqlalchemy.sql import text
6+
from app.users.models import Users, UsersSchema
7+
8+
class Post(DB.Model):
9+
__tablename__ = 'posts'
10+
__table_args__ = {'mysql_collate': 'utf8_general_ci'}
11+
12+
id = DB.Column(DB.Integer, primary_key=True)
13+
name = DB.Column(DB.String(255), nullable=False)
14+
author_id = DB.Column(DB.Integer, DB.ForeignKey(Users.id))
15+
author = DB.relationship("Users", uselist=False)
16+
17+
def __init__(self, name: str, author_id: int):
18+
self.name = name
19+
self.author_id = author_id
20+
21+
class PostSchema(Schema):
22+
id = fields.Integer()
23+
name = fields.Str()
24+
author = fields.Nested(UsersSchema)

app/posts/views.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
from http import HTTPStatus
2+
from flask import jsonify
3+
from flask import make_response
4+
from app.users.models import Users, UsersSchema
5+
from sqlalchemy.exc import SQLAlchemyError
6+
from flask_restplus import Api, Namespace, fields, reqparse, Resource
7+
from app.constants import STATUS_CODE
8+
from app.constants import GET, POST, PATCH, DELETE
9+
from app.posts.models import Post, PostSchema
10+
from app.api.database import DB
11+
12+
API = Namespace('Posts',description="Post's REST API")
13+
14+
POSTS_SCHEMA = PostSchema()
15+
16+
POST_FIELDS = API.model('Post', {
17+
'name': fields.String,
18+
'author_id': fields.Integer,
19+
})
20+
21+
@API.route('/posts')
22+
class Posts(Resource):
23+
parser = reqparse.RequestParser()
24+
parser.add_argument('name', required=True, type=str, help="post's name", location='json')
25+
parser.add_argument('author_id', required=True, type=int, help="post's author", location='json')
26+
27+
@API.expect(POST_FIELDS)
28+
def post(self):
29+
args_ = self.parser.parse_args()
30+
post = Post(name=args_['name'], author_id=args_['author_id'])
31+
try:
32+
DB.session.add(post)
33+
DB.session.commit()
34+
body = jsonify({"posts": POSTS_SCHEMA.dump(post).data})
35+
code = HTTPStatus.OK
36+
except SQLAlchemyError as err:
37+
DB.session.rollback()
38+
message = str(err)
39+
body = jsonify({"message": message})
40+
code = HTTPStatus.INTERNAL_SERVER_ERROR
41+
return make_response(body, code.value)
42+
43+
@API.route('/post/<int:seqno>')
44+
class PostItem(Resource):
45+
def get(self, seqno):
46+
try:
47+
post_item = DB.session.query(Post).outerjoin(Users, Users.id==Post.author_id).filter(Post.id==seqno).first()
48+
body = jsonify({"post":POSTS_SCHEMA.dump(post_item).data})
49+
if post_item:
50+
code = HTTPStatus.OK
51+
else:
52+
code = HTTPStatus.NOT_FOUND
53+
except SQLAlchemyError as err:
54+
message = str(err)
55+
body = jsonify({"message": message})
56+
code = HTTPStatus.INTERNAL_SERVER_ERROR
57+
return make_response(body, code.value)

app/users/models.py

Lines changed: 1 addition & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from app.api.database import DB, CRUD
1+
from app.api.database import DB
22
from marshmallow import Schema, fields
33
from flask_sqlalchemy import SQLAlchemy
44
from marshmallow import validate
@@ -40,23 +40,3 @@ def get_top_level_links(self, data, many):
4040
class Meta:
4141
type_ = 'users'
4242
strict = True
43-
44-
45-
46-
class Post(DB.Model):
47-
__tablename__ = 'posts'
48-
__table_args__ = {'mysql_collate': 'utf8_general_ci'}
49-
50-
id = DB.Column(DB.Integer, primary_key=True)
51-
name = DB.Column(DB.String(255), nullable=False)
52-
author_id = DB.Column(DB.Integer, DB.ForeignKey(Users.id))
53-
author = DB.relationship("Users", uselist=False)
54-
55-
def __init__(self, name: str, author_id: int):
56-
self.name = name
57-
self.author_id = author_id
58-
59-
class PostSchema(Schema):
60-
id = fields.Integer()
61-
name = fields.Str()
62-
author = fields.Nested(UsersSchema)

app/users/views.py

Lines changed: 36 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -6,28 +6,11 @@
66
from flask_restplus import Api, Namespace, fields, reqparse, Resource
77
from app.constants import STATUS_CODE
88
from app.constants import GET, POST, PATCH, DELETE
9-
from app.users.models import Post, PostSchema
109
from app.api.database import DB
1110

12-
API = Api(title='Board API',
13-
version='1.0',
14-
description="Board REST API"
15-
# All API metadatas
16-
)
17-
18-
SCHEMA = UsersSchema()
19-
post_schema = PostSchema()
20-
21-
USER_FIELDS = API.model('Users', {
22-
'name': fields.String,
23-
'email': fields.String,
24-
'password': fields.String
25-
})
26-
POST_FIELDS = API.model('Post', {
27-
'name': fields.String,
28-
'author_id': fields.Integer,
29-
})
11+
API = Namespace('Users',description="User's REST API")
3012

13+
USERS_SCHEMA = UsersSchema()
3114

3215
@API.route('/users/<int:user_id>')
3316
@API.param('user_id', 'The user identifier')
@@ -37,25 +20,31 @@ class UserItem(Resource):
3720
parser.add_argument('email', required=True, type=str, help="user's email", location='json')
3821
parser.add_argument('password', required=True, type=str, help="password", location='json')
3922

23+
user_field = API.model('Users', {
24+
'name': fields.String,
25+
'email': fields.String,
26+
'password': fields.String
27+
})
28+
4029
@API.doc(responses=GET)
4130
def get(self, user_id):
4231
user = Users.query.get_or_404(user_id)
43-
user = SCHEMA.dump(user).data
32+
user = USERS_SCHEMA.dump(user).data
4433
return user
4534

46-
@API.expect(USER_FIELDS)
35+
@API.expect(user_field)
4736
@API.doc(responses=PATCH)
4837
def patch(self, user_id):
4938
args = self.parser.parse_args()
5039
user = Users.query.get_or_404(user_id)
51-
response = user.update(args, SCHEMA)
40+
response = user.update(args, USERS_SCHEMA)
5241
return response
5342

5443
@API.doc(responses=DELETE)
5544
def delete(self, user_id):
5645
#import pdb; pdb.set_trace()
5746
user = Users.query.get_or_404(user_id)
58-
response = user.delete(user, SCHEMA)
47+
response = user.delete(user, USERS_SCHEMA)
5948
return response
6049

6150

@@ -66,19 +55,25 @@ class UsersList(Resource):
6655
parser.add_argument('email', required=True, type=str, help="user's email", location='json')
6756
parser.add_argument('password', required=True, type=str, help="password", location='json')
6857

58+
user_field = API.model('Users', {
59+
'name': fields.String,
60+
'email': fields.String,
61+
'password': fields.String
62+
})
63+
6964
def get(self):
7065
users_query = Users.query.all()
71-
results = SCHEMA.dump(users_query, many=True).data
66+
results = USERS_SCHEMA.dump(users_query, many=True).data
7267
return results
7368

74-
@API.expect(USER_FIELDS)
69+
@API.expect(user_field)
7570
def post(self):
7671
args = self.parser.parse_args()
7772
user = Users(args['name'], args['email'], args['password'])
7873
try:
7974
DB.session.add(user)
8075
DB.session.commit()
81-
body = jsonify({"users": SCHEMA.dump(user).data})
76+
body = jsonify({"users": USERS_SCHEMA.dump(user).data})
8277
code = HTTPStatus.OK
8378
except SQLAlchemyError as err:
8479
DB.session.rollback()
@@ -87,52 +82,30 @@ def post(self):
8782
code = HTTPStatus.INTERNAL_SERVER_ERROR
8883
return make_response(body, code.value)
8984

90-
@API.route('/posts')
91-
class Posts(Resource):
85+
@API.route('/users/auth')
86+
class GetUser(Resource):
9287
parser = reqparse.RequestParser()
93-
parser.add_argument('name', required=True, type=str, help="post's name", location='json')
94-
parser.add_argument('author_id', required=True, type=int, help="post's author", location='json')
88+
parser.add_argument('name', required=True, type=str, help="user's name", location='json')
89+
parser.add_argument('password', required=True, type=str, help="user's password", location='json')
9590

96-
@API.expect(POST_FIELDS)
97-
def post(self):
98-
args_ = self.parser.parse_args()
99-
post = Post(name=args_['name'], author_id=args_['author_id'])
100-
try:
101-
DB.session.add(post)
102-
DB.session.commit()
103-
body = jsonify({"posts": post_schema.dump(post).data})
104-
code = HTTPStatus.OK
105-
except SQLAlchemyError as err:
106-
DB.session.rollback()
107-
message = str(err)
108-
body = jsonify({"message": message})
109-
code = HTTPStatus.INTERNAL_SERVER_ERROR
110-
return make_response(body, code.value)
91+
user_field = API.model('Auth', {
92+
'name': fields.String,
93+
'password': fields.String
94+
})
11195

112-
@API.route('/post/<int:seqno>')
113-
class PostItem(Resource):
114-
def get(self, seqno):
96+
@API.expect(user_field)
97+
def post(self):
98+
args = self.parser.parse_args()
11599
try:
116-
post_item = DB.session.query(Post).outerjoin(Users, Users.id==Post.author_id).filter(Post.id==seqno).first()
117-
body = jsonify({"post":post_schema.dump(post_item).data})
118-
if post_item:
100+
user = Users.query.filter(Users.name == args['name'] and Users.password == args['password']).first()
101+
body = jsonify({"user" : USERS_SCHEMA.dump(user).data})
102+
if user:
119103
code = HTTPStatus.OK
120104
else:
121105
code = HTTPStatus.NOT_FOUND
122106
except SQLAlchemyError as err:
123107
message = str(err)
124-
body = jsonify({"message": message})
108+
body = jsonify({"message" : message})
125109
code = HTTPStatus.INTERNAL_SERVER_ERROR
126110
return make_response(body, code.value)
127111

128-
@API.route('/userLogin')
129-
class GetUser(Resource):
130-
parser = reqparse.RequestParser()
131-
parser.add_argument('name', required=True, type=str, help="user's name", location='json')
132-
parser.add_argument('password', required=True, type=str, help="user's password", location='json')
133-
134-
@API.expect(USER_FIELDS)
135-
def post(self):
136-
args = self.parser.parse_args()
137-
user = Users.query.filter(Users.name == args['name']).first()
138-
import pdb; pdb.set_trace()

0 commit comments

Comments
 (0)