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

时间:2016-01-04 10:39:20

标签: 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。请帮忙 !我挣扎了两天。

1 个答案:

答案 0 :(得分:7)

TL; DR:

改变这个:

awaitConnection.done(new Action<Void>() {
            @Override
            public void run(Void obj) throws Exception {

                Log.d(TAG, "Hub Connected");
            }
        }).onError(new ErrorCallback() {
            @Override
            public void onError(Throwable error) {
                error.printStackTrace();
                Log.d(TAG, "SignalRServiceHub Cancelled");

            }
        }).onCancelled(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "SignalRServiceHub Cancelled");

            }
        });

对此:

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不适用于此类内容。此外,它应该是通过dialect注册的名称,而不是任意迭代器。但无论如何,方言在这里无法帮助你。

相反,您应该将解码后的流直接传递给csv.register_dialect()