Flask TypeError: 预期的字节

huangapple go评论74阅读模式
英文:

Flask TypeError: Expected bytes

问题

我正在尝试从表格中获取数据并响应结果。我遇到了这个问题,因为数据来自数据库。以下是代码:

cursor = connection.cursor()
cursor.execute("select * from table")
result = cursor.fetchall()
for row in result:
    data = row
connection.close()
return Response(
    data,
    mimetype="text/csv",
    headers={
        "Content-disposition": "attachment; filename=data.csv"
    },
)

在尝试获取数据时,我遇到了这个错误:

TypeError: 期望的是字节

我该如何解决这个问题?

英文:

I'm trying to get data from a table and response the result. I am facing this issue since the data is from a database. Below is the code:

cursor = connection.cursor()
cursor.execute("""select * from table""")
result = cursor.fetchall()
for row in result:
    data = row
connection.close()
return Response(
    data,
    mimetype="text/csv",
    headers={
        "Content-disposition": "attachment; filename=data.csv"
    },
)

While trying to get it, I am getting this error:

TypeError: Expected bytes

How can I resolve this?

答案1

得分: 1

以下是翻译好的代码部分,不包括翻译请求的内容:

import csv
from io import StringIO

# ...

# 实例化一个StringIO来在内存中缓冲CSV
sio = StringIO()

# 实例化一个CSV写入器来写入StringIO
cw = csv.writer(sio)

# 执行查询
cursor.execute("""select * from table""")

# 根据您的数据库,您可以在循环之前使用 `cw.writerow`
# 来将列名作为第一行写入CSV。

# 循环遍历查询返回的行,将每个单元格转换为字符串后写入CSV写入器。
# 您可能需要调整 `str()` 调用以特定方式格式化日期等内容。
for row in cursor:
    cw.writerow([str(cell) for cell in row])

# 获取StringIO的内容并编码为UTF-8字节
csv_bytes = sio.getvalue().encode("utf-8")

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

You're probably looking for something like this. I elided the connection-related bits, because they're specific to your database connection.

import csv
from io import StringIO

# ...

# Instantiate a StringIO to buffer the CSV in memory to
sio = StringIO()

# Instantiate a CSV writer to write to the StringIO
cw = csv.writer(sio)

# Execute the query
cursor.execute("""select * from table""")

# Depending on your database, you could use `cw.writerow`
# before the loop to write the column names as the first line here.

# Loop over the rows returned by the query, casting each cell to a string
# before writing to the CSV writer.  You may need to adjust the `str()`
# invocation to format e.g. dates in a specific way.
for row in cursor:
    cw.writerow([str(cell) for cell in row])

# Get the StringIO's contents and encode to UTF-8 bytes
csv_bytes = sio.getvalue().encode("utf-8")

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

huangapple
  • 本文由 发表于 2023年3月7日 18:27:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75660760.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定