[英]POST data and creating REST API with Python/Flask
我從 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)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.