【问题标题】:Javascript/Python - click a button on a website and run a function in pythonJavascript/Python - 单击网站上的按钮并在 python 中运行函数
【发布时间】:2020-04-16 13:24:16
【问题描述】:

现在是下午 2:17,我从早上 8 点开始就一直在处理这个问题。我通常做python。我想制作一组按钮,单击按钮将在服务器上运行 python 函数。我想通过从客户端javascript向python服务器发送一个web请求来做到这一点,python服务器将接收它、解析它并运行正确的函数。我尝试过 webhooks、websockets、ajax 和手动解析 GET 和 POST 请求。我无法让它工作,似乎没有关于 python 中的 webhook 的在线信息,python websocket API 坚持你使用异步甚至不工作,我几乎不了解 ajax,但它不允许你更改端口,当我尝试手动解析请求,我得到的只是初始连接,单击按钮将不再发送。

这是我最近一次尝试客户端,获取请求解析(我想更改端口或解析标头,但我只在 python 中的套接字首次创建连接时获取数据,稍后单击按钮时我什么也得不到。)

<html>
<head>
<title>Dashboard v0.1</title>
<script>
    function send(theUrl)
    {
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open( "GET", theUrl, false);
        xmlHttp.send(null);
        return xmlHttp.responseText;
    }
</script>

<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>

</head>
<body>
    <button type="button" onclick="send("http://127.0.0.1:34000")">Test</button>
</body>
</html>

这是我最近尝试的服务器端:

from threading import *
from socket import *

server = socket(AF_INET, SOCK_STREAM)
Port = 34000

Host = ""
BufferSize = 2048
server.bind((Host, Port))
server.listen(1000)

while True:
    connection, address = server.accept()
    print("Accepted connection")

    while True:
        response = connection.recv(BufferSize).decode("utf8")
        print(str(response))

请帮忙。我只是想发送一个请求。坦率地说,我不在乎安全性,它在我的家庭网络上。我不懂javascript,这都是sn-ps的代码。

【问题讨论】:

    标签: javascript python python-3.x websocket network-programming


    【解决方案1】:

    我找到了答案!只需回复HTTP/1.1 200 OK 即可关闭浏览器。这是我的实现:

    def listen(id, server):
        while True:
            client_connection, client_address = server.accept()
            request_data = client_connection.recv(1024)
            executeCommand(id)
    
            http_response = b"""\
        HTTP/1.1 200 OK
        """
            client_connection.sendall(http_response)
            client_connection.close()
    
            print(str(id))```
    

    【讨论】:

      猜你喜欢
      • 2017-09-17
      • 2016-09-20
      • 2014-10-01
      • 2015-09-01
      • 2020-08-10
      • 1970-01-01
      • 2012-06-29
      • 2016-07-15
      相关资源
      最近更新 更多