pip install sqlalchemy
pip install mysql-connector-python
config.py
db = {
"user": "root",
"password": "0000!",
"host": "localhost",
"port": 3306,
"database": "minister"
}
DB_URL = f"mysql+mysqlconnector://{db['user']}:{db['password']}@{db['host']}:{db['port']}/{db['database']}?charset=utf8"
- Flask가 create_app이라는 이름의 func를 읽어 factory function으로 인식
- test_config 이라는 파라미터는 유니테스트를 실행시킬 때 테스트용db의 설정 정보를 적용하기 위함
- Flask 인스턴스의 속성으로 가리킴
import os
from flask import Flask, jsonify, request, current_app
from flask.json import JSONEncoder
from sqlalchemy import create_engine, text
...
def create_app(test_config=None):
app = Flask(__name__)
if not test_config:
app.config.from_pyfile("config.py")
else:
app.config.update(test_config)
database = create_engine(app.config["DB_URL"], encoding="utf-8", max_overflow=0)
app.database = database
return app
회원가입 엔드포인트
import os
from flask import Flask, jsonify, request, current_app
from flask.json import JSONEncoder
from sqlalchemy import create_engine, text
# class CustomJSONEncoder(JSONEncoder):
# def default(self, obj):
# if isinstance(obj, set):
# return list(obj)
# return JSONEncoder.default(self, obj)
def create_app(test_config = None):
app = Flask(__name__)
# app.json_encoder = CustomJSONEncoder
if test_config is None:
app.config.from_pyfile("config.py")
else:
app.config.update(test_config)
database = create_engine(app.config['DB_URL'], encoding = 'utf-8', max_overflow = 0) # 3)
app.database = database
@app.route("/sign-up", methods=['POST'])
def sign_up():
new_user = request.json
new_user_id = app.database.execute(text("""
INSERT INTO users(
name,
email,
profile,
hashed_password
) VALUES (
:name,
:email,
:profile,
:password
)
"""), new_user). lastrowid
row = current_app.database.execute(text("""
SELECT
id,
name,
email,
profile
FROM users
WHERE id =:user_id
"""), {
'user_id' : new_user_id
}).fetchone()
created_user = {
'id' : row['id'],
'name' : row['name'],
'email' : row['email'],
'profile' : row['profile']
} if row else None
return jsonify(created_user)
return app
http -v POST http://localhost:5000/sign-up name=현욱 email=lego7407@naver.com password=1234 profile="hi!"
mysql> select * from users
-> ;
+----+------+--------------------+-----------------+---------+---------------------+------------+
| id | name | email | hashed_password | profile | created_at | updated_at |
+----+------+--------------------+-----------------+---------+---------------------+------------+
| 3 | 현욱 | lego7407@naver.com | 1234 | hi! | 2021-02-18 23:21:06 | NULL |
+----+------+--------------------+-----------------+---------+---------------------+------------+
1 row in set (0.00 sec)
mysql>
반응형
'SW ENGINEERING > Flask' 카테고리의 다른 글
API 개발하기(14) - timeline 엔드포인트 (0) | 2021.02.21 |
---|---|
API 개발하기(13) - tweet 엔드포인트 (0) | 2021.02.21 |
API 개발하기(11) - MySQL 다루기 (0) | 2021.02.17 |
API 개발하기(10) - MySQL 설치 (0) | 2021.02.17 |
API 개발하기(9) - 데이터베이스 개념 (0) | 2021.02.17 |
최근댓글