gpt4 book ai didi

python - 在 Django 中上传和提交 csv 文件时,“str”不支持缓冲区接口(interface)

转载 作者:行者123 更新时间:2023-12-01 04:13:38 26 4
gpt4 key购买 nike

我想上传 csv 文件并将其存储在数据库中。我的Django版本是1.9和Python3.4。下面是代码。我的应用程序名称是“pft”pft/utils.py

from .models import Account
import csv
def handle_uploaded_file(file, valid_fields_method, record_creation_function):
file.seek(0)
# !importtant
# csv file must be encoded in UTF-8
sniffdialect = csv.Sniffer().sniff(file.read(10000), delimiters='\t,;')
file.seek(0)
#print sniffdialect.fieldnames
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
def account_valid_fields(field_names):
required_fields = ('species', 'x', 'y')
for field in required_fields:
if field not in field_names:
return False
return False
def create_account_in_db(dict_data):
list_data = []
result = False
rows_error = 0
for record in dict_data:
species = record['species']
x = record['x']
y = record['y']
account = models.Account(species=species,\
x=x,\
y=y)
list_data.append(account)
if list_data:
# bulk_create will create multiple object in a single query
created_accounts = models.Account.objects.bulk_create(list_data)
if len(list_data) == len(created_accounts):
result=True
else:
rows_error = len(list_data) - len(created_accounts)
return result, rows_error

模型.py

class Account(models.Model):
species=models.CharField(max_length=255)
x=models.IntegerField()
y=models.IntegerField()

last_modified = models.DateTimeField(auto_now = True)
first_created = models.DateTimeField(auto_now_add = True)

def __str__(self):
return "%s %s %s" % (self.species, self.x,self.y)

View .py

def add_multiple_accounts(request):
if request.method == 'POST':
csv_upload_form = UploadFileForm(request.POST, request.FILES)
if csv_upload_form.is_valid():
file = csv_upload_form.cleaned_data['file']
csv_result, rows_error = utils.handle_uploaded_file(file, utils.account_valid_fields, utils.create_account_in_db)
if csv_result:
message = 'Successfully imported accounts from the csv file to the database.\n'
message += 'The system is creating Active Directory Accounts using those information in the background.\n'
message += 'Please wait...'
messages.add_message(request, messages.INFO, message)
else:
message = 'There are some errors occured. Please try again.'
messages.add_message(request, messages.INFO, message)
else:
csv_upload_form = UploadFileForm()
return render_to_response('add_multiple.html', locals(), context_instance=RequestContext(request))

url.py

url(r'^csv',add_multiple_accounts),

add.mutilple.html

<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ csv_upload_form.as_p }}
<button type="submit" class="action green btn-center" name="action" value="add_csv"><span class="label">Upload</span></button>
<input type="submit" />
</form>

当我单击提交按钮时,出现上述错误。我该如何解决这个问题?

最佳答案

尝试:

file_content = bytes(file.read(10000), 'UTF-8')
sniffdialect = csv.Sniffer().sniff(file_content, delimiters='\t,;')

这是因为Python3.x中的string与python2.x中的不一样,需要用字节进行转换并编码为utf-8

关于python - 在 Django 中上传和提交 csv 文件时,“str”不支持缓冲区接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34574087/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com