【问题标题】:Python3.4 handling UTF encoded POST dataPython3.4处理UTF编码的POST数据
【发布时间】:2016-02-07 11:38:17
【问题描述】:
我正在使用 Python3.4 和 bottle web-framekwork 通过 AJAX POST 请求将文件名传递给打开文件并对其进行处理的一些 python 代码。但是,当文件名包含非英文字母时,例如韩文。由于路径错误,我无法打开文件。
如果我在 Javascript 中使用 escape() 传递它,然后在 python 代码中使用 html.unescape(),我会得到稍微修改的错误:
FileNotFoundError: [Errno 2] 没有这样的文件或目录:
'C:\Data\[%uC9C1%uCEA0] 160123 %uBC0D%uC2A4 (%uC218%uC544)
%uC6B0%uB9AC.mp4'
如何正确处理此问题,以便访问非英文命名文件?
提前致谢。
【问题讨论】:
标签:
javascript
jquery
python
python-3.x
pyqt5
【解决方案1】:
你可以这样做;我测试了它,它没有这个问题:
在浏览器中(JQuery/JavaScript):
function newModule() {
var path = $("#path").val(); // Whatever value you want to be sent.
$.ajax({
url: "{% url 'modules' %}", // Handler as defined in Django URLs.
type: "POST", // Method.
dataType: "json", // Format as JSON (Default).
data: {
path: path, // Dictionary key (JSON).
csrfmiddlewaretoken:
'{{ csrf_token }}' // Unique key.
},
success: function (json) {
// On success do this.
},
error: function (xhr, errmsg, err) {
// On failure do this.
}
});
在服务器引擎(Python)中:
def handle(request):
# Post request containing the key.
if request.method == 'POST' and 'path' in request.POST.keys():
# Retrieving the value.
current_title = request.POST['path']
# You can also do |ttl = current_title.encode('utf-8')| to make sure.
# ...