在有效负载中传递多个或零值以使用 Python 调用 REST API



如何使用来自数据库的多个值或无值来调用python的post API,而不是对有效负载中的值进行硬编码? 这意味着每当我调用 post API 时,有效负载值 [id] 都可以根据 SQL 查询生成的一个或多个 id 进行更改。 当我对它进行硬编码并在有效负载中传递一个值时,它可以工作:

dictionary={"profile_fields": {"name":["email", "address"]},"filters": {"id": "AB1"}}

但是当我不想对其进行硬编码并使用用于查询数据库的变量名称时,我没有得到任何结果,也没有看到任何错误。

dictionary={"profile_fields": {"name": ["email","address"]},"filters": {"id": 
df}}

谢谢你的帮助。

SQL 输出示例:

col1:
AB1
AB2

代码示例 Python 3:

c = con.cursor()
# sql query from sqlite, the output can be 1 vaue or two or even empty
c.execute('select col1 from t1 where col1 = col2')
df=c.fetchall()
print('checking the output of sql',df)
#print output:
# [('AB1',), ('AB2',)]
# data payload
dictionary={"profile_fields": {"name": ["email", "address"]},"filters": {"id": df}}
# url
url='https://...'
#post api call
response= response.post(url,json=dictionary,...)

if (responce.status_code == 200):
#response back in JSON format
df = response.json()
print('Success!')
else:
print('error.. ')

我没有得到任何结果,也没有看到任何错误

这很奇怪,因为pd.read_sql_query的结果是一个数据帧,而fetchall是一个cursor的方法。我很确定它不应该在那里,调用它会引发一个例外。

接下来,df是一个数据帧,并且可能是二维的,因为您没有在read_sql_query中指定列。因此,您正在发送id的数组数组。尝试打印有效负载以查看正在发送的内容:

print(json.dumps(dictionary))

df转换为id的集合:

ids = tuple(df[0])

现在,ids可能为空,但它可能是一个或多个值。您如何处理这个问题不在这个问题的范围内,但现在您可以id = ids[0]并将其放入dictionary(而不是df(。

最新更新