【问题标题】:Using flask to run SQL command & output results as CSV download使用烧瓶运行 SQL 命令并将结果输出为 CSV 下载
【发布时间】:2020-10-02 21:52:57
【问题描述】:

想法:

  • 从 html 输入中获取 ID
  • 使用 id 运行 sql 并返回相关用户名
  • 单击“下载”按钮时,在前端将输出下载为 csv

html

Enter comma delimited ids <input type="text" id="text1" name="text1"><br><br>
<a href="/getPlotCSV">download</a>

蟒蛇

@app.route("/getPlotCSV", methods=['GET','POST'])
def getPlotCSV():
    text1 = request.form['text1']
    result = {}

    a = []
    x = []

    a.extend([str(x) for x in text1.split(",")])
    format_strings = ','.join(['%s'] * len(a))
    cursor = cnxn.cursor()
    sql = "SELECT DisplayName FROM dbo.[Users] where id IN ({seq})".format(
        seq=','.join(['?'] * len(a)))
    cursor.execute(sql,a)
    for row, in cursor:
        x.append(row)

    csv = x

    return Response(
        csv,
        mimetype="text/csv",
        headers={"Content-disposition":
                 "attachment; filename=myplot.csv"})

sql 和输入有效,因为我在没有 csv 下载的情况下单独对其进行了测试,并且它返回了正确的数据。我目前得到的错误是“400 Bad Request:浏览器(或代理)发送了这个服务器无法理解的请求。”键错误:'text1'

我在这里错过了什么?

【问题讨论】:

    标签: python sql flask


    【解决方案1】:

    KeyError 是因为您实际上还没有将 text1 的值传递给您的 getPlotCSV 路由。 HTML 页面上的链接也不会与它一起传输数据。相反,您需要使用带有操作页面的表单,如下所示:

    <form action="/getPageCSV" method="post">
      Enter comma delimited ids: <input type="text" id="text1" name="text1">
      <input type="submit" name="Submit" id="submit">
    </form>
    

    然后应该将这些值以action 属性的形式传递给url,在本例中为getPageCSV。不一定非要 POST,我只是举个例子。

    然后,当你的路由收到数据时:

    @app.route('/getPageCSV')
    def getPlotCSV():
        if request.method == "POST": #in other words, if the form is being submitted
          text1 = request.form.get('text1') #use dict.get in case it isn't there
          
          # your code 
    
          csv = x
          return redirect(url_for('getPlotCSV')) #this time a get method
        return Response(
            csv,
            mimetype="text/csv",
            headers={"Content-disposition":
                     "attachment; filename=myplot.csv"})
    

    如果您不以自己的方式添加将 POST 过程数据/csv 移至重定向用户时,上述内容将无法正常工作。您可以将其作为请求标头执行,将其存储在会话存储中,甚至将其放入查询字符串中,这取决于您,但是您必须能够在用户时将 POST 过程的结果显示为 GET 请求被重定向。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-24
      • 2020-09-10
      • 1970-01-01
      • 1970-01-01
      • 2013-03-16
      • 2013-07-16
      • 2016-02-07
      • 1970-01-01
      相关资源
      最近更新 更多