Python back-end write download file, this time there was this error
latin-1 codec cant encode characters in position 42-48:ordinal not in range256
What to do:
Check cause: Found file name has Chinese name, so cause error, encoding is LATIN-1 encoding, so we need to decode into Unicode encoded into latin-1
Look at the code first:
This code involves a Python transcoding problem, be sure to note
Filepathname = Self.get_argument ("filepathname"# Gets the file name filename = STR (filepathname.split ("/") [-1]). Strip () # Gets the file name = Filename.encode ( " Utf-8 "). Decode ("latin1"# This sentence is very important, to parse into latin-1 only OK, so that will not error
classDownfilehandler (Downbaserequesthandler): @tornado. Gen.coroutinedefGet (self, *args, * *Kwargs):ifSelf.verifyflag = = 1 andSelf.status = =0:status= 2000Try: Filepathname= Self.get_argument ("Filepathname", None) Filepathname= Mybase64.decryption (unquote (filepathname))#This is a decryption .FileName = str (Filepathname.split ("/") [-1]). Strip () Latinfilename= Filename.encode ("Utf-8"). Decode ("latin1")#This sentence is critical, to parse into latin-1 is OK, so that will not errorNewFileName = str (int (time.time ())) +"."+ Filename.split (".") [1]#The second way is to change the name of a fileSelf.set_header ("Content-type","application/x-zip-compressed") #-----< or write >-----# #Self.set_header ("Content-type", "Application/octet-stream")Self.set_header ("content-disposition","attachment; filename=%s"%latinfilename) F= Open (Filepathname,'RB') whiletrue:b= F.read (8096) if notB: Break Else: Self.write (b) Self.flush () f.close ()exceptException as E:e=Formaterrorcode (E) my_log.error (e) Status=Int (e[0]) self.write (Json.dumps (Result (Status=status))) Self.finish ()Else: Self.write (Json.dumps (Result (Status=4005)) ) self.finish ()
latin-1 codec cant encode characters in position 42-48:ordinal don't in range256 download file error