22 app init
33"""
44
5- from flask import Flask , render_template
5+ from flask import Flask , render_template , jsonify
66from flask_restplus import Resource , Api , fields , reqparse
77from flask_sqlalchemy import SQLAlchemy
88from sqlalchemy .exc import SQLAlchemyError
99from sqlalchemy .sql import text
10- from flask_bootstrap import Bootstrap
10+ from flask_marshmallow import Marshmallow
1111
1212DB = SQLAlchemy ()
1313SQLALCHEMY_DATABASE_URI = \
1414 ("mysql+pymysql://{USER}:{PASSWORD}@{ADDR}:{PORT}/{NAME}?charset=utf8" )
15-
1615# API Doc에 대한 설명을 덧 붙이기 위한 생성자
1716API = Api (version = '1.0' , title = 'Board API' ,
1817 description = 'A simple Board RESTPlus API' ,)
1918# 설명할 API에 대한 것
2019api_ns = API .namespace ('userinfo' , description = 'UserInfo operations' )
20+ MA = Marshmallow ()
2121
2222class UserInfo (DB .Model ):
2323 """ UserInfo model """
2424 __tablename__ = "userinfo"
2525 __table_args__ = {'mysql_collate' : 'utf8_general_ci' }
2626 id = DB .Column ("id" , DB .Integer , primary_key = True )
2727 name = DB .Column ("name" , DB .String (250 ), nullable = False )
28+ age = DB .Column ("age" , DB .Integer , nullable = False )
2829 tel = DB .Column ("tel" , DB .String (20 ), nullable = False )
30+ email = DB .Column ("email" , DB .String (50 ), nullable = False )
2931 created = DB .Column (DB .TIMESTAMP , server_default = text ("CURRENT_TIMESTAMP" ), nullable = False )
3032
31- def __init__ (self , name , tel ):
33+ def __init__ (self , name , age , tel , email ):
3234 self .name = name
35+ self .age = age
3336 self .tel = tel
37+ self .email = email
3438
3539def create_app () -> (Flask ):
3640 """ create_app() 함수를 호출해 앱을 초기화 """
@@ -41,7 +45,6 @@ def create_app() -> (Flask):
4145 # 나중에 config는 다 빼야 할 것 같다.
4246 app = Flask (__name__ )
4347 app .app_context ().push ()
44- Bootstrap (app )
4548 app .config ['SQLALCHEMY_DATABASE_URI' ] = SQLALCHEMY_DATABASE_URI .format (
4649 USER = "root" ,
4750 PASSWORD = "1234" ,
@@ -53,16 +56,22 @@ def create_app() -> (Flask):
5356 app .config ['DEBUG' ] = True
5457 DB .init_app (app )
5558 API .init_app (app )
56-
57-
59+ MA .init_app (app )
5860
5961 """ API model을 보이기 위한 설명 추가 """
6062 # 나중에 따로 빼야 할 것 같다.
6163 user_info = API .model ('UserInfo' , {
6264 'name' : fields .String (required = True , description = "User's name" ),
63- 'tel' : fields .String (required = True , description = "User's tel" )
65+ 'age' : fields .Integer (required = True , description = "User's age" ),
66+ 'tel' : fields .String (required = True , description = "User's tel" ),
67+ 'email' : fields .String (required = True , description = "User's email" )
6468 })
6569
70+ class UserSchema (MA .Schema ):
71+ class Meta :
72+ # Fields to expose
73+ fields = ("name" , "age" , "tel" , "email" )
74+
6675
6776
6877 """ API.route part"""
@@ -72,13 +81,75 @@ def get(self):
7281 return {'hello' : 'world' }
7382
7483 @api_ns .route ('/users' )
84+ class Show (Resource ):
85+ post_parser = reqparse .RequestParser (bundle_errors = True )
86+ post_parser .add_argument ('name' , required = True , type = str , help = "user name" ,location = 'json' )
87+ post_parser .add_argument ('age' , required = True , type = int , help = "user age" ,location = 'json' )
88+ post_parser .add_argument ('tel' , required = True , type = str , help = "user tel" ,location = 'json' )
89+ post_parser .add_argument ('email' , required = True , type = str , help = "user email" ,location = 'json' )
90+ def get (self ):
91+ user_schema = UserSchema (many = True )
92+ all_users = DB .session .query (UserInfo ).all ()
93+ result = user_schema .dump (all_users )
94+ return jsonify (result .data )
95+
96+ @api_ns .expect (user_info )
97+ def post (self ):
98+ args_ = self .post_parser .parse_args ()
99+ user = UserInfo (name = args_ ['name' ], age = args_ ['age' ], tel = args_ ['tel' ], email = args_ ['email' ])
100+ message = "not working"
101+ try :
102+ DB .session .add (user )
103+ DB .session .commit ()
104+ message = "success"
105+ except SQLAlchemyError as err :
106+ message = str (err )
107+ DB .session .rollback ()
108+ finally :
109+ DB .session .close ()
110+ return message
111+
112+ @api_ns .expect (user_info )
113+ def delete (self ):
114+ args_ = self .post_parser .parse_args ()
115+ user = UserInfo .query .filter_by (name = args_ ['name' ]).first ()
116+ try :
117+ DB .session .delete (user )
118+ DB .session .commit ()
119+ message = "success"
120+ except SQLAlchemyError as err :
121+ message = str (err )
122+ DB .session .rollback ()
123+ finally :
124+ DB .session .close ()
125+ return message
126+
127+ @api_ns .route ('/test' )
128+ class Test (Resource ):
129+ post_parser = reqparse .RequestParser (bundle_errors = True )
130+ post_parser .add_argument ('name' , required = True , type = str , help = "user name" ,location = 'json' )
131+ post_parser .add_argument ('age' , required = True , type = int , help = "user age" ,location = 'json' )
132+ post_parser .add_argument ('tel' , required = True , type = str , help = "user tel" ,location = 'json' )
133+ post_parser .add_argument ('email' , required = True , type = str , help = "user email" ,location = 'json' )
134+ def get (self ):
135+ return {'test' : 'test' }
136+
137+ @api_ns .expect (user_info )
138+ def post (self ):
139+ args_ = self .post_parser .parse_args ()
140+ user = UserInfo (name = args_ ['name' ], age = args_ ['age' ], tel = args_ ['tel' ], email = args_ ['email' ])
141+ return {'name' : 'server' + user .name , 'age' : user .age , 'tel' : user .tel , 'email' : user .email }
142+
143+
144+ @api_ns .route ('/test' )
75145 class HelloWorld (Resource ):
76146 post_parser = reqparse .RequestParser (bundle_errors = True )
77147 post_parser .add_argument ('name' , required = True , type = str , help = "user name" ,location = 'json' )
78148 post_parser .add_argument ('tel' , type = str , help = "user tel" ,location = 'json' )
79149
80150 def get (self ):
81151 userInfo = DB .session .query (UserInfo ).all ()
152+ import pdb ; pdb .set_trace ()
82153 return {'hello' : 'world' }
83154
84155 @api_ns .expect (user_info )
@@ -98,20 +169,5 @@ def post(self):
98169 DB .session .close ()
99170 return message
100171
101-
102-
103- """ app.route part """
104- # 나중에 route는 다 빼야 할 것 같다.
105- @app .route ("/index" )
106- def index ():
107- """ / url index """
108- return render_template ('/index.html' )
109-
110- @app .route ("/register" )
111- def register ():
112- """ 회원가입 페이지 """
113- return render_template ('/register.html' )
114-
115-
116172 """ return part """
117173 return app
0 commit comments