1

我正在尝试使用以下代码片段: http: //djangosnippets.org/snippets/788/来导入 CSV。

我收到以下错误:

强制转换为 Unicode:需要字符串或缓冲区,找到列表

为什么?

PS文件是从S3存储加载的,这就是为什么我有额外的CSVImport来检测它是字符串还是文件并且应该工作。

这是完整的代码:

运行导入:

from core.csv_reader import CSV
            from .csvImport import CSVImport

            csv_object = CSV(self.filepath)
            this_file = csv_object.get_data()


            new_object = CSVImport(csvfile=this_file,
                                   model=Contact,
                                   modelspy=".",
                                   mappings="1=first_name,2=mobile")

            new_object.run()

CSVImport 类:

import csv
from django.core.files.base import File


class CSV:
    def __init__(self, file=None):
        self.file = file
        if isinstance(file, str): # if the file is a string, it's a path that has to be opened
            with open(self.file, 'r') as f:
                self.data = [row for row in csv.reader(f)]
        elif isinstance(file, File): # if that's a file object, no need to open
            self.data = [row for row in csv.reader(file.read().splitlines())]
        else: # otherwise, I don't know what to do, so aaaaaaaargh!
            raise Exception("File object type unknown: %s %s" % (type(file), file,))

    def get_row_count(self):
        return len(self.data)

    def get_column_count(self):
        return len(self.data[0])

    def get_data(self, rows=1):
        return self.data


Error:

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/contacts/upload/configurator/92/

Django Version: 1.5.1
Python Version: 2.7.2
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'django.contrib.humanize',
 'django.contrib.sitemaps',
 'south',
 'userena',
 'social_auth',
 'djcelery',
 'storages',
 'endless_pagination',
 'django.contrib.flatpages',
 'django_sagepay',
 'guardian',
 'widget_tweaks',
 'badger',
 'tastypie',
 'accounts',
 'contacts',
 'sms',
 'smartpages',
 'django_sagepay',
 'unsubscribe',
 'core',
 'django_nose',
 'debug_toolbar')
Installed Middleware:
('dogslow.WatchdogMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'async_messages.middleware.AsyncMiddleware',
 'core.middleware.ssl.SSLRedirect',
 'core.middleware.account.RefreshBalance',
 'debug_toolbar.middleware.DebugToolbarMiddleware')


Traceback:
File "/Users/user/Documents/workspace/test/django-env/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  115.                         response = callback(request, *callback_args, **callback_kwargs)
File "/Users/user/Documents/workspace/test/django-env/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  25.                 return view_func(request, *args, **kwargs)
File "/Users/user/Documents/workspace/test/contacts/views.py" in upload_configurator
  201.             process_upload_Temp(upload_id=upload.id, cleaned_data=data)
File "/Users/user/Documents/workspace/test/contacts/views.py" in process_upload_Temp
  222.     upload.process(cleaned_data=cleaned_data)
File "/Users/user/Documents/workspace/test/contacts/models.py" in process
  172.         new_object = CSVImport(csvfile=open(self.filepath).read(),

Exception Type: TypeError at /contacts/upload/configurator/92/
Exception Value: coercing to Unicode: need string or buffer, FieldFile found
4

1 回答 1

2

self.data是一个列表(在CSV):

self.data = [row for row in csv.reader(f)]
self.data = [row for row in csv.reader(file.read().splitlines())]

因此this_file是一个列表:

this_file = csv_object.get_data()

因此,当您这样做时,这new_object = CSVImport(csvfile=this_file,...)似乎CSVImportcsvfile一个字符串,但您将其传递给list.

我不确切知道您要完成什么,但这似乎是错误。

希望这可以帮助!

于 2013-06-26T12:58:34.033 回答