Ejemplo n.º 1
0
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))
Ejemplo n.º 2
0
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()
Ejemplo n.º 3
0
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)
Ejemplo n.º 4
0
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
Ejemplo n.º 5
0
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)
Ejemplo n.º 6
0
def make_imageapp():
	global _setup_complete
	if not _setup_complete:
		imageapp.setup()
		p = imageapp.create_publisher()
		_setup_complete = True
	return quixote.get_wsgi_app()
Ejemplo n.º 7
0
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()
Ejemplo n.º 8
0
Archivo: web.py Proyecto: ctb/waroo
def create_publisher():
    # sets global Quixote publisher
    Publisher(TopDirectory(), display_exceptions='plain')

    # return a WSGI wrapper for the Quixote Web app.
    app = quixote.get_wsgi_app()
    app.publisher.is_thread_safe = True
    return app
Ejemplo n.º 9
0
def make_app():
    global _the_app

    if _the_app is None:
        p = create_publisher()
        _the_app = quixote.get_wsgi_app()

    return _the_app
Ejemplo n.º 10
0
    def setup(self):
        wsgi_app = None

        x = sys.stdout  # Quixote mangles sys.stdout; save.
        try:
            publisher = create_publisher()
            wsgi_app = quixote.get_wsgi_app()
        finally:
            sys.stdout = x  # restore.

        twill.add_wsgi_intercept("localhost", 80, lambda: wsgi_app, "/qx_test")
Ejemplo n.º 11
0
    def setup(self):
        wsgi_app = None

        x = sys.stdout  # Quixote mangles sys.stdout; save.
        try:
            publisher = create_publisher()
            wsgi_app = quixote.get_wsgi_app()
        finally:
            sys.stdout = x  # restore.

        twill.add_wsgi_intercept('localhost', 80, lambda: wsgi_app, '/qx_test')
Ejemplo n.º 12
0
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
Ejemplo n.º 13
0
def make_app(app_name):

  global _the_app

  if _the_app is None:
    if app_name == 'altdemo':
      p = create_publisher()
    else:
      p = imageapp.create_publisher()
    _the_app = quixote.get_wsgi_app()

  return _the_app
Ejemplo n.º 14
0
def create_publisher(coordinator, pubsubhubbub_server=None):
    push_list = []
    if pubsubhubbub_server:
        push_list.append(pubsubhubbub_server)

    qx_app = QuixoteWebApp(coordinator, push_list)

    # sets global Quixote publisher
    Publisher(qx_app, display_exceptions="plain")

    # return a WSGI wrapper for the Quixote Web app.
    return quixote.get_wsgi_app()
Ejemplo n.º 15
0
def create_publisher(coordinator, pubsubhubbub_server=None):
    push_list = []
    if pubsubhubbub_server:
        push_list.append(pubsubhubbub_server)
        
    qx_app = QuixoteWebApp(coordinator, push_list)
    
    # sets global Quixote publisher
    Publisher(qx_app, display_exceptions='plain')

    # return a WSGI wrapper for the Quixote Web app.
    return quixote.get_wsgi_app()
Ejemplo n.º 16
0
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
Ejemplo n.º 17
0
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
Ejemplo n.º 18
0

# 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()
Ejemplo n.º 19
0
def make_altdemo():
    create_publisher()
    return quixote.get_wsgi_app()
Ejemplo n.º 20
0
def make_imageapp():
    imageapp.setup()
    p = imageapp.create_publisher()
    return quixote.get_wsgi_app() 
Ejemplo n.º 21
0
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()
Ejemplo n.º 22
0
def handle_connection(conn,host,port):
    received = conn.recv(1)
    
    if not received:
        print 'Error, remote client closed connection without sending anything'
        return

    while received[-4:] != '\r\n\r\n':
        received += conn.recv(1)

    headersHTTP = map(lambda x: x.split(" "), received.split("\r\n"))
    headerDic = {}
    for header in headersHTTP:
        if header[0] != "" and len(header) >= 2:  #Dont get body from post
            headerDic[header[0].upper().replace(":", "").replace("-", "_")] = " ".join(header[1:])

    url = headersHTTP[0][1]
    path = urlparse(url)[2]
    query = urlparse(url)[4]
    mode = headersHTTP[0][0]
    environ = {}
    
    if mode == "POST":
        #Get POST body
        body = ""
        while len(body) < int(headerDic['CONTENT_LENGTH']):
            body += conn.recv(1)
        
        environ['REQUEST_METHOD'] = mode
        environ['PATH_INFO'] = path
        environ['QUERY_STRING'] = query
        environ['CONTENT_TYPE'] = headerDic['CONTENT_TYPE']
        environ['CONTENT_LENGTH'] = headerDic['CONTENT_LENGTH']
        environ['SCRIPT_NAME'] = ''
        environ['SERVER_NAME'] = host
        environ['SERVER_PORT'] = str(port)
        environ['wsgi.input'] = StringIO.StringIO(body)
        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'] = headerDic['COOKIE'] if headerDic.get('COOKIE') else ""
        
    if mode == "GET":
        environ['REQUEST_METHOD'] = mode
        environ['PATH_INFO'] = path
        environ['QUERY_STRING'] = query
        environ['CONTENT_TYPE'] = ''
        environ['SCRIPT_NAME'] = ''
        environ['CONTENT_LENGTH'] = str(0)
        environ['SERVER_NAME'] = 'localhost'
        environ['SERVER_PORT'] = str(port)
        environ['wsgi.input'] = StringIO.StringIO("")
        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'] = headerDic['COOKIE'] if headerDic.get('COOKIE') else ""
    
    
    #Select WSGI app    
    if args.myapp or args.app[0] == "myapp":
        new_app = validator(make_app())

    elif args.quixote or args.imageapp or args.app[0] == "quixote" or args.app[0] == "imageapp":
        new_app = quixote.get_wsgi_app()

    elif args.app[0] == "quotes":
        new_app = QuotesApp('./quotes/quotes.txt', './quotes/html')

    elif args.app[0] == "chat":
        new_app = ChatApp('./chat/html')

    elif args.app[0] == "cookie":
        new_app = wsgi_cookie


    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')

    result = new_app(environ, start_response)
    for data in result:
        conn.send(data)

    conn.close()
Ejemplo n.º 23
0
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)
Ejemplo n.º 24
0
def handle_connection(conn, pargs):

    # Start connection and receive data through headers
    data = conn.recv(1)
    while data[-4:] != '\r\n\r\n':
        bit = conn.recv(1)
        if bit == '':
            return
        else:
            data += bit

    # Repurpose code used earlier to parse headers into a dict
    reqc = StringIO.StringIO(data)
    reqc.readline()
    headers = {}
    while (True):
        temp = reqc.readline()
        if temp == "\r\n":
            break

        temp = temp.split("\r\n")[0].split(":", 1)
        headers[temp[0].lower()] = temp[1]

    req = data.split(" ")

    # Extra content if the type is post
    content = ''
    if data.startswith('POST '):
        # Receive the content data, based off the content length header
        while len(content) < int(headers['content-length']):
            content += conn.recv(1)

    path = urlparse.urlparse(req[1])
    # Create the environ dict for the app
    environ = {}
    environ['REQUEST_METHOD'] = req[0]
    environ['PATH_INFO'] = path.path
    environ['QUERY_STRING'] = path.query
    environ['SERVER_NAME'] = pargs['host']
    environ['SERVER_PORT'] = str(pargs['p'])
    if 'content-type' in headers:
        environ['CONTENT_TYPE'] = headers['content-type']
    if 'content-length' in headers:
        environ['CONTENT_LENGTH'] = headers['content-length']
    environ['wsgi.input'] = StringIO.StringIO(content)
    environ['wsgi.errors'] = sys.stderr
    environ['wsgi.multithread'] = 0
    environ['wsgi.multiprocess'] = 0
    environ['wsgi.run_once'] = 0
    environ['wsgi.url_scheme'] = 'http'
    environ['wsgi.version'] = (1,0)
    environ['SCRIPT_NAME'] = ''
    if 'cookie' in headers:
        environ['HTTP_COOKIE'] = headers['cookie']
    else:
        environ['HTTP_COOKIE'] = ''

    print "%s %s" %(req[0], path.path)

    def start_response(status, response_headers):
        conn.send('HTTP/1.0 %s' % status)
        conn.send('\r\n')

        for head in response_headers:
            key, value = head
            conn.send('%s: %s' % (key, value))
            conn.send('\r\n')

        conn.send('\r\n')

    if (pargs['A'] == 'altdemo'):
        _the_app = make_app()

    elif (pargs['A'] == 'quotes'):
        from quotes import apps
        _the_app = apps.QuotesApp('quotes/quotes.txt', './quotes/html')

    elif (pargs['A'] == 'chat'):
        from chat import apps
        _the_app = apps.ChatApp('./chat/html')

    elif (pargs['A'] == 'myapp'):
        _the_app = app.make_app()

    elif (pargs['A'] == 'cookie'):
        import cookieapp
        _the_app = cookieapp.wsgi_app

    else:
        _the_app = quixote.get_wsgi_app()

    #app1 = quixote.get_wsgi_app()
    result = _the_app(environ, start_response)

    for data in result:
        try:
            conn.send(data)
        except socket.error:
            break

    ##result.close()
    conn.close()
Ejemplo n.º 25
0
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()
Ejemplo n.º 26
0
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()
Ejemplo n.º 27
0
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()
Ejemplo n.º 28
0
def handle_connection(conn, port, app):
    loader = jinja2.FileSystemLoader('./templates')
    env = jinja2.Environment(loader=loader)
    print 'New connection, you\'re so popular!'

    info = conn.recv(1)

    # info is headers
    while info[-4:] != '\r\n\r\n':
        info += conn.recv(1)

    # req is either POST or GET
    req = info.split('\r\n')[0].split(' ')[0]

    # reqType is the path extracted
    reqType = info.split('\r\n')[0].split(' ')[1]
    urlInfo = urlparse.urlparse(reqType)
    reqType = urlInfo.path
    query = urlInfo.query

    cookies       = ''
    content       = '';
    contentLength = 0;
    contentType   = '';
    wsgi_input    = '';
    lineSplit     = info.split('\r\n')
    if req == 'POST':
        for s in lineSplit:
            if 'Content-Type' in s:
                contentType = s.split(' ', 1)[1]
            if 'Content-Length' in s:
                contentLength = int (s.split()[1])
        for i in range(contentLength):
            content += conn.recv(1)
        wsgi_input = content

    environ = {}
    environ['REQUEST_METHOD'] = req
    environ['PATH_INFO']      = reqType
    environ['QUERY_STRING']   = query
    environ['CONTENT_TYPE']   = contentType
    environ['CONTENT_LENGTH'] = str(contentLength)
    environ['wsgi.input']     = StringIO(wsgi_input)
    environ['SCRIPT_NAME']    = ''
    environ['SERVER_NAME']    = socket.getfqdn()
    environ['SERVER_PORT']    = str(port)
    environ['wsgi.errors']    = StringIO('blah')
    environ['wsgi.multithread'] = ''
    environ['wsgi.multiprocess'] = ''
    environ['wsgi.run_once']  = ''
    environ['wsgi.version']   = (2,0)
    environ['wsgi.url_scheme'] = 'http'
    # Splits headers on line and returns line with cookies.
    for line in lineSplit:
        if 'Cookie: ' in line:
            cookies = line.split(' ', 1)[1]
    environ['HTTP_COOKIE'] = cookies

    def start_response(status, response_headers):
        conn.send('HTTP/1.0 ')
        conn.send(status)
        conn.send('\r\n')
        for k, v in response_headers:
            conn.send("%s: %s\r\n" % (k, v))
        conn.send('\r\n')

    if app == "image":
        wsgi_app = quixote.get_wsgi_app()
    elif app == "altdemo":
        p = quixote.demo.altdemo.create_publisher()
        wsgi_app = quixote.get_wsgi_app()
    elif app == "myapp":
        wsgi_app = make_app()
    elif app == "quotes":
        wsgi_app = quotes.setup()
    elif app == "chat":
        wsgi_app = chat.setup()
    elif app == "cookie":
        wsgi_app = cookieapp.wsgi_app
    else:
        print 'no such app'
#        wsgi_app = make_app()

#    validator_app = validator(wsgi_app)

    output   = wsgi_app(environ, start_response)
#    output = validator_app(environ, start_response)
    for line in output:
        conn.send(line)
    #conn.send(output)
    """
    ret = ["%s: %s\n" % (key, value)
           for key, value in environ.iteritems()]
    print ret
    """
    conn.close()
Ejemplo n.º 29
0
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()
Ejemplo n.º 30
0
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()
Ejemplo n.º 31
0
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()
Ejemplo n.º 32
0
def create_publisher(coordinator):
    # sets global Quixote publisher
    Publisher(QuixoteWebApp(coordinator), display_exceptions="plain")

    # return a WSGI wrapper for the Quixote Web app.
    return quixote.get_wsgi_app()
Ejemplo n.º 33
0
import quixote, qx_testserver
from wsgiref.simple_server import make_server

qx_testserver.create_publisher()
wsgi_app = quixote.get_wsgi_app()

httpd = make_server('', 8000, wsgi_app)
httpd.serve_forever()