I am taking a python course where they use BaseHTTPServer. The code they start with is here
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()
I am using python anywhere and there the only possibility to get an application onto the internet is to use an wsgi interface.
A configuration file for the wsgi interface looks like this:
import sys
path = '<path to app>'
if path not in sys.path:
sys.path.append(path)
from app import application
application could be something like this:
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 would be a string with html content.
I cannot just point to port 8080 as in the example. In order to use python anywhere I do have to interface both. I reckoned it could be possible that the wsgi is derived from BaseHTTPServer so it might be possible to interface them and to use my course on pythonanywhere.com
It is clear I have to get rid in the code in the main function and use the application function instead. But I am not exactly getting how this works. I get a callback (start_response) which I call and then I yield the content? How can I combine this with the webServerHandler class?
If this would be possible it should in theory work as well for the google app engine. I found a very complex example here where BaseHTTPServer is used but this is too complex for me yet.
Is it possible to do this and if yes could someone give me a hint how to do this and provide me with some basic start code?