在Ubuntu上使用XMLHttpRequest()和Apache时如何在python中接收POST数据?不使用烧瓶

问题描述 投票:0回答:2

我真的很难从客户端 JavaScript 获取数据,使用 xmlHTTPrequest POST 到一个非常简单的 python3 cgi-bin 程序。我看到很多使用 Forms 和 Flask 的例子,但我真的想尽可能简单 - 不,我不能使用 Form,因为我想对图表上的鼠标单击做出反应 - 这会创建一个“onClick”事件我抓住;在服务器端,我使用 Apache2 作为网络服务器,而不是 python 提供的网络服务器。我拥有的是:

客户端:

data.time=3600;
var xhr = new XMLHttpRequest();
  //set the py file you want to send data to --> 
  xhr.open("POST", "/cgi-bin/load.py", true);
  xhr.setRequestHeader("Content-Type", "application/json");

  ....  (here is the onreadystatechange-function - which is not important here) .....

xhr.send(JSON.stringify(data);

在服务器端:文件load.py:

#!/usr/bin/python3
import cgi, cgitb
import sys

form = cgi.FieldStorage()
print("Content-type:text/html\r\n\r\n")
print(" ")
print("Form=",form)

这会导致内部服务器错误 (500),并在 Apache2 error.log 中显示以下错误:

 File "/usr/lib/cgi-bin/load.py", line 8, in <module>
    form = cgi.FieldStorage()
  File "/usr/lib/python3.10/cgi.py", line 485, in __init__
    self.read_single()
  File "/usr/lib/python3.10/cgi.py", line 678, in read_single
    self.read_binary()
  File "/usr/lib/python3.10/cgi.py", line 700, in read_binary
    self.file.write(data)
TypeError: write() argument must be str, not bytes

我似乎明白 TypeError 是 cgi 代码内部的?那么我该怎么办呢?当我独立运行 load.py 文件(python3 load.py)时,一切都很好吗?不幸的是,我没有找到任何在没有表单的情况下使用 POST 到 python 服务器端的示例......(在客户端)。

javascript python xmlhttprequest
2个回答
0
投票
form = cgi.FieldStorage()

您已选择以新解决方案为基础 正在消失的旧技术。

https://docs.python.org/3/library/cgi.html

自版本 3.11 起已弃用,将在版本 3.13 中删除:cgi 模块已弃用(有关详细信息和替代方案,请参阅 PEP 594)。

FieldStorage 类通常可以替换为...email.message 模块或用于 POST 的multipart

https://peps.python.org/pep-0594/#cgi

CGI 被认为效率低下,因为每个传入请求都在新进程中处理。 PEP 206 将该模块视为:

“[…] 设计不佳,现在几乎不可能修复 (cgi) […]”

建议您重新评估生成可支持的解决方案的方法。 这些链接为本常见问题解答提供了有用的资源。


0
投票
如果能够实现这一点那就太好了,您是否能够找到面向未来的解决方案,或者之前评论中链接的更好的文档?

© www.soinside.com 2019 - 2024. All rights reserved.