繁体   English   中英

Javascript/Python - 单击网站上的按钮并在 python 中运行 function

[英]Javascript/Python - click a button on a website and run a function in python

现在是下午 2 点 17 分,我从早上 8 点开始就一直在做这件事。 我通常做 python。 我想制作一组按钮,单击按钮将在服务器上运行 python function 。 I want to do this by sending a web request from the client javascript to a python server, which will receive it, parse it, and run the correct function. 我尝试过 webhooks、websockets、ajax,以及手动解析 GET 和 POST 请求。 I can't get it to work, there seems to be nothing online about webhooks in python, python websocket API's insist you use async and don't even work, I barely understand ajax but it doesn't let you change ports, and when我尝试手动解析请求,我得到的只是初始连接,单击按钮将不再发送。

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

<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,这都是代码片段。

我找到了答案! 只需回复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))```

暂无
暂无

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

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