简体   繁体   English

使用python中的request.post发送文件名中带有Unicode字符的文件

[英]Send files with Unicode characters in filename using requests.post in python

I need to post a file using request module in python, which has unicode characters in filename. 我需要使用python中的请求模块发布文件,该文件名中包含unicode字符。

I am using below code: 我正在使用以下代码:

url = "https://demo.php"
headers = {'Accept': 'application/vnd.ve.v1.0+json','API': 'aasadadas'}
file_up = {'filename': open(file_name, 'rb')}
upload_file_rest =requests.post(url,files=file_up,headers=headers,verify=False)

Using the above code and when passing the filename as "指事字.exe", I am getting below exception: 使用上面的代码并将文件名传递为“指事字.exe”时,出现以下异常:

'ascii' codec can't decode byte 0xc2 in position 26: ordinal not in range(128)

Any help is really appreciated. 任何帮助都非常感谢。

PS: I had already tried below code, and it doesn't worked for me: PS:我已经尝试过以下代码,但对我来说不起作用:

file_up = {'filename': open(file_name.encode('utf-8'), 'rb')}

Alas, you didn't post a stack trace or which version of Python you're using, so here is some guessword involved. las,您没有发布堆栈跟踪或使用的是哪个版本的Python,因此这里涉及一些猜测单词。 My first assumption is that the exception comes from the line which tries to open the file, not from within the requests module. 我的第一个假设是,异常来自尝试打开文件的行,而不是来自请求模块内部。

Make sure you declare the encoding of your python file in the first line: 确保在第一行中声明python文件的编码:

# -*- coding: utf-8 -*-

Use unicode constants, or make sure your strings are unicode: 使用unicode常量,或确保您的字符串是unicode:

filename = u"指事字.txt"

After that, it should be possible to open the file. 之后,应该可以打开文件。 This snippet works on my computer (Macbook, Python 2.7.10): 此代码段可在我的计算机上运行(Macbook,Python 2.7.10):

filename = u"指事字.txt"
f = open(filename, "rb")
data = f.read()
print u"%d bytes in %s" % (len(data), filename)

...I first created a file named 指事字.txt in the current directory, with some lines of text in it. ...我首先在当前目录中创建了一个名为指事字.txt的文件,其中包含一些文本行。

Theres a REALLY good explanation that if you read it will give you alot of understanding. 有一个非常好的解释,如果您阅读它,将会带给您很多理解。 It looks long but its really not and well worth the read: http://nedbatchelder.com/text/unipain/unipain.html#1 它看起来很长,但确实不值得一读: http : //nedbatchelder.com/text/unipain/unipain.html#1

But, encode converts a unicode object to a string object. 但是,encode将unicode对象转换为字符串对象。 But here you have invoked it on a string object. 但是在这里,您已经在字符串对象上调用了它。 So python has to convert the string to a unicode object first. 因此,python必须首先将字符串转换为unicode对象。 So it does the equivalent of 所以它相当于

"指事字".decode().encode('utf-8')

But the decode fails because the string isn't valid ascii. 但是解码失败,因为该字符串不是有效的ascii。 That's why you get a complaint about not being able to decode. 这就是为什么您会抱怨无法解码的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM