2015-06-20 52 views
2

我试图通过GET请求在猎鹰中发送CSV。我不知道从哪里开始。通过Falcon在身体中发送CSV

下面是我的代码:

class LogCSV(object): 
"""CSV generator. 

This class responds to GET methods. 
""" 
def on_get(self, req, resp): 
    """Generates CSV for log.""" 

    mylist = [ 
     'one','two','three' 
    ] 

    myfile = open("testlogcsv.csv", 'w') 
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL) 
    wr.writerow(mylist) 

    resp.status = falcon.HTTP_200 
    resp.content_type = 'text/csv' 
    resp.body = wr 

我不想spoonfeeding,请让我知道我应该读/表来帮助解决这个问题是什么。 谢谢

回答

1

您应该使用Response.stream属性。在返回之前,它必须设置为类文件对象(带有read()方法的对象)。

所以首先,你应该写你的CSV到这个对象,然后把它给猎鹰。你的情况:

resp.content_type = 'text/csv' 
# Move the file pointer to the beginning 
myfile.seek(0) 
resp.stream = myfile 

记住文件指针移动到使用seek(0)开始,所以猎鹰可以读取它。

如果您的文件是短暂的并且足够小以存储在内存中,则可以使用内存文件(如BytesIO)而不是普通文件。它的行为与普通文件相似,但从不写入文件系统。

myfile = BytesIO() 
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL) 

... 

resp.content_type = 'text/csv' 
# Move the file pointer to the beginning 
myfile.seek(0) 
resp.stream = myfile