django - 在 django 中上传 csv 时,迭代器应该返回字符串,而不是字节(您是否以文本模式打开文件?)

标签 django csv python-3.x

我想上传 csv 文件并存储在数据库中。当我单击提交按钮时,出现以下错误

Environment:


Request Method: POST
Request URL: http://localhost:8000/csv

Django Version: 1.9
Python Version: 3.4.3
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.gis',
 'django.contrib.admindocs',
 'world',
 'pft',
 'wms',
 'djgeojson',
 'html5',
 'geoexplorer']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
  149.                     response = self.process_exception_by_middleware(e, request)

File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
  147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Python34\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "C:\Python34\Lib\site-packages\django\bin\geodjango\pft\views.py" in add_multiple_accounts
  95.              csv_result, rows_error = utils.handle_uploaded_file(file, utils.account_valid_fields, utils.create_account_in_db)

File "C:\Python34\Lib\site-packages\django\bin\geodjango\pft\utils.py" in handle_uploaded_file
  24.     if not valid_fields_method(data.fieldnames):

File "C:\Python34\lib\csv.py" in fieldnames
  96.                 self._fieldnames = next(self.reader)

Exception Type: Error at /csv
Exception Value: iterator should return strings, not bytes (did you open the file in text mode?)

我的句柄文件上传函数在下面-utils.py

def handle_uploaded_file(file, valid_fields_method, record_creation_function):
    file.seek(0)
    sniffdialect = csv.reader(codecs.iterdecode(file, 'utf-8')
    file.seek(0)
    data = csv.DictReader(file, dialect=sniffdialect)

    if not valid_fields_method(data.fieldnames):
        return False, -1

    result, rows_error = record_creation_function(data)

    return result, rows_error

我正在使用 django 1.9 和 python 3.4。请帮忙 !这两天我很挣扎。

最佳答案

TL;博士:

更改此:

file.seek(0)
sniffdialect = csv.reader(codecs.iterdecode(file, 'utf-8')
file.seek(0)
data = csv.DictReader(file, dialect=sniffdialect)

对此:

file.seek(0)
data = csv.DictReader(codecs.iterdecode(file, 'utf-8'))

(顺便说一句,我会检查是否确实需要 seek(0) 。)

<小时/>

说明:

您已经了解您需要解码文件中的内容,这是正确的。但是,为此,您使用的是方言,这是错误的。

dialect 不适用于此类内容。另外,它应该是通过 csv.register_dialect() 注册的名称,而不是任意迭代器。但无论如何,方言在这里帮不了你。

相反,您应该将解码后的流直接传递给 DictReader

关于django - 在 django 中上传 csv 时,迭代器应该返回字符串,而不是字节(您是否以文本模式打开文件?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34589267/

相关文章:

python - 在VS Code中调试dockerized Django会导致错误 “Timed out waiting for launcher to connect”

python - 在 Django 中将通用图像字段添加到 ModelForm

python - 升级后,原始 sql 查询在 postgres 上将 json 字段作为字符串返回

python - Luhn 算法在 (I)python 中的意外表现

python-3.x - 如何在 sqlAlchemy 中使用 "Like"运算符

python-3.x - 检查列表中任意 3 个数字的总和是否等于 0 (python)

django - Backbone js 与 django 一起使用有什么优势

python-3.x - 使用 Cloud Functions 在 Cloud Storage 中创建 csv 文件

csv - 使用 Apex Data Loader 一次可以将多少条记录加载到 Salesforce 中?

python - 使用 beautifulsoup 抓取 XML 元素属性