Python3.4 处理 UTF 编码的 POST 数据
Python3.4 handling UTF encoded POST data
我正在使用 Python3.4 和 bottle web-framekwork 通过 AJAX POST 请求将文件名传递给一些 python 打开的代码文件并对其进行处理。但是,当文件名包含非英文字母时,例如韩文。由于路径错误,我无法打开文件。
如果我在 Javascript 中使用 escape()
传递它,然后在 python 代码中使用 html.unescape()
,我会得到稍微修改过的错误:
FileNotFoundError: [Errno 2] No such file or directory:
'C:\Data\[%uC9C1%uCEA0] 160123 %uBC0D%uC2A4 (%uC218%uC544)
%uC6B0%uB9AC.mp4'
如何正确处理此问题以便我可以访问非英文命名文件?
提前致谢。
你可以这样做;我测试了它,它没有那个问题:
在浏览器中(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.
# ...
我正在使用 Python3.4 和 bottle web-framekwork 通过 AJAX POST 请求将文件名传递给一些 python 打开的代码文件并对其进行处理。但是,当文件名包含非英文字母时,例如韩文。由于路径错误,我无法打开文件。
如果我在 Javascript 中使用 escape()
传递它,然后在 python 代码中使用 html.unescape()
,我会得到稍微修改过的错误:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\Data\[%uC9C1%uCEA0] 160123 %uBC0D%uC2A4 (%uC218%uC544) %uC6B0%uB9AC.mp4'
如何正确处理此问题以便我可以访问非英文命名文件?
提前致谢。
你可以这样做;我测试了它,它没有那个问题:
在浏览器中(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.
# ...