“ascii”编解码器无法编码。。。上载csv fi时

2024-10-02 14:18:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类上传我的csv文件假期到我的完整日历。看起来像这样:

class UploadVacationsView(APIView):
    def put(self, request, *args, **kwargs):
        try:
            # check file type
            mime = MimeTypes()
            url = urllib.pathname2url(request.FILES['file']._name)
            mime_type = mime.guess_type(url)
            if 'text/csv' not in mime_type:
                raise APIException(code=400, detail='File type must be CSV')
            vacations_list =[]
            csv_file = StringIO(request.data.get('file', None).read().decode('utf-8'))
            user_tz = pytz.timezone(request.user.common_settings.time_zone)
            schedule_file = ScheduleFile.objects.create(user=request.user)
            instance_hebcal = HebcalService()
            events = instance_hebcal.process_csv(csv_file, user_tz)
        ...

在另一个类中,我有一个可以处理csv文件的方法:

^{pr2}$

在处理英语假日的名字时一切正常,但是当我遇到希伯来语的名字时,它会出错:

Traceback (most recent call last):
  File "/home/stas/work/vacation/vmode/apps/marketplaces/base/api/views.py", line 47, in put
    events = instance_hebcal.process_csv(csv_file, user_tz)
  File "/home/stas/work/vacation/vmode/apps/marketplaces/base/services/hebcal.py", line 106, in process_csv
    for row in list(csv_input)[1:]:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 19-23: ordinal not in range(128)

我读过关于将所有字符串都转换成unicode,但不明白它从哪里得到默认的ASCII编码,如何处理它并用holiday_name从csv文件保存字符串?在


Tags: 文件csvinstanceinurlputrequesttype