背景
postgresとPythonで連携するノウハウ
ポスグレリンク集
日本PostgreSQLユーザ会
PythonからPostgreSQLに接続する方法
import
pythonから使うためのツールはこんな感じです。
fromflaskimportFlask,render_template,gfromhamlish_jinjaimportHamlishExtensionfromwerkzeugimportImmutableDictfromflask_sqlalchemyimportSQLAlchemy
requirements.txt
Flask==1.0.0
line-bot-sdk==1.5.0
requests
psutil
psycopg2
flask-sqlalchemy
hamlish_jinja
werkzeug
テーブル生成
importosfromflaskimportFlask,render_template,gfromhamlish_jinjaimportHamlishExtensionfromwerkzeugimportImmutableDictfromflask_sqlalchemyimportSQLAlchemyclassFlaskWithHamlish(Flask):jinja_options=ImmutableDict(extensions=[HamlishExtension])app=FlaskWithHamlish(__name__)db_uri=os.environ.get('DATABASE_URL')app.config['SQLALCHEMY_DATABASE_URI']=db_uridb=SQLAlchemy(app)classEntry(db.Model):# テーブル名を定義
__tablename__="entries"# カラムを定義
id=db.Column(db.Integer,primary_key=True)title=db.Column(db.String(),nullable=False)body=db.Column(db.String(),nullable=False)
SQL実行
## insert
cur.execute("insert into entries values(1,'HELLO WORLD1', 'aaa')")cur.execute("insert into entries values(2,'HELLO WORLD2', 'bbb')")cur.execute("insert into entries values(3,'HELLO WORLD3', 'ccc')")## select
cur.execute('SELECT * FROM entries')forrowincur:print(row[0])# 1
# 2
# 3
herokuでテーブル作成
$herokurunpython-a[app名]>>># テーブル定義されたファイルを実行
>>>fromappimportdb>>>db.create_all()
REST API
REST APIのテンプレート
api.py
fromflaskimportBlueprint,request,abort,jsonifyfrommodelsimportdb,Userapi=Blueprint('api',__name__,url_prefix='/api')@api.route('/users',methods=['GET'])deflist_user():q_limit=request.args.get('limit',default=-1,type=int)q_offset=request.args.get('offset',default=0,type=int)ifq_limit==-1:users=User.query.all()else:users=User.query.offset(q_offset).limit(q_limit)returnjsonify({'users':[user.to_dict()foruserinusers]})@api.route('/users/<int:user_id>',methods=['GET'])defget_user(user_id=None):user=User.query.filter_by(id=user_id).first()returnjsonify(user.to_dict())@api.route('/users',methods=['POST'])defpost_user():payload=request.jsonname=payload.get('name')age=payload.get('age')user=User(name,age)db.session.add(user)db.session.commit()response=jsonify(user.to_dict())response.headers['Location']='/api/users/%d'%user.idreturnresponse,201@api.route('/users/<user_id>',methods=['PUT'])defput_user(user_id):user=User.query.filter_by(id=user_id).first()ifnotuser:abort(404,{'code':'Not found','message':'user not found'})payload=request.jsonuser.name=payload.get('name')user.age=payload.get('age')db.session.commit()returnjsonify(user.to_dict())@api.route('/users/<user_id>',methods=['DELETE'])defdelete_user(user_id):user=User.query.filter_by(id=user_id).first()ifnotuser:abort(404,{'code':'Not found','message':'user not found'})db.session.delete(user)db.session.commit()returnjsonify(None),204# エラーハンドリング
@api.errorhandler(400)@api.errorhandler(404)deferror_handler(error):returnjsonify({'error':{'code':error.description['code'],'message':error.description['message']}}),error.code