【发布时间】:2011-07-06 05:45:37
【问题描述】:
我正在研究 WSGI,这非常困难。
我想做的事情很简单:当我点击一个链接时,我想从 python 脚本中获取字符串“hello”并在我的 HTML 段落元素中显示“hello”。
现在我制作了显示 HTML 文本的 WSGI python 脚本,即使用 WSGI python 提供页面,但没有将 Python、AJAX 和 WSGI 一起用于上述目的。
现在发生的情况是,当我单击 HTML 页面中的链接时,段落元素显示“错误”而不是“你好”。你认为我哪里错了;在 python 或 javascript 中?
我下面的python脚本正确吗?:
#!/usr/bin/env python
from wsgiref.simple_server import make_server
from cgi import parse_qs, escape
def application(environ, start_response):
return [ "hello" ]
if __name__ == '__main__':
from wsgiref.simple_server import make_server
srv = make_server('localhost', 8000, application)
srv.serve_forever()
也许是我的 Javascript 和/或 HTML 我错了?:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
<!--
function onTest( dest, params )
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById( "bb" ).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST",dest,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send( params );
}
-->
</script>
</head>
<body>
<p id="bb"> abcdef </p>
<a href="javascript:onTest('aaa.py', '')">Click it</a>
</body>
</html>
我测试它的步骤:
- 运行 wsgi 假服务器脚本
- 打开浏览器并输入http://localhost:8000/test.html
- 单击 html 页面中的链接并返回“错误”
我的文件 wsgi.py、aaa.py 和 test.html 都在同一个文件夹中。
我的服务器: 导入线程 导入浏览器 导入操作系统 从 wsgiref.simple_server 导入 make_server
FILE = 'index.html'
PORT = 8000
def test_app(environ, start_response):
if environ['REQUEST_METHOD'] == 'POST':
try:
request_body_size = int(environ['CONTENT_LENGTH'])
request_body = environ['wsgi.input'].read(request_body_size)
except (TypeError, ValueError):
request_body = "0"
try:
response_body = str(int(request_body) ** 2)
except:
response_body = "error"
status = '200 OK'
headers = [('Content-type', 'text/plain')]
start_response(status, headers)
return [response_body]
else:
f = environ['PATH_INFO'].split( "?" )[0]
f = f[1:len(f)]
response_body = open(f).read()
status = '200 OK'
headers = [('Content-type', 'text/html'), ('Content-Length', str(len(response_body)))]
start_response(status, headers)
return [response_body]
def open_browser():
"""Start a browser after waiting for half a second."""
def _open_browser():
webbrowser.open('http://localhost:%s/%s' % (PORT, FILE))
thread = threading.Timer(0.5, _open_browser)
thread.start()
def start_server():
"""Start the server."""
httpd = make_server("", PORT, test_app)
httpd.serve_forever()
if __name__ == "__main__":
open_browser()
print "Now serving on Port 8000"
start_server()
【问题讨论】: