POST数据并使用Python/Flask创建REST API



我从REST API开始,我需要开发一个API来将值插入到PG数据库中。

我将在另一个Flask应用程序中使用此API端点("/myendpoint"(,方法为:r = requests.post('https:/myendpoint', params=payload, verify=False)

api.py:

def insert_values(schema, table_name, list_values):
cursor2 = connection.cursor() 
cursor2.execute("INSERT INTO "+schema+"."+table_name+" VALUES "+str(list_values)+ ";")
connection.commit()


@app.route('/myendpoint', methods=("POST","GET","PUT"))
def insert():
if request.method == 'POST':
if request.args['key']=="hello":
table = request.args.get('table')
connect_to_db()
insert_values(schema, table, ('hello','world'))
#close DB connexion
close_db_connect()
return'''<h1>INSERT INTO PG</h1>'''

当我在Postman上测试连接时,我如何修复代码,以便将我的("hello"、"world"(数据直接放入体内?谢谢

调用方法时缺少值。insert_values(table, ('hello','world'))应该是insert_values(table, ('hello','world'), another_something),当您发送('hello','world')时,您正在发送一个元组。

如果我没有错的话,你应该像insert_values('my_schema', 'my table',['va1', 'val2'])那样打电话。

然后查询cursor2.execute("INSERT INTO {}.{} VALUES {};".format(schema, table_name, ', '.join(list_values)))

最新更新