[英]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.