首页 > 解决方案 > 使用 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') 数据直接放入正文?谢谢

标签: pythonrestapiflaskpostman

解决方案


调用方法时您缺少值。 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)))


推荐阅读