2015-03-31 31 views
1

我的網頁形式如下:如何在點擊網頁表單提交時調用python s cript?

<!DOCTYPE html> 
<html> 
<head> 
<title>Form Example</title> 
<link rel="stylesheet" href="formstyle.css" type="text/css" /> 
</head> 
<body> 
<h1>Form Example</h1> 

<form action="checkpoint.py" method="POST"> 
    <input type="text" size="6" maxlength="20" name="text2" /> 
    <input type="submit" value="Go!" /> 
</form> 

</body> 
</html> 

在點擊提交時,瀏覽器會提示打開checkpoint.py文件,而不是執行它。該文件存在於相同的文件夾中。你能幫我解決我在做什麼錯嗎? 我對前端和Web開發完全陌生。

+0

您需要將您的網絡服務器配置爲正確處理對* .py文件的請求,例如,對於Apache httpd,你可以使用cgi/fastcgi或mod_wsgi。 – AChampion 2015-03-31 07:14:57

回答

0

首先你需要讓服務器運行(在我的情況下,它運行在cgi-bin \目錄下)。在這裏,你有源代碼:

from http.server import HTTPServer, CGIHTTPRequestHandler 
webdir = '.'   # where your html files and cgi-bin script directory live 
port = 8080    # default http://localhost or http://127.0.0.1 
srvraddr = ("", port) 
srvrobj = HTTPServer(srvraddr, CGIHTTPRequestHandler) 
srvrobj.serve_forever() 

然後你需要爲請求處理的腳本:當然

#!/usr/bin/python 
import cgi 
form = cgi.FieldStorage()   # parse form data 
print('Content-type: text/html\n') 
print('<title>Reply Page</title>') 
print(form) 
if not 'text2' in form: 
    print('<h1>Who are you?</h1>') 
else: 
    print('<h1>Hello <i>%s</i>!</h1>' % cgi.excape(form['text2'].value)) 

而且,HTML文件,該文件已經(記得在「行動」正確的值表單屬性)。

運行服務器(離開它運行),打開你的表格(http://localhost:8080),並將其發送 - 與正在運行的服務器然後在CMD窗口中,您應該看到http請求的一些信息 - >這意味着你的服務器正確運行並獲取請求。

編輯:此代碼在Windows + Python3上工作,但也應該在Linux上工作。

相關問題