在網頁和python程序之間進行通信的一種非常常見的方式是運行python作爲WSGI server。有效地,python程序是一個單獨的服務器,它使用GET和POST與網頁進行通信。
這種方法的一個好處是,它將Python應用程序與網頁本身解耦。您可以在開發過程中直接向測試服務器發送http請求來測試它。
Python包含一個built-in WSGI implementation,所以創建一個WSGI服務器非常簡單。這是一個非常簡單的例子:
from wsgiref.simple_server import make_server
# this will return a text response
def hello_world_app(environ, start_response):
status = '200 OK' # HTTP Status
headers = [('Content-type', 'text/plain')] # HTTP Headers
start_response(status, headers)
return ["Hello World"]
# first argument passed to the function
# is a dictionary containing CGI-style environment variables
# second argument is a function to call
# make a server and turn it on port 8000
httpd = make_server('', 8000, hello_world_app)
httpd.serve_forever()
感謝您的回覆!你能解釋一下從Javascript的一面來看這是怎麼回事?假設你上面編寫的代碼被稱爲「helloWorld.py」,並且在命令行中使用了參數「hello」,那麼你如何傳遞腳本「hello」並接收腳本的JS方面的響應? – Acoustic77
WSGI服務器只是在監聽http請求,它的返回值 - 無論它們是什麼 - 將被髮送以迴應請求。這個問題包括一些在JS中使用不同方法的例子:http://stackoverflow.com/questions/247483/http-get-request-in-javascript – theodox
我感謝你的幫助,但我仍然沒有運氣。我修改了python腳本來簡單地創建一個html頁面。所以我所需要的就是弄清楚這個javascript的一面。我只需要傳遞一個字符串並運行它。 (整個腳本,而不僅僅是一個函數,例如:$ python3 myscript.py inputString – Acoustic77