def make_imageapp(): global _setup_complete if not _setup_complete: imageapp.setup() p = imageapp.create_publisher() _setup_complete = True return quixote.get_wsgi_app()
def main(): parser = argparse.ArgumentParser() parser.add_argument("-p", "--port", type=int, default=0) parser.add_argument("-A", "--app", default="simple") args = parser.parse_args() port = args.port appname = args.app ### if appname == "simple": from app import make_app the_wsgi_app = make_app() elif appname == "imageapp": import imageapp, quixote imageapp.setup() p = imageapp.create_publisher() the_wsgi_app = quixote.get_wsgi_app() elif appname == "cookie": import cookieapp the_wsgi_app = cookieapp.wsgi_app host = socket.getfqdn() # Get local machine name if port == 0: port = random.randint(8000, 9999) httpd = make_server("", port, the_wsgi_app) print "Serving at http://%s:%d/..." % (host, port) httpd.serve_forever()
def main(): parser = argparse.ArgumentParser(description='Process server info') parser.add_argument('-A', default='image', choices=['image', 'altdemo', 'myapp', 'quotes', 'chat', 'cookie'], type=str) parser.add_argument('-p', type=int, choices=range(8000,10000), default=random.randint(8000,9999)) args = parser.parse_args() args = vars(args) if args['A'] == 'image': imageapp.setup() x = imageapp.create_publisher() s = socket.socket() # Create a socket object host = socket.getfqdn() # Get local machine name port = args['p'] s.bind((host, port)) # Bind to the port args['host'] = host print 'Starting server on', host, port print 'The Web server URL for this would be http://%s:%d/' % (host, port) s.listen(5) # Now wait for client connection. print 'Entering infinite loop; hit CTRL-C to exit' while True: # Establish connection with client. c, (client_host, client_port) = s.accept() print 'Got connection from', client_host, client_port try: handle_connection(c, args) finally: imageapp.teardown()
def main(): parser = argparse.ArgumentParser() parser.add_argument( '-A', '--runApp', help = 'Application to run (image/altdemo/myapp)' ) parser.add_argument( '-p', '--portNumb', help = 'Specified port number', type=int ) args = parser.parse_args() # Handle port input (if there) if args.portNumb: port = args.portNumb else: port = random.randint(8000, 9999) # Determine what app to create if args.runApp == 'myapp': wsgi_app = make_app() elif args.runApp == 'image': imageapp.setup() p = imageapp.create_publisher() wsgi_app = quixote.get_wsgi_app() elif args.runApp == 'altdemo': p = create_publisher() wsgi_app = quixote.get_wsgi_app() elif args.runApp == 'quotes': import quotes wsgi_app = quotes.setup() elif args.runApp == 'chat': import chat wsgi_app = chat.setup() elif args.runApp == 'cookie': import cookieapp wsgi_app = cookieapp.wsgi_app else: print 'Invalid Application...' return s = socket.socket() # Create a socket object host = socket.getfqdn() # Get local machine name s.bind((host, port)) # Bind to the port print 'Starting server on', host, port print 'The Web server URL for this would be http://%s:%d/' % (host, port) s.listen(5) # Now wait for client connection. print 'Entering infinite loop; hit CTRL-C to exit' while True: # Establish connection with client. c, (client_host, client_port) = s.accept() print 'Got connection from', client_host, client_port try: handle_connection(c, port, wsgi_app) finally: imageapp.teardown()
def main(socketmodule=None): if socketmodule is None: socketmodule = socket app, port = get_args() if app == 'myapp': s = socketmodule.socket() host = socketmodule.getfqdn() if port == 0: port = random.randint(8000, 9999) s.bind((host, port)) print 'Starting server on', host, port print 'The Web server URL for this would be http://%s:%d/' % (host, port) s.listen(5) print 'Entering infinite loop; hit CTRL-C to exit' while True: c, (client_host, client_port) = s.accept() print 'Got connection from', client_host, client_port handle_connection(c, client_port) elif app == 'image': imageapp.setup() p = imageapp.create_publisher() wsgi_app = quixote.get_wsgi_app() from wsgiref.simple_server import make_server host = socketmodule.getfqdn() if port == 0: port = random.randint(8000, 9999) httpd = make_server('', port, wsgi_app) print 'Starting server on', host, port print 'The Web server URL for this would be http://%s:%d/' % (host, port) try: httpd.serve_forever() finally: imageapp.teardown() elif app == 'altdemo': p = create_publisher() wsgi_app = quixote.get_wsgi_app() from wsgiref.simple_server import make_server host = socketmodule.getfqdn() if port == 0: port = random.randint(8000, 9999) p.is_thread_safe = True httpd = make_server('', port, wsgi_app) print 'Starting server on', host, port print 'The Web server URL for this would be http://%s:%d/' % (host, port) httpd.serve_forever() elif app in ('quotes', 'chat'): if port == 0: port = random.randint(8000, 9999) os.chdir(app) os.system("python2.7 %s-server %d" % (app, port))
def make_app(app_type): global _the_app if _the_app is None: imageapp.setup() p = None if app_type == "imageapp": p = imageapp.create_publisher() else: # app_type == "altdemoapp": p = quixote.demo.altdemo.create_publisher() p.is_thread_safe = True # hack.. _the_app = quixote.get_wsgi_app() return _the_app
def main(): parser = argparse.ArgumentParser() parser.add_argument("-A",help="What application to run") parser.add_argument("-p",help="What port to use",type=int) args = parser.parse_args() if not args.A: print "Please specify an app with -A" return -1; if args.p: port = args.p else: port = random.randint(8000, 9999) if args.A == "image": imageapp.setup() p = imageapp.create_publisher() wsgi_app = quixote.get_wsgi_app() elif args.A == "altdemo": p = quixote.demo.altdemo.create_publisher() wsgi_app = quixote.get_wsgi_app() elif args.A == "myapp": wsgi_app = make_app() elif args.A == "chat": wsgi_app = chatapp.ChatApp('./chat/html') elif args.A == "quotes": wsgi_app = quoteapp.QuotesApp('quotes/quotes.txt','./quotes/html') elif args.A == "cookie": wsgi_app = cookieapp.wsgi_app else: print "App not found" return -1; s = socket.socket() # Create a socket object host = socket.getfqdn() # Get local machine name s.bind((host, port)) # Bind to the port print 'Starting server on', host, port print 'The Web server URL for this would be http://%s:%d/' % (host, port) s.listen(5) # Now wait for client connection. print 'Entering infinite loop; hit CTRL-C to exit' while True: # Establish connection with client. c, (client_host, client_port) = s.accept() print 'Got connection from', client_host, client_port handle_connection(c,wsgi_app)
def main(): s = socket.socket() # Create a socket object. host = socket.getfqdn() # Get local machine name. parser = argparse.ArgumentParser() #creating a parser parser.add_argument("-A", choices=['image', 'altdemo', 'myapp', 'quotes', 'chat', 'cookie'], help='Choose which app you would like to run') parser.add_argument("-p", type=int, help="Choose the port you would like to run on.") args = parser.parse_args() #Check to see if a port is specified if args.p == None: port = random.randint(8000, 9999) #Creating WSGI app s.bind((host, port)) else: port = args.p s.bind((host, port)) if args.A == 'myapp': wsgi_app = make_app() elif args.A == "image": imageapp.setup() p = imageapp.create_publisher() wsgi_app = quixote.get_wsgi_app() elif args.A == "altdemo": p = create_publisher() wsgi_app = quixote.get_wsgi_app() elif args.A == "quotes": directory_path = './quotes/' wsgi_app = quotes.create_quotes_app(directory_path + 'quotes.txt', directory_path + 'html') elif args.A == "chat": wsgi_app = chat.create_chat_app('./chat/html') elif args.A == "cookie": wsgi_app = make_cookie_app() else: wsgi_app = make_app() #In the event that no argument is passed just make my_app print 'Starting server on', host, port print 'The Web server URL for this would be http://%s:%d/' % (host, port) s.listen(5) #wait for client connection print 'Entering infinite loop; hit CTRL+C to exit' while True: #Establish a connection with the client c, (client_host, client_port) = s.accept() print 'Got connection from', client_host, client_port handle_connection(c, wsgi_app) #handle connection(c, validate_app) return
def main(): parse = argparse.ArgumentParser() parse.add_argument( '-A', '--run_app', help = 'Application to run (image/altdemo/myapp)' ) parse.add_argument( '-p', '--port_numb', help = 'Port number', type=int ) args = parse.parse_args() # Take care of port handling if args.port_numb: port = args.port_numb else: port = random.randrange(8000,9999) # Running the new apps if args.run_app == "myapp": wsgi_app = create_app() elif args.run_app == "image": imageapp.setup() p = imageapp.create_publisher() wsgi_app = quixote.get_wsgi_app() elif args.run_app == "altdemo": p = imageapp.create() wsgi_app = quixote.get_wsgi_app() elif args.run_app == "chat": import chat wsgi_app == chat.setup() elif args.run_app == "cookie": wsgi_app = cookie_app.wsgi_app elif args.run_app == "quotes": import quotes wgsgi_app = quotes.setup() else: raise Exception("Invalid app.") s = socket.socket() # Create a socket object host = socket.getfqdn() # Get local machine name s.bind((host, port)) # Bind to the port print 'Starting server on', host, port print 'The Web server URL for this would be http://%s:%d/' % (host, port) s.listen(5) # Now wait for client connection. print 'Entering infinite loop; hit CTRL-C to exit' while True: # Establish connection with client. c, (client_host, client_port) = s.accept() print 'Got connection from', client_host, client_port handle_connection(c, port, wsgi_app)
def main(): parser = argparse.ArgumentParser() parser.add_argument("-A", "--app", help="please specify app", required=True) parser.add_argument("-p", "--port", type=int, help="please specify port") args = parser.parse_args() app = '' if args.port: port = args.port print args.port else: port = random.randint(8000, 9999) if args.app: app = args.app if args.app == "image": imageapp.setup() p = imageapp.create_publisher() s = socket.socket() # Create a socket object host = socket.getfqdn() # Get local machine name s.bind((host, port)) # Bind to the port print 'Starting server on', host, port print 'The Web server URL for this would be http://%s:%d/' % (host, port) s.listen(5) # Now wait for client connection. print 'Entering infinite loop; hit CTRL-C to exit' while True: print 'Waiting for a connection.' # Establish connection with client. c, (client_host, client_port) = s.accept() print 'Got connection from', client_host, client_port try: t = threading.Thread(target=handle_connection, args=(c, port, app)) t.start() print t.getName() finally: imageapp.teardown()
def make_app(): global _the_app global _selected_app if _the_app is None: if _selected_app == 'image': imageapp.setup() p = imageapp.create_publisher() _the_app = quixote.get_wsgi_app() elif _selected_app == 'altdemo': p = create_publisher() _the_app = quixote.get_wsgi_app() elif _selected_app == 'myapp': _the_app = app.make_app() elif _selected_app == 'django': sys.path.append(os.path.join(os.path.dirname(__file__), 'imageappdjango')) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "imageappdjango.imageappdjango.settings-prod") _the_app = get_wsgi_application() else: raise Exception("Invalid app selected") return _the_app
def init_app(current_app): global _app_init_complete if(current_app == MY_APP): return app.make_app() elif (current_app == QUIXOTE_ALTDEMO_APP): if not _app_init_complete: p = create_publisher() _app_init_complete = True return quixote.get_wsgi_app() elif (current_app == IMAGE_APP): if not _app_init_complete: imageapp.setup() p = imageapp.create_publisher() _app_init_complete = True return quixote.get_wsgi_app() elif (current_app == CHAT_APP): return ChatApp('./chat/html') elif (current_app == QUOTES_APP): return QuotesApp('./quotes/quotes.txt', './quotes/html') elif (current_app == COOKIE_APP): return cookieapp.wsgi_app
# Accepts one of the above three strings def choose_app(app_name): global _setup_complete if(app_name == APP_MINE): return app.make_app() elif(app_name == APP_QUIXOTE_ALTDEMO): if not _setup_complete: p = create_publisher() _setup_complete = True return quixote.get_wsgi_app() elif(app_name == APP_QUIXOTE_IMAGEAPP): if not _setup_complete: imageapp.setup() p = imageapp.create_publisher() _setup_complete = True return quixote.get_wsgi_app() elif(app_name == APP_CHAT): chat_app = chat.make() return chat_app elif(app_name == APP_QUOTES): quotes_app = quotes.make()
def make_imageapp(): imageapp.setup() p = imageapp.create_publisher() return quixote.get_wsgi_app()
def handle_connection(conn, port, app): headers = {} headers_string = '' env={} while headers_string[-4:] != '\r\n\r\n': headers_string += conn.recv(1) initLine, headerData = headers_string.split('\r\n', 1) init_list = initLine.split(' ') requestType = init_list[0] url = urlparse(init_list[1]) path = url[2] query = url[4] headers_list = headers_string.split('\r\n')[1:] for line in headerData.split('\r\n')[:-2]: key, val = line.split(': ', 1) headers[key.lower()] = val env['REQUEST_METHOD'] = 'GET' env['PATH_INFO'] = path env['QUERY_STRING'] = query env['CONTENT_TYPE'] = 'text/html' env['CONTENT_LENGTH'] = str(0) env['SCRIPT_NAME'] = '' env['SERVER_NAME'] = socket.getfqdn() env['SERVER_PORT'] = str(port) env['wsgi.version'] = (1, 0) env['wsgi.errors'] = stderr env['wsgi.multithread'] = False env['wsgi.multiprocess'] = False env['wsgi.run_once'] = False env['wsgi.url_scheme'] = 'http' env['HTTP_COOKIE'] = headers['cookie'] if 'cookie' in headers.keys() else '' def start_response(status, headers_response): conn.send('HTTP/1.0 ') conn.send(status) conn.send('\r\n') for pair in headers_response: key, header = pair conn.send(key + ': ' + header + '\r\n') conn.send('\r\n') content='' if requestType == "POST": env['REQUEST_METHOD'] = 'POST' env['CONTENT_LENGTH'] = str(headers['content-length']) try: env['CONTENT_TYPE'] = headers['content-type'] except: pass print "CONTENTLENGTH!!!" print env['CONTENT_LENGTH'] content_length = int(headers['content-length']) # !!! On Arctic, this drops data # content = conn.recv(content_length) while len(content) < content_length: content += conn.recv(1) env['wsgi.input'] = StringIO(content) if app == 'altdemo': import quixote from quixote.demo.altdemo import create_publisher try: p = create_publisher() except RuntimeError: pass wsgi = quixote.get_wsgi_app() elif app == 'image': import quixote import imageapp from imageapp import create_publisher try: p = create_publisher() imageapp.setup() except RuntimeError: pass wsgi = quixote.get_wsgi_app() elif app == "quotes": import quotes wsgi = quotes.get_wsgi_app('./quotes/quotes.txt', './quotes/html') elif app == "chat": import chat wsgi = chat.get_wsgi_app('./chat/html') elif app == "cookie": import cookieapp wsgi = cookieapp.wsgi_app else: from app import make_app wsgi = make_app() wsgi = validator(wsgi) result = wsgi(env, start_response) for data in result: conn.send(data) result.close() conn.close()
def handle_connection(conn, port, wsgi_app): """Takes a socket connection, and serves a WSGI app over it. Connection is closed when app is served.""" # Start reading in data from the connection req = conn.recv(1) count = 0 env = {} while req[-4:] != '\r\n\r\n': new = conn.recv(1) if new == '': return else: req += new # Parse the headers we've received req, data = req.split('\r\n',1) headers = {} for line in data.split('\r\n')[:-2]: key, val = line.split(': ', 1) headers[key.lower()] = val # Parse the path and related env info urlInfo = urlparse(req.split(' ', 3)[1]) env['REQUEST_METHOD'] = 'GET' env['PATH_INFO'] = urlInfo[2] env['QUERY_STRING'] = urlInfo[4] env['CONTENT_TYPE'] = 'text/html' env['CONTENT_LENGTH'] = str(0) env['SCRIPT_NAME'] = '' env['SERVER_NAME'] = socket.getfqdn() env['SERVER_PORT'] = str(port) env['wsgi.version'] = (1, 0) env['wsgi.errors'] = stderr env['wsgi.multithread'] = False env['wsgi.multiprocess'] = False env['wsgi.run_once'] = False env['wsgi.url_scheme'] = 'http' env['HTTP_COOKIE'] = headers['cookie'] if 'cookie' in headers.keys() else '' # Start response function for WSGI interface def start_response(status, response_headers): """Send the initial HTTP header, with status code and any other provided headers""" # Send HTTP status conn.send('HTTP/1.0 ') conn.send(status) conn.send('\r\n') # Send the response headers for pair in response_headers: key, header = pair conn.send(key + ': ' + header + '\r\n') conn.send('\r\n') # If we received a POST request, collect the rest of the data content = '' if req.startswith('POST '): # Set up extra env variables env['REQUEST_METHOD'] = 'POST' env['CONTENT_LENGTH'] = str(headers['content-length']) env['CONTENT_TYPE'] = headers['content-type'] # Continue receiving content up to content-length cLen = int(headers['content-length']) while len(content) < cLen: content += conn.recv(1) env['wsgi.input'] = StringIO(content) if wsgi_app == "image": from imageapp import create_publisher imageapp.setup() try: p = imageapp.create_publisher() except RuntimeError: pass wsgi_app = quixote.get_wsgi_app() elif wsgi_app == "myapp": from app import make_app wsgi_app = make_app() elif wsgi_app == "altdemo": from quixote.demo.altdemo import create_publisher try: p = create_publisher() except RuntimeError: pass wsgi_app = quixote.get_wsgi_app() elif wsgi_app == "quotes": wsgi_app = quotes.create_quotes_app('./quotes/quotes.txt', './quotes/html') elif wsgi_app == "chat": wsgi_app = chat.create_chat_app('./chat/html') ## VALIDATION ## wsgi_app = validator(wsgi_app) result = wsgi_app(env, start_response) # Serve the processed data for data in result: conn.send(data) # Close the connection result.close() conn.close()
import socket import random ### here is the code needed to create a WSGI application interface to ### a Quixote app: import quixote import imageapp imageapp.setup() p = imageapp.create_publisher() wsgi_app = quixote.get_wsgi_app() ### now that we have a WSGI app, we can run it in the WSGI reference server: from wsgiref.simple_server import make_server host = socket.getfqdn() # Get local machine name #port = random.randint(8000, 9999) port = 8000 httpd = make_server('', port, wsgi_app) print "Serving at http://%s:%d/..." % (host, port,) try: httpd.serve_forever() finally: imageapp.teardown()
def main(): """Waits for a connection, then serves a WSGI app using handle_connection""" # Create a socket object sock = socket.socket() # Get local machine name (fully qualified domain name) host = socket.getfqdn() argParser = argparse.ArgumentParser(description='Set up WSGI server') argParser.add_argument('-A', metavar='App', type=str, default=['myapp'], choices=['myapp', 'imageapp', 'altdemo', 'chat', 'quotes'], help='Select which app to run', dest='app') argParser.add_argument('-p', metavar='Port', type=int, default=-1, help='Select a port to run on', dest='p') argVals = argParser.parse_args() app = argVals.app if app == 'altdemo': ## Quixote altdemo import quixote from quixote.demo.altdemo import create_publisher p = create_publisher() wsgi_app = quixote.get_wsgi_app() ## elif app == 'imageapp': ## Image app import quixote import imageapp from imageapp import create_publisher p = create_publisher() imageapp.setup() wsgi_app = quixote.get_wsgi_app() ## elif app == 'chat': ## Chat app from chat.apps import ChatApp as make_app wsgi_app = make_app('chat/html') ## elif app == 'quotes': ## Chat app from quotes.apps import QuotesApp as make_app wsgi_app = make_app('quotes/quotes.txt', 'quotes/html') else: ## My app.py from app import make_app ## ## My app.py wsgi_app = make_app() ## # Bind to a (random) port port = argVals.p if argVals.p != -1 else random.randint(8000,9999) sock.bind((host, port)) print 'Starting server on', host, port print 'The Web server URL for this would be http://%s:%d/' % (host, port) # Now wait for client connection. sock.listen(5) print 'Entering infinite loop; hit CTRL-C to exit' # Determine which web app to serve app = argVals.app[0] while True: # Establish connection with client. conn, (client_host, client_port) = sock.accept() print 'Got connection from', client_host, client_port handle_connection(conn, port, wsgi_app)
def main(): """ Initializes the Server. Parses command line arguments (if present), then initializes the wsgi_app and starts up the server, then waits for connections """ apps = [ 'fires', 'hw6', 'imageapp', 'quixote_demo', 'quotes', 'chat', 'cookie' ] parser = argparse.ArgumentParser( description='A WSGI Server implemented for CSE491-001.', epilog='Please check the non-existent documentation for more info.', formatter_class=argparse.RawTextHelpFormatter ) # Add the '-?' alias for '--help', which I prefer to use: parser.add_argument('-?', action='help', help='Alias for --help') # Add the application argument: parser.add_argument('--app', nargs='?', dest='app', default='fires', choices=apps, help='\n'.join([ 'Which WSGI application to run.', '(default: "%(default)s" - my homework 6)', 'Alias: -A' ])) parser.add_argument('-A', nargs='?', dest='app', default='fires', choices=apps, help=argparse.SUPPRESS) # Add the port argument: parser.add_argument('--port', nargs='?', default=random.randint(8000, 9999), type=int, help='\n'.join([ 'Which port to start the server on.', '(default: random integer between 8000 and 9999)', 'Alias: -p' ])) # After that, parse the command-line arguments. args = parser.parse_args() # Create a socket object sock = socket.socket() # Get local machine name host = socket.getfqdn() if host in ('magrathea', 'Thoth'): # For testing, I don't want to have to change my url all the damn time. port = 8080 else: port = args.port # Bind to the port # TODO figure out how to immediately unbind when I'm done sock.bind((host, port)) print 'Starting server at http://%s:%d/' % (host, port) # Now wait for client connection. sock.listen(5) # get this from commandline app_to_run = args.app if app_to_run == 'quixote_demo': # quixote stuff for testing with that p = create_publisher() # p.is_thread_safe = True # hack... wsgi_app = quixote.get_wsgi_app() elif app_to_run == 'imageapp': imageapp.setup() p = imageapp.create_publisher() wsgi_app = quixote.get_wsgi_app() elif app_to_run == 'quotes': wsgi_app = QuotesApp('./quotes/quotes.txt', './quotes/html') elif app_to_run == 'chat': wsgi_app = ChatApp('./chat/html') elif app_to_run == 'cookie': wsgi_app = cookieapp.wsgi_app else: #if app_to_run == 'fires': # default wsgi_app = app.make_app() print 'Entering infinite loop; hit CTRL-C to exit' try: while True: # Establish connection with client. conn, (client_host, client_port) = sock.accept() print 'Got connection from', client_host, client_port handle_connection(conn, wsgi_app) finally: # teardown stuffs if app_to_run == 'imageapp': imageapp.teardown() sock.shutdown(2) sock.close()
def handle_connection(conn, host, port, appname): environ = {} request = conn.recv(1) # This will get all the headers while request[-4:] != "\r\n\r\n": new = conn.recv(1) if new == "": return else: request += new request, data = request.split("\r\n", 1) headers = {} for line in data.split("\r\n")[:-2]: key, val = line.split(": ", 1) headers[key.lower()] = val first_line_of_request_split = request.split("\r\n")[0].split(" ") # Path is the second element in the first line of the request # separated by whitespace. (Between GET and HTTP/1.1). GET/POST is first. http_method = first_line_of_request_split[0] environ["REQUEST_METHOD"] = first_line_of_request_split[0] try: parsed_url = urlparse.urlparse(first_line_of_request_split[1]) environ["PATH_INFO"] = parsed_url[2] env["QUERY_STRING"] = parsed_url[4] except: pass urlInfo = urlparse.urlparse(request.split(" ", 3)[1]) environ["REQUEST_METHOD"] = "GET" environ["PATH_INFO"] = urlInfo[2] environ["QUERY_STRING"] = urlInfo[4] environ["CONTENT_TYPE"] = "text/html" environ["CONTENT_LENGTH"] = str(0) environ["SCRIPT_NAME"] = "" environ["SERVER_NAME"] = socket.getfqdn() environ["SERVER_PORT"] = str(port) environ["wsgi.version"] = (1, 0) environ["wsgi.errors"] = sys.stderr environ["wsgi.multithread"] = False environ["wsgi.multiprocess"] = False environ["wsgi.run_once"] = False environ["wsgi.url_scheme"] = "http" environ["HTTP_COOKIE"] = headers["cookie"] if "cookie" in headers.keys() else "" def start_response(status, response_headers): conn.send("HTTP/1.0 ") conn.send(status) conn.send("\r\n") for pair in response_headers: key, header = pair conn.send(key + ": " + header + "\r\n") conn.send("\r\n") content = "" if request.startswith("POST "): environ["REQUEST_METHOD"] = "POST" environ["CONTENT_LENGTH"] = str(headers["content-length"]) try: environ["CONTENT_TYPE"] = headers["content-type"] except: pass cLen = int(headers["content-length"]) while len(content) < cLen: content += conn.recv(1) environ["wsgi.input"] = StringIO(content) # Create the appropriate wsgi app based on the command-line parameter if appname == "image": try: # Sometimes this gets called multiple times. Blergh. p = imageapp.create_publisher() imageapp.setup() except RuntimeError: pass wsgi_app = quixote.get_wsgi_app() elif appname == "myapp": wsgi_app = app.make_app() elif appname == "altdemo": try: p = quixote.demo.altdemo.create_publisher() except RuntimeError: pass wsgi_app = quixote.get_wsgi_app() elif appname == "quotes": # The quotes files are in the 'quotes' subdirectory directory_path = "./quotes/" wsgi_app = quotes.create_quotes_app(directory_path + "quotes.txt", directory_path + "html") elif appname == "chat": # The chat files are in the 'quotes' subdirectory wsgi_app = chat.create_chat_app("./chat/html") elif appname == "cookie": wsgi_app = cookieapp.wsgi_app result = wsgi_app(environ, start_response) try: for response in result: conn.send(response) finally: if hasattr(result, "close"): result.close() conn.close()
def main(socketmodule=None): if socketmodule is None: socketmodule = socket app, port = get_args() if app == 'myapp': s = socketmodule.socket() host = socketmodule.getfqdn() if port == 0: port = random.randint(8000, 9999) s.bind((host, port)) print 'Starting server on', host, port print 'The Web server URL for this would be http://%s:%d/' % (host, port) s.listen(5) print 'Entering infinite loop; hit CTRL-C to exit' while True: c, (client_host, client_port) = s.accept() print 'Got connection from', client_host, client_port handle_connection(c, client_port) elif app == 'image': imageapp.setup() p = imageapp.create_publisher() wsgi_app = quixote.get_wsgi_app() from wsgiref.simple_server import make_server host = socketmodule.getfqdn() if port == 0: port = random.randint(8000, 9999) httpd = make_server('', port, wsgi_app) print 'Starting server on', host, port print 'The Web server URL for this would be http://%s:%d/' % (host, port) try: httpd.serve_forever() finally: imageapp.teardown() elif app == 'altdemo': p = create_publisher() wsgi_app = quixote.get_wsgi_app() from wsgiref.simple_server import make_server host = socketmodule.getfqdn() if port == 0: port = random.randint(8000, 9999) p.is_thread_safe = True httpd = make_server('', port, wsgi_app) print 'Starting server on', host, port print 'The Web server URL for this would be http://%s:%d/' % (host, port) httpd.serve_forever() elif app == 'quotes': if port == 0: port = random.randint(8000, 9999) quotes_app = QuotesApp('quotes.txt', './quoteshtml') Server(port, quotes_app).serve_forever() elif app == 'chat': if port == 0: port = random.randint(8000, 9999) chat_app = ChatApp('./chathtml') Server(port, chat_app).serve_forever() elif app == 'cookie': if port == 0: port = random.randint(8000, 9999) import cookieapp from wsgiref.simple_server import make_server the_wsgi_app = cookieapp.wsgi_app host = socket.getfqdn() # Get local machine name httpd = make_server('', port, the_wsgi_app) print "Serving at http://%s:%d/..." % (host, port,) httpd.serve_forever()
def handle_connection(conn, host, port, appname): environ = {} request = conn.recv(1) # This will get all the headers while request[-4:] != '\r\n\r\n': new = conn.recv(1) if new == '': return else: request += new request, data = request.split('\r\n',1) headers = {} for line in data.split('\r\n')[:-2]: key, val = line.split(': ', 1) headers[key.lower()] = val first_line_of_request_split = request.split('\r\n')[0].split(' ') # Path is the second element in the first line of the request # separated by whitespace. (Between GET and HTTP/1.1). GET/POST is first. http_method = first_line_of_request_split[0] environ['REQUEST_METHOD'] = first_line_of_request_split[0] try: parsed_url = urlparse.urlparse(first_line_of_request_split[1]) environ['PATH_INFO'] = parsed_url[2] env['QUERY_STRING'] = parsed_url[4] except: pass urlInfo = urlparse.urlparse(request.split(' ', 3)[1]) environ['REQUEST_METHOD'] = 'GET' environ['PATH_INFO'] = urlInfo[2] environ['QUERY_STRING'] = urlInfo[4] environ['CONTENT_TYPE'] = 'text/html' environ['CONTENT_LENGTH'] = str(0) environ['SCRIPT_NAME'] = '' environ['SERVER_NAME'] = socket.getfqdn() environ['SERVER_PORT'] = str(port) environ['wsgi.version'] = (1, 0) environ['wsgi.errors'] = sys.stderr environ['wsgi.multithread'] = False environ['wsgi.multiprocess'] = False environ['wsgi.run_once'] = False environ['wsgi.url_scheme'] = 'http' environ['HTTP_COOKIE'] = headers['cookie'] if 'cookie' in headers.keys() else '' def start_response(status, response_headers): conn.send('HTTP/1.0 ') conn.send(status) conn.send('\r\n') for pair in response_headers: key, header = pair conn.send(key + ': ' + header + '\r\n') conn.send('\r\n') content = '' if request.startswith('POST '): environ['REQUEST_METHOD'] = 'POST' environ['CONTENT_LENGTH'] = str(headers['content-length']) try: environ['CONTENT_TYPE'] = headers['content-type'] except: pass cLen = int(headers['content-length']) while len(content) < cLen: content += conn.recv(1) environ['wsgi.input'] = StringIO(content) # Create the appropriate wsgi app based on the command-line parameter if appname == "image": try: # Sometimes this gets called multiple times. Blergh. p = imageapp.create_publisher() imageapp.setup() except RuntimeError: pass wsgi_app = quixote.get_wsgi_app() elif appname == "myapp": wsgi_app = app.make_app() elif appname == "altdemo": try: p = quixote.demo.altdemo.create_publisher() except RuntimeError: pass wsgi_app = quixote.get_wsgi_app() elif appname == "quotes": # The quotes files are in the 'quotes' subdirectory directory_path = './quotes/' wsgi_app = quotes.create_quotes_app(directory_path + 'quotes.txt', directory_path + 'html') elif appname == "chat": # The chat files are in the 'quotes' subdirectory wsgi_app = chat.create_chat_app('./chat/html') elif appname == "cookie": wsgi_app = cookieapp.wsgi_app result = wsgi_app(environ, start_response) try: for response in result: conn.send(response) finally: if hasattr(result, 'close'): result.close() conn.close()