python - 使用 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')
您正在发送一个元组。
如果我没有正确理解你应该打电话给 like insert_values('my_schema', 'my table',['va1', 'val2'])
。
然后查询cursor2.execute("INSERT INTO {}.{} VALUES {};".format(schema, table_name, ', '.join(list_values)))
推荐阅读
- php - 调试 exec() PHP: "sh: *.exe : 无法执行二进制文件"
- eclipse - 在 SWT 向导页面中如何仅在单击下一步按钮时编写事件
- umbraco - Umbraco 无法启动。配置了连接字符串,但 Umbraco 无法连接到数据库
- r - 由于未指定面板数据,因此使用受访者编号选择面板数据
- javascript - 如何删除包含搜索文本的父 div
- linux - 如何防止 Linux 内核在 RAM 即将耗尽时驱逐文件支持的可执行页面?(否则会导致磁盘抖动)
- azure-application-insights - 自定义查询的 Application Insights 警报
- ocr - smartFix:Tarmed 产品中 TopDown 字段的扩展
- javascript - 使用 fetch() 发出问题并承诺提取多个图像文件的 url 和 url 路径
- reactjs - React 代码 (JSX) 的 Eslint (Airbnb) 缩进问题