예제 #1
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
예제 #2
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()
예제 #3
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()
예제 #4
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()