【问题标题】:Getting Attrbute error _exit_ when use "with" keyword使用“with”关键字时出现属性错误__exit__
【发布时间】:2015-06-03 07:25:10
【问题描述】:

我已通过.csv 文件发布请求,

input_file = data.get('file', None)
with input_file as datasheet:
        header = datasheet.readline()

总是在第二行出现错误。我的文件类型也是Unicode,这就是为什么它再次在第三行为readline() 给出错误

【问题讨论】:

  • data.get()返回了什么?
  • {u'file': u'C:\\sample_datasheet.csv'}

标签: python django tastypie


【解决方案1】:
>>> with "test1.html" as fp:
...    header = fp.readline()
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: __exit__
>>> 

如何使用 with 语句读取文件:

代码:

>>> with open("test1.html") as fp:
...    header = fp.readline()
... 

在进行任何处理之前检查文件是否退出。

使用操作系统模块

演示

>>> os.path.isfile("test1.html")
True
>>> os.path.isfile("nofile.html")
False
>>> 

在 API 测试中通过 post 请求将文件上传到服务器

fp = open("C:\sample_datasheet.csv", 'rb')
content = fp.read()
fp.close()

fd ={'file': "C:\sample_datasheet.csv", "content": content}
self.assertHttpOK(self.api_client.post('api of upload', format='json',\
org_id=2, content_type="multipart/form-data",\
data=fd))

并将contentdata 保存到视图中的服务器位置。

【讨论】:

  • 我试过这个,但现在给第三行 unicode 没有属性 readline() 的错误
  • 你想做什么?表示服务器上存在文件,而您在 url 中传递文件名?对吗??
  • 文件存在于我的本地机器上,我在帖子数据中传递名称@viveksable
  • 你能把 py 文件和 html 和 CSV 文件传给我吗-在我的电子邮件中(vivekbsable@gmaill.com)
  • 实际上我正在做测试,并且在上传请求数据中的文件时发生了这个错误。当我通过它在 api 端以 unicode 格式接收的文件通过发布数据时,我正在使用 .chunks() ,因此它会引发错误,因为 Unicode 对象没有属性块 @viveksable
【解决方案2】:

考虑到{u'file': u'C:\\sample_datasheet.csv'}data.get()函数返回的,你得获取文件名并打开:

data = data.get('file', None)
fname = data["file"]
with open(fname, "r") as datasheet:
        header = datasheet.readline()

【讨论】:

  • 但引发另一个错误为 AttributeError: 'unicode' object has no attribute 'chunks'。当我在做“for chunk in upload_file.chunks():”时,上传的文件是相同的 input_file @dlask
  • 我们可以在测试用例中使用tastepie @dlask通过post上传文件吗
  • 请仔细检查您正在处理的每条数据的类型。不能在需要文件对象的地方使用字典,不能在需要文件名的地方使用数字,等等。
  • 第二个答案是什么,我们可以通过tastepie @dlask 中的post 请求上传文件
  • @Sanket 我想现在该轮到你了。在代码中添加几个print 语句,查看各个变量中的内容,查看文档可以使用这些变量做什么,并找到正确的代码形式。
猜你喜欢
  • 1970-01-01
  • 2011-10-29
  • 1970-01-01
  • 2021-01-16
  • 2018-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-07
相关资源
最近更新 更多