我正在学习他们使用 BaseHTTPServer 的 python 课程。他们开始的代码在这里
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class webServerHandler(BaseHTTPRequestHandler):
def do_GET(self):
try:
if self.path.endswith("/hello"):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
message = ""
message += "<html><body>Hello!</body></html>"
self.wfile.write(message)
print message
return
except IOError:
self.send_error(404, 'File Not Found: %s' % self.path)
def main():
try:
port = 8080
server = HTTPServer(('', port), webServerHandler)
print "Web Server running on port %s" % port
server.serve_forever()
except KeyboardInterrupt:
print " ^C entered, stopping web server...."
server.socket.close()
if __name__ == '__main__':
main()
我在任何地方都在使用 python,而将应用程序放到 Internet 上的唯一可能性是使用 wsgi 接口。
wsgi 接口的配置文件如下所示:
import sys
path = '<path to app>'
if path not in sys.path:
sys.path.append(path)
from app import application
应用程序可能是这样的:
def application(environ, start_response):
if environ.get('PATH_INFO') == '/':
status = '200 OK'
content = HELLO_WORLD
else:
status = '404 NOT FOUND'
content = 'Page not found.'
response_headers = [('Content-Type', 'text/html'), ('Content-Length', str(len(content)))]
start_response(status, response_headers)
yield content.encode('utf8')
HELLO_WORLD 将是一个带有 html 内容的字符串。
我不能像示例中那样只指向端口 8080。为了在任何地方使用 python,我必须同时连接两者。我认为 wsgi 可能是从 BaseHTTPServer 派生的,因此可以连接它们并在 pythonanywhere.com 上使用我的课程
很明显,我必须摆脱 main 函数中的代码并改用 application 函数。但我并不完全了解这是如何工作的。我得到一个我调用的回调(start_response)然后我产生内容?如何将它与 webServerHandler 类结合使用?
如果这是可能的,理论上它应该也适用于谷歌应用引擎。我在这里找到了一个使用 BaseHTTPServer 的非常复杂的示例,但这对我来说太复杂了。
是否有可能做到这一点,如果是的话,有人可以给我一个提示如何做到这一点并为我提供一些基本的起始代码吗?