33"""
44
55from flask import Flask
6+ from flask_restplus import Resource , Api , fields , reqparse
67from flask_sqlalchemy import SQLAlchemy
8+ from sqlalchemy .exc import SQLAlchemyError
79from sqlalchemy .sql import text
810
911DB = SQLAlchemy ()
1012SQLALCHEMY_DATABASE_URI = \
1113 ("mysql+pymysql://{USER}:{PASSWORD}@{ADDR}:{PORT}/{NAME}?charset=utf8" )
14+
15+ # API Doc์ ๋ํ ์ค๋ช
์ ๋ง ๋ถ์ด๊ธฐ ์ํ ์์ฑ์
16+ API = Api (version = '1.0' , title = 'Board API' ,
17+ description = 'A simple Board RESTPlus API' ,)
18+ # ์ค๋ช
ํ API์ ๋ํ ๊ฒ
19+ api_ns = API .namespace ('userinfo' , description = 'UserInfo operations' )
1220
13- class Userinfo (DB .Model ):
14- """ Userinfo model """
21+ class UserInfo (DB .Model ):
22+ """ UserInfo model """
1523 __tablename__ = "userinfo"
1624 __table_args__ = {'mysql_collate' : 'utf8_general_ci' }
1725 id = DB .Column ("id" , DB .Integer , primary_key = True )
@@ -26,6 +34,8 @@ def __init__(self, name, tel):
2634def create_app () -> (Flask ):
2735 """ create_app() ํจ์๋ฅผ ํธ์ถํด ์ฑ์ ์ด๊ธฐํ """
2836
37+
38+
2939 """ app config part """
3040 # ๋์ค์ config๋ ๋ค ๋นผ์ผ ํ ๊ฒ ๊ฐ๋ค.
3141 app = Flask (__name__ )
@@ -40,10 +50,55 @@ def create_app() -> (Flask):
4050 app .config ['SQLALCHEMY_ECHO' ] = True
4151 app .config ['DEBUG' ] = True
4252 DB .init_app (app )
53+ API .init_app (app )
54+
55+
56+
57+ """ API model์ ๋ณด์ด๊ธฐ ์ํ ์ค๋ช
์ถ๊ฐ """
58+ # ๋์ค์ ๋ฐ๋ก ๋นผ์ผ ํ ๊ฒ ๊ฐ๋ค.
59+ user_info = API .model ('UserInfo' , {
60+ 'name' : fields .String (required = True , description = "User's name" ),
61+ 'tel' : fields .String (required = True , description = "User's tel" )
62+ })
63+
64+
65+
66+ """ API.route part"""
67+ @api_ns .route ("/hello" )
68+ class HelloWorld (Resource ):
69+ def get (self ):
70+ return {'hello' : 'world' }
71+
72+ @api_ns .route ('/users' )
73+ class HelloWorld (Resource ):
74+ post_parser = reqparse .RequestParser (bundle_errors = True )
75+ post_parser .add_argument ('name' , required = True , type = str , help = "user name" ,location = 'json' )
76+ post_parser .add_argument ('tel' , type = str , help = "user tel" ,location = 'json' )
77+
78+ def get (self ):
79+ userInfo = DB .session .query (UserInfo ).all ()
80+ return {'hello' : 'world' }
81+
82+ @api_ns .expect (user_info )
83+ def post (self ):
84+ """ ์ ์ ์์ฑ """
85+ args_ = self .post_parser .parse_args ()
86+ user = UserInfo (name = args_ ['name' ], tel = args_ ['tel' ])
87+ message = "not working"
88+ try :
89+ DB .session .add (user )
90+ DB .session .commit ()
91+ message = "success"
92+ except SQLAlchemyError as err :
93+ message = str (err )
94+ DB .session .rollback ()
95+ finally :
96+ DB .session .close ()
97+ return message
4398
44- """ route part """
99+ """ app. route part """
45100 # ๋์ค์ route๋ ๋ค ๋นผ์ผ ํ ๊ฒ ๊ฐ๋ค.
46- @app .route ("/" )
101+ @app .route ("/index " )
47102 def index ():
48103 """ / url index """
49104 return "<h1>Hello World ! <br> This is index page</h1>"
0 commit comments