我在使用BaseHTTPServer的Python课程。他们下手的代码是here在Python中将BaseHttpServer连接到WSGI
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的任何地方,那里唯一可能获得的应用程序在互联网上是使用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,我必须同时接口。我估计它可能有可能是从BaseHTTPServer派生的wsgi,所以它可能可以连接它们并在pythonanywhere.com上使用我的课程。
很明显,我必须摆脱主代码中的代码,改用应用程序功能。但我并不完全明白这是如何工作的。我收到一个回调(start_response),我打电话,然后我产生内容?我怎样才能将它与webServerHandler类结合起来?
如果这将是可能的,它应该在理论上也适用于谷歌应用程序引擎。我发现了一个非常复杂的示例here,其中使用了BaseHTTPServer,但这对我来说太复杂了。
是否有可能做到这一点,如果是的话可以有人给我一个提示如何做到这一点,并为我提供一些基本的开始代码?
如果你能评论为什么downvote,那么我会改善这个问题。 –
我在查看你的问题,当你编辑它,我认为你改善了你的问题(我没有投票你顺便说一句)。另外一个建议是包含您收到的任何错误消息。 –