我需要根据Flask网络应用的用户输入动态查询我的Postgres数据库。我曾在Python中使用它,但是当我将其移至Flask时,它停止了工作。我已将其范围缩小到在查询中插入变量的问题。
def predict_page():
address_lookup = '10 West 28 Street'
# eventually this would take a user input like below
# address_lookup = request.args.get('address')
sq = """SELECT noise, population_density, median_home_value,
median_household_income, yearbuilt, vacant FROM
lookup_table WHERE address = %(input_address)s;"""
param = {'input_address':address_lookup}
query_results = pd.read_sql_query(sq, con, params = param)
query_results = query_results.to_json()
return query_results
当我在查询中明确地写地址而不是变量时,它就起作用了。
def predict_page():
sq = """SELECT noise, population_density, median_home_value,
median_household_income, yearbuilt, vacant FROM lookup_table
WHERE address = '10 West 28 Street';"""
query_results = pd.read_sql_query(sq, con)
query_results = query_results.to_json()
return query_results
答案 0 :(得分:1)
我认为您所缺少的只是sq
字符串中的单引号:
address_lookup = '10 West 28 Street'
sq = """SELECT noise, population_density, median_home_value,
median_household_income, yearbuilt, vacant FROM
lookup_table WHERE address = '%s';""" % address_lookup
print sq
输出:
SELECT noise, population_density, median_home_value,
median_household_income, yearbuilt, vacant FROM
lookup_table WHERE address = '10 West 28 Street';
注意
我写了这个答案,以便可以独立运行,因为我想着重解决缺少单引号的问题。任何使用read_sql_query
的人都应该使用所需的任何参数传递语法来允许服务器进行输入清理。您不要要通过使用Python格式将参数插入SQL查询字符串来绕过服务器端参数验证。