我在使用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,那麼我會改善這個問題。 –
我在查看你的問題,當你編輯它,我認爲你改善了你的問題(我沒有投票你順便說一句)。另外一個建議是包含您收到的任何錯誤消息。 –