我正在使用python 3.6使用get方法编写一个flask api,它将与GCP postgreSQL创建连接并执行一个简单的select查询。在这里,我希望我的函数应该向我返回postgreSQL查询(行)的结果。下面是我的代码:
from sqlalchemy.engine import url
import pg8000
import logging
import os
import json
from flask import Flask, Response, request, render_template
import sqlalchemy
app = Flask(__name__)
logger = logging.getLogger()
# Environment specific parameter values to establish DB connection with postgreSQL
db_user = os.environ.get("DB_USER")
db_pass = os.environ.get("DB_PASS")
db_name = os.environ.get("DB_NAME")
cloud_sql_connection_name = os.environ.get("CLOUD_SQL_CONNECTION_NAME")
# Creating a connection with postgresql DB model.
db = sqlalchemy.create_engine(
url.URL(
drivername='postgres+pg8000',
username=db_user,
password=db_pass,
database=db_name,
query={
'unix_sock': '/cloudsql/{}/.s.PGSQL.5432'.format(
cloud_sql_connection_name)
}
),
pool_size=5,
max_overflow=2,
pool_timeout=30,
pool_recycle=1800,
)
@app.route('/', methods=['GET'])
def main(request):
with db.connect() as conn:
# Execute the query and fetch all usernames
users = conn.execute("select username from user_table").fetchall()
return users
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8080, debug=True)
答案 0 :(得分:1)
我尝试了您的代码并收到此错误:
TypeError:视图函数未返回有效响应。返回类型必须是字符串,字典,元组,Response实例或可调用的WSGI,但这是一个列表
因此,请尝试返回str(users)
或先将数据转换为字典。
答案 1 :(得分:0)
fetchall()从文档https://docs.sqlalchemy.org/en/13/core/connections.html#sqlalchemy.engine.ResultProxy.fetchall返回光标。您不能将游标对象作为响应返回。您需要将其转换为允许的响应类型。下面的代码可能会帮助您理解相同的内容。
@app.route('/', methods=['GET'])
def main(request):
users = []
with db.connect() as conn:
# Execute the query and fetch all usernames
db_users = conn.execute("select username from user_table").fetchall()
users = list(db_users)
data = {'users': users}
resp = Response(json.dumps(data), status=200, mimetype="application/json")
return resp