Exemple #1
0
 def do_GET(self):
    # file request?
    try:
       
       # which pieces were requested?
       if True or os.path.dirname( self.path.strip() ) in self.server.available_files:
          if self.path.endswith("done"):
             # receiver is done with this file
             #del self.server.available_files[ os.path.dirname( self.path.strip() ) ]
             self.send_response( 200 )
          
          else:
             # file has been made available
             SimpleHTTPRequestHandler.do_GET(self)
          
          return
       
       else:
          self.send_response(404)    # nothing to send
          return
    
    except Exception, inst:
       iftlog.exception( "Could not fully transmit " + self.path, inst)
       self.send_response(404)
       return
Exemple #2
0
 def do_GET(self):
     """Serve a GET request."""
     #print ' '
     #print '==================================================='
     #print 'HTTP Request GET >>> %s' % self.path
     PrintD(self, 'do_GET', {'Request':self.path})
     PrintD(self, 'do_GET', {'IP address':'(%s %s)' % self.client_address})
     
     reqeust = None
     try:            
         reqeust = self.__ParseServiceRequest(self.path)
     except:
         PrintD(self, 'do_GET', {'Failed to parse request':None}, 1)
         
     if (reqeust != None):
         result = False
         data = None
         
         try:
             result, data = self.OnReqService(reqeust) 
             
             if (result == True and data != None):              
                 self.__CreateResponse(data)
             else:
                 SimpleHTTPRequestHandler.do_GET(self)
                 #self.send_error(405, "Method Not Allowed")
             
         except Exception as e:
             PrintD(self, 'do_GET', {'OnReqService Problem':e}, 2)      
                 
     else:
         f = self.send_head()
         if f:
             self.copyfile(f, self.wfile)
             f.close()
Exemple #3
0
 def do_GET(self):
     try:
         print("-> GET" + str(self.__dict__))
         SimpleHTTPRequestHandler.do_GET(self)
     except:
         print("Unexpected error:" + str(sys.exc_info()[0]))
         raise
Exemple #4
0
  def do_GET(self):
    """ Overrides SimpleHTTPRequestHandler.do_GET() to handle
        PyBBIO function calls. """
    url = self.raw_requestline.split(' ')[1]
    if ('?' in url):
      # We've received a request for a PyBBIO function call,
      # parse out parameters:
      url = url.split('?')[1]
      params = urlparse.parse_qs(url)
      function_id = params['function_id'][0]

      # This should be a key in the FUNCTION_STRINGS dictionary: 
      if (function_id in FUNCTION_STRINGS):
        function = FUNCTION_STRINGS[function_id]

        if ("entry_text" in params):
          # This is a request from a text entry, so we also need to
          # parse out the text to be passed to the function:
          text = params['entry_text'][0]
          if (text == " "):
            # An empty text box is converted into a space character
            # by the Javascript, because otherwise the parsed url
            # would not have an entry_text param and we'd get errors
            # trying to call the function; convert it back:
            text = "" 
          # If we inserted the text into the function string and 
          # evaluated it at this point, the text received would be 
          # evaluated by Python, which we really don't want. If we
          # put it in an extra set of quotes it will evaluate to a 
          # string correctly: 
          text = "'%s'" % text
          function = function % (text)

        # Evaluate the function string and capture the return value
        # in a string (which will be an empty string if function has 
        # no return value):
        response = str(eval(function))

      else:
        # The function id is not in the dictionary. This happens if
        # the server has restarted, which generates new function ids, 
        # and the page has not been refreshed.
        response = "*Refresh page*"

      # Send the HTTP headers:
      self.send_response(200)
      self.send_header('Content-Type', 'text/html')
      # Our length is simply the length of our function return value:
      self.send_header("Content-length", len(response))
      self.send_header('Server', 'PyBBIO Server')
      self.end_headers()

      # And finally we write the response:
      self.wfile.write(response)
      return

    # If we get here there's no function id in the request, which
    # means it's a normal page request; let SimpleHTTPRequestHandler
    # handle it the standard way:
    SimpleHTTPRequestHandler.do_GET(self)
Exemple #5
0
 def do_GET(self, method="GET"):
     self.wfile = FileWrapper(self.wfile)
     SimpleHTTPRequestHandler.do_GET(self)
     
     print ""
     print self._heading("HTTP Response")
     print self.wfile
Exemple #6
0
 def do_GET(s):
     job = re.compile('^/jobs/[0-9]+$')
     joblist = re.compile('^/jobs/?$')
     if (s.path == '/stats/heap' and 'guppy' in sys.modules):
         s.send_response(200)
         s.send_header('Content-Type:', 'text/plain')
         s.end_headers()
         s.wfile.write(hpy().heap())
     elif job.match(s.path):
         s.send_response(200)
         s.send_header('Content-Type:', 'application/json')
         s.end_headers()
         id = int(s.path.split('/')[2])
         result = dict()
         result['command'] = s.server.hbq.commands[id].args
         result['status'] = s.server.hbq.commands[id].status
         result['stdout'] = s.server.hbq.commands[id].stdout
         s.wfile.write(json.dumps(result))
     elif joblist.match(s.path):
         s.send_response(200)
         s.send_header('Content-Type:', 'application/json')
         s.end_headers()
         result = dict()
         for i, cmd in enumerate([[x.args, x.status]
                                 for x in s.server.hbq.commands]):
             result[i] = dict(command=" ".join(cmd[0]), status=cmd[1])
         s.wfile.write(json.dumps(result))
     else:
         SimpleHTTPRequestHandler.do_GET(s)
Exemple #7
0
 def do_GET(self):
     try:
         global TICKET
         global MASTER_ADRESS
         if self.path == "/write":
             answer = "KO" if TICKET < datetime.now() else "OK"
             self.send_response(200)
             self.send_header("Content-type", "text/html")
             self.end_headers()
             self.wfile.write(answer)
                    #         '<br />TICKET : ' + TICKET.strftime("%d/%m/%y %H:%M") + 
                     #        '<br />now : ' + datetime.now().strftime("%d/%m/%y %H:%M")) 
             #print 'GET : ' + TICKET.strftime("%d/%m/%y %H:%M")
         elif self.path == "/set-new-ticket":    
             referer_url = self.headers.getheader('referer')
             print referer_url
             print MASTER_ADRESS
             if referer_url == MASTER_ADRESS:
                 TICKET = datetime.now() + TICKET_LIVE_TIME
                 self.send_response(200)
                 self.send_header("Content-type", "text/html")
                 self.end_headers()
             else:
                 self.send_error(404,"File Not Found: %s" % self.path)
         else:                 
             SimpleHTTPRequestHandler.do_GET(self)
     except IOError:
         self.send_error(404,"File Not Found: %s" % self.path)
 def do_GET(self):
     if '.ico' in self.path or '.png' in self.path:
         SimpleHTTPRequestHandler.do_GET(self)
     else:
         self._writeheaders()
         with open("BASEHTML.html",'r') as f:
             self.wfile.write(f.read().decode('utf-8').replace('twitterid',TwitterID).encode('utf-8'))
Exemple #9
0
 def do_GET(self):
     if is_proxied(self.path):
         self.do_proxied()
     elif self.path == "/config.js":
         self.do_config_js()
     else:
         SimpleHTTPRequestHandler.do_GET(self)
Exemple #10
0
 def do_GET(self): 
   if len(self.path.split('?',1))>1:
     arg=self.path.split('?',1)[1]
     args=arg.split('&')
     cmd=args[0].split('=',1)
     print "arg=%s args=%s cmd=%s" % (arg, args, cmd)
     if args[0]=='lastsnap':
       self.serve_file('/tmp/motion/lastsnap.jpg');
     elif cmd[0]=='cmd':
       ret=("executing "+cmd[1])
       fnc=({ #http://stackoverflow.com/a/60211/781312
       'serverStop': self.serverStop
       ,'serverStart': self.serverStart
       ,'cleanHistory': self.cleanHistory
       }[cmd[1]])
       ret+=fnc()
       self.serve_content(ret)
     else: 
       data=arg
       self.send_response(200)
       self.send_header("Content-Length", len(data))
       self.send_header("Last-Modified", self.date_time_string())
       self.end_headers()
       self.wfile.write(data);
   # except Exception, e:
   else:
     print self.path
     SimpleHTTPRequestHandler.do_GET(self)
 def do_GET(self):
     if self.headers.get("Upgrade", None) == "websocket":
         WebSocketHandler(self, lambda msg: self.__handle_websocket_message(msg)).run()
         #This handler is in websocket mode now.
         #do_GET only returns after client close or socket error.
     else:
         SimpleHTTPRequestHandler.do_GET(self)
Exemple #12
0
 def do_GET(self):
     parsed_path = urlparse.urlparse(self.path)
     if parsed_path.path.startswith("/echo"):
         message = '\n'.join([
             'CLIENT VALUES:',
             'client_address=%s (%s)' % (self.client_address,
                 self.address_string()),
             'command=%s' % self.command,
             'path=%s' % self.path,
             'real path=%s' % parsed_path.path,
             'query=%s' % parsed_path.query,
             'request_version=%s' % self.request_version,
             '',
             'HEADERS:',
             '%s' % self.headers,
             ])
         self.send_response(200)
         self.end_headers()
         self.wfile.write(message)
     elif parsed_path.path.startswith("/redirect"):
        self.send_response(301)
        self.send_header('Location', "/echo")
        self.end_headers()
     else:
         SimpleHTTPRequestHandler.do_GET(self)
         
     return
 def do_GET(self):
     if not self._isAuthorized():
         self.send_response(401, 'Unauthorized')
         self.send_header('WWW-Authenticate', 'Basic realm="Test"')
         self.end_headers()
         return
     SimpleHTTPRequestHandler.do_GET(self)
Exemple #14
0
    def do_GET(self):
        if self.path.startswith('/assets'):	
            with FileLock(common.LOCK_FILE):
                SimpleHTTPRequestHandler.do_GET(self)
        elif self.path.startswith('/addrag'):
            self.sendOk()
        elif self.path == '/statsrotate':
            statsrotate()
            self.sendOk()
        elif self.path.startswith('/log'):
            qs = self.path[self.path.index('?')+1:]
            parsed = parse_qs(qs)
            parsed['ts'] = str(int(time.time()))
            # Remove cachebuster
	    if '_' in parsed:
                del parsed['_']
            try:
                fields_to_write = [
                                   BOARD_ID,
                                   parsed['ts'], 
                                   parsed['id'][0],
                                   parsed['event'][0],
                                   parsed['state'][0]
                                   ]
            except Exception, e:
                print "Oops", e
                self.sendResponse("Stuff missing", 400)
                return
            line = ','.join(fields_to_write)
            with stats_lock:
                main_stats.write(line)
                main_stats.write("\n")
                main_stats.flush()
            self.sendOk()
	def do_GET(self):
		if(VALID_FILE_REGEX.search(self.path) != None or self.path == "/"):
			self.path = FILE_PATH+self.path
			SimpleHTTPRequestHandler.do_GET(self)
		else:
			self.send_response(404)
			self.end_headers()
Exemple #16
0
 def do_GET(self):
     # run the build script before every pageload
     if self.path.endswith(".html"):
         print "regen for", self.path
         sys.stdout, _out = file("/dev/null", "w"), sys.stdout
         build()
         sys.stdout = _out
     Handler.do_GET(self)
Exemple #17
0
 def do_GET(self, *args, **kwargs):
     path = self.path
     reobj = re.search(r'/cdict/(.*)', path)
     if reobj:
         print reobj.group(1)
         self.wfile.write(cdic_proxy(reobj.group(1)))
     else:
         HTTPHandler.do_GET(self, *args, **kwargs)
 def do_GET(self):
     """Serve a GET request."""
     if not self.allow_path():
         self.send_error(403)
     elif self.is_brat():
         self.run_brat_direct()
     else:
         SimpleHTTPRequestHandler.do_GET(self)
Exemple #19
0
 def do_GET(self):
     """ Handle http requests to serve html/image files only """
     print self.path, self.translate_path(self.path)
     permitted_extensions = ['.html','.png','.svg','.jpg', '.js']
     if not os.path.splitext(self.path)[1] in permitted_extensions:
         self.send_error(404, 'File Not Found/Allowed')
     else:
         SimpleHTTPRequestHandler.do_GET(self)
Exemple #20
0
    def do_GET(self):
        dict_by_path = {
            "/pasteboard.html": {
                "PasteboardShare": True,
                "PasteboardShare_details": "text",
                "TextShare_details": "text",
                "PicturesShare_details": "0 albums",
                "show_link_text": True,
                "show_link_pictures": True,
                "is_shared": True,
            },
            "/text.html": {
                "TextShare": True,
                "TextShare_details": "text",
                "PasteboardShare_details": "text",
                "TextShare_details": "text",
                "PicturesShare_details": "0 albums",
                "show_link_pasteboard": True,
                "show_link_pictures": True,
                "is_shared": True,
            },
            "/pictures.html": {
                "PicturesShare": True,
                "PasteboardShare_details": "text",
                "TextShare_details": "text",
                "PicturesShare_details": "0 albums",
                "show_link_text": True,
                "show_link_pasteboard": True,
                "is_shared": True,
                "album_list_html_block": self.album_list_html_block(),
            },
            "/album.html": {
                "AlbumShare": True,
                "PasteboardShare_details": "text",
                "TextShare_details": "text",
                "PicturesShare_details": "0 albums",
                "show_link_text": True,
                "show_link_pasteboard": True,
                "show_link_pictures": True,
                "is_shared": True,
                "album_name": "My Photos",
                "number_of_pictures": 15,
                "pictures_html_block": self.pictures_html_block(),
            },
        }

        path = self.path
        if path == "/" or path == "/index.html":
            path = "/pasteboard.html"

        if path in dict_by_path:
            self.send_response(200)
            self.send_header("Content-type", "text/html")
            self.end_headers()
            sys.stdout = self.wfile
            print self.preprocessor.process_tpl_name_with_dict("index.html", dict_by_path[path])
        else:
            SimpleHTTPRequestHandler.do_GET(self)
  def do_GET(self):
    """ Overrides SimpleHTTPRequestHandler.do_GET() to handle
        PyBBIO function calls. """
    url = self.raw_requestline.split(' ')[1]
    if ('?' in url):
      # We've received a request for a PyBBIO function call,
      # parse out parameters:
      url = url.split('?')[1]
      params = urlparse.parse_qs(url)
      function_id = params['function_id'][0]
      
      function = FUNCTIONS.get(function_id)
      if (function):
        if ("entry_text" in params):
          # This is a request from a text entry, so we also need to
          # parse out the text to be passed to the function:
          text = params['entry_text'][0]
          if (text == " "):
            # An empty text box is converted into a space character
            # by the Javascript, because otherwise the parsed url
            # would not have an entry_text param and we'd get errors
            # trying to call the function; convert it back:
            text = "" 

          response = str(function(text))
	
	elif ("bowl" in params):
	  spin = '%s' %  params['spin'][0]
	  speed = '%s' % params['speed'][0]
	  pitchspot = '%s' % params['pitchspot'][0]
          response = str(function(spin,speed,pitchspot))

        else:
          # The function takes no arguments, just call it.
          response = str(function())

      else:
        # The function id is not in the dictionary. This happens if
        # the server has restarted, which generates new function ids, 
        # and the page has not been refreshed.
        response = "*Refresh page*"

      # Send the HTTP headers:
      self.send_response(200)
      self.send_header('Content-Type', 'text/html')
      # Our length is simply the length of our function return value:
      self.send_header("Content-length", len(response))
      self.send_header('Server', 'PyBBIO Server')
      self.end_headers()

      # And finally we write the response:
      self.wfile.write(response)
      return

    # If we get here there's no function id in the request, which
    # means it's a normal page request; let SimpleHTTPRequestHandler
    # handle it the standard way:
    SimpleHTTPRequestHandler.do_GET(self)
Exemple #22
0
 def do_GET(self):
   if self.path.find('.jd') != -1:
     if self.path.find('?') != -1:
       self.path, self.requete = self.path.split('?', 1)
     else:
       self.requete = ''
     self.reponse()
   else:
     SimpleHTTPRequestHandler.do_GET(self)
Exemple #23
0
 def do_GET(self):
     if self.path.startswith('/ajax/'):
         self.send_response(200);
         self.send_header("Content-Type", "text/html")
         self.send_header('Connection', 'close')
         self.end_headers()
         self.wfile.write(tmp)
     else:
         SimpleHTTPRequestHandler.do_GET(self)
Exemple #24
0
 def do_GET(self):
     pieces = urlparse.urlparse(self.path)
     if (re.match('^/chat$', pieces.path,re.IGNORECASE)):
         self.chat(urlparse.parse_qs(pieces.query))
         return
     if (re.match('^/chat/history$', pieces.path,re.IGNORECASE)):
         self.history()
         return
     SimpleHTTPRequestHandler.do_GET(self)
Exemple #25
0
    def do_GET(self):
        real_path = urllib.unquote(self.path)
        real_path = unicode(real_path, 'utf8')

        (real_path, sep, param_text) = real_path.partition('?')
        self.params = {}
        for p in param_text.split('&'):
            (key, sep, value) = p.partition('=')
            self.params[key] = value

        # Wiki requests return article contents or redirect to Wikipedia.
        m = re.match(r'^/wiki/(.+)$', real_path)
        if m:
            self.send_article(m.group(1))
            return

        # Search requests return search results.
        m = re.match(r'^/search$', real_path)
        if m:
            self.send_searchresult(self.params.get('q', ''))
            return

        # Image requests are handled locally or are referenced from Wikipedia.
        # matches /es_PE/images/, /en_US/images/ etc
        m = re.match(r'^/\w*/images/(.+)$', real_path)
        if m:
            self.send_image(real_path)
            return

        # Svg icons in the home are a special case to apply user colors
        m = re.match(r'^/static/svg/(.*)$', real_path)
        if m:
            self.send_svg_icon(real_path)
            return

        # Static requests handed off to SimpleHTTPServer.
        m = re.match(r'^/(static|generated)/(.*)$', real_path)
        if m:
            SimpleHTTPRequestHandler.do_GET(self)
            return

        # Handle link validation requests
        m = re.match(r'^/links/(.*)$', real_path)
        if m:
            self.send_links(m.group(1))
            return

        # Feedback links.
        m = re.match(r'^/(report|render)$', real_path)
        if m:
            self.handle_feedback(m.group(1), self.params.get('q', ''))
            return

        # Any other request redirects to the index page.
        self.send_response(301)
        self.send_header("Location", "/static/")
        self.end_headers()
Exemple #26
0
    def do_GET( self ):
        if self.path == '/':
            self.path = '/index.html'

        if( self.pageExists() ):
            self.sendPage()
        elif self.path.endswith( 'style.css' ):
            self.sendCss()
        else:
            SimpleHTTPRequestHandler.do_GET( self )
Exemple #27
0
 def do_GET(self):
     if self.server.auth and not self.checkAuthentication():
         return
     if self.headers.get("Upgrade", None) == "websocket":
         self._handshake()
         #This handler is in websocket mode now.
         #do_GET only returns after client close or socket error.
         self._read_messages()
     else:
         SimpleHTTPRequestHandler.do_GET(self)
Exemple #28
0
  def do_GET(self):
	path, args = self.parse_req()
	if not hasattr(self, path):
		SimpleHTTPRequestHandler.do_GET(self)
		return
	try:
		res = eval("self." + path, {"self":self}, {})(**args)
	except Exception, e:
		self.error(e.message)
		return
Exemple #29
0
 def send_image(self, path):
     if os.path.exists(path.encode("utf8")[1:]):
         # If image exists locally, serve it as normal.
         SimpleHTTPRequestHandler.do_GET(self)
     else:
         # If not, redirect to wikimedia.
         redirect_url = "http://upload.wikimedia.org/wikipedia/commons/%s" % path.encode("utf8")
         self.send_response(301)
         self.send_header("Location", redirect_url.encode("utf8"))
         self.end_headers()
Exemple #30
0
 def do_GET(self):
     print("> HTTP received " + self.path)
     if(self.path == "/exit"):
         self.send_response(204)
         cv.acquire()
         cv.done = True
         cv.notify()
         cv.release()
     else:
         SimpleHTTPRequestHandler.do_GET(self)
Exemple #31
0
 def do_GET(self):
     if self.path.endswith("/") or self.path.endswith(".html"):
         self.log_message("running make.py")
         call("./make.py", shell=True)
     SimpleHTTPRequestHandler.do_GET(self)
Exemple #32
0
 def do_GET(self):
     self.path = self.path.replace(self.base_url, b'/')
     
     SimpleHTTPRequestHandler.do_GET(self)
Exemple #33
0
 def do_GET(self):
     print(str(self.headers), "in thread =",
           threading.currentThread().getName())
     #delegate to parent
     SimpleHTTPRequestHandler.do_GET(self)
     return
Exemple #34
0
 def do_GET(self):
     if self.path in ['/getstarted', '/faq', '/addingupdating', '/searching']:
         self.path = '/'
     return SimpleHTTPRequestHandler.do_GET(self)
Exemple #35
0
 def do_GET_HTTP(self):
     """Override this handler."""
     SimpleHTTPRequestHandler.do_GET(self)
     pass
 def do_GET(self):
     if self.path == '/':
         index_page.run()
     return SimpleHTTPRequestHandler.do_GET(self)
 def do_GET(self):
     SimpleHTTPRequestHandler.do_GET(self)
     self.delete_temp_files()
Exemple #38
0
    def do_GET(self):
        """
        Handles the browser access (GET requests).
        """

        auth_session = self.__check_session_cookie()
        LOG.debug("%s:%s -- [%s] GET %s", self.client_address[0],
                  str(self.client_address[1]),
                  auth_session.user if auth_session else 'Anonymous',
                  self.path)

        if auth_session is not None:
            self.auth_token = auth_session.token

        product_endpoint, path = routing.split_client_GET_request(self.path)

        if self.server.manager.is_enabled and not auth_session \
                and routing.is_protected_GET_entrypoint(path):
            # If necessary, prompt the user for authentication.
            returnto = '?returnto=' + urllib.quote_plus(self.path.lstrip('/'))\
                if self.path != '/' else ''

            self.send_response(307)  # 307 Temporary Redirect
            self.send_header('Location', '/login.html' + returnto)
            self.send_header('Connection', 'close')
            self.end_headers()
            self.wfile.write('')
            return

        if product_endpoint is not None and product_endpoint != '':
            # Route the user if there is a product endpoint in the request.

            product = self.server.get_product(product_endpoint)
            if not product:
                # Give an error if the user tries to access an invalid product.
                LOG.info("Product endpoint '{0}' does not exist."
                         .format(product_endpoint))
                self.send_error(
                    404,
                    "The product {0} does not exist."
                    .format(product_endpoint))
                return

            if product:
                # Try to reconnect in these cases.
                # Do not try to reconnect if there is a schema mismatch.
                reconnect_cases = [DBStatus.FAILED_TO_CONNECT,
                                   DBStatus.MISSING,
                                   DBStatus.SCHEMA_INIT_ERROR]
                # If the product is not connected, try reconnecting...
                if product.db_status in reconnect_cases:
                    LOG.error("Request's product '{0}' is not connected! "
                              "Attempting reconnect..."
                              .format(product_endpoint))
                    product.connect()
                    if product.db_status != DBStatus.OK:
                        # If the reconnection fails,
                        # redirect user to the products page.
                        self.send_response(307)  # 307 Temporary Redirect
                        self.send_header("Location", '/products.html')
                        self.end_headers()
                        return

            if path == '' and not self.path.endswith('/'):
                # /prod must be routed to /prod/index.html first, so later
                # queries for web resources are '/prod/style...' as
                # opposed to '/style...', which would result in 'style'
                # being considered product name.
                LOG.debug("Redirecting user from /{0} to /{0}/index.html"
                          .format(product_endpoint))

                # WARN: Browsers cache '308 Permanent Redirect' responses,
                # in the event of debugging this, use Private Browsing!
                self.send_response(308)
                self.send_header("Location",
                                 self.path.replace(product_endpoint,
                                                   product_endpoint + '/',
                                                   1))
                self.end_headers()
                return

            # In other cases when '/prod/' is already in the request,
            # serve the main page and the resources, for example:
            # /prod/(index.html) -> /(index.html)
            # /prod/styles/(...) -> /styles/(...)
            self.path = self.path.replace(
                "{0}/".format(product_endpoint), "", 1)
        else:
            # No product endpoint in the request.

            if self.path in ['/', '/index.html']:
                # In case the homepage is requested and only one product
                # exists, try to skip the product list and redirect the user
                # to the runs immediately.
                only_product = self.server.get_only_product()
                if only_product:
                    if only_product.db_status == DBStatus.OK:
                        LOG.debug("Redirecting '/' to ONLY product '/{0}'"
                                  .format(only_product.endpoint))

                        self.send_response(307)  # 307 Temporary Redirect
                        self.send_header("Location",
                                         '/{0}'.format(only_product.endpoint))
                        self.end_headers()
                        return
                    else:
                        LOG.debug("ONLY product '/{0}' has database issues..."
                                  .format(only_product.endpoint))

                        self.send_response(307)  # 307 Temporary Redirect
                        self.send_header("Location", '/products.html')
                        self.end_headers()
                        return

                # If multiple products exist, route homepage queries to
                # serve the product list.
                LOG.debug("Serving product list as homepage.")
                self.path = '/products.html'
            else:
                # The path requested does not specify a product: it is most
                # likely a resource file.
                LOG.debug("Serving resource '{0}'".format(self.path))

            self.send_response(200)  # 200 OK

        SimpleHTTPRequestHandler.do_GET(self)  # Actual serving of file.
 def do_GET(self):
     sleep(self._latency)
     return SimpleHTTPRequestHandler.do_GET(self)
Exemple #40
0
    def do_GET(self):
        if self.path == "/":
            self.path = "/index.html"

        try:

            # check http url query value
            # http://127.0.0.1:8080/abc.json?comment=1234
            writeComment = False
            comment = ''
            updateTestDetails = ''
            readFileList = ''
            query = urlparse(self.path).query
            if query:
                query_components = dict(
                    qc.split("=") for qc in query.split("&"))

                # if query_components.__contains__('comment'):
                # if query_components.has_key('comment'):
                if 'comment' in query_components:
                    writeComment = True
                    comment = query_components["comment"]
                if 'updateTestDetails' in query_components:
                    updateTestDetails = True
                    detailComment = query_components["updateTestDetails"]
                    testId = query_components["testId"]
                if 'readFile' in query_components:
                    readFileList = True
                    baseFolder = query_components["readFile"]

            if writeComment == True:
                # filename = curdir + sep + self.path
                filename = curdir + urlparse(self.path).path

                # read json file
                with open(filename, 'r') as f:
                    json_data = json.load(f)
                    f.close()

                # update comment and write file
                comment = unquote(comment)
                if comment == "null":
                    comment = ""
                with open(filename, 'w') as f:
                    json_data['comment'] = comment
                    json.dump(json_data, f)
                    f.close()

                # return http response
                self.send_response(200)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                return
            elif updateTestDetails == True:
                # filename = curdir + sep + self.path
                filename = curdir + urlparse(self.path).path

                # read json file
                with open(filename, 'r') as f:
                    json_data = json.load(f)
                    f.close()

                # update comment and write file
                comment = unquote(detailComment)
                if comment == "null":
                    comment = ""
                with open(filename, 'w') as f:
                    tests = json_data['testResults']

                    for testResult in tests:
                        if testResult['test_id'] == testId:
                            testResult['analysis_comment'] = comment
                            break

                    json.dump(json_data, f)
                    f.close()

                # return http response
                self.send_response(200)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                return
            elif readFileList == True:

                jsonData = []
                baseFolder = curdir + urlparse(self.path).path
                if os.path.isdir(baseFolder):

                    for fileInFolder in os.listdir(baseFolder):
                        if ('_' in fileInFolder
                                and '_trend' not in fileInFolder
                                and ".DS_Store" not in fileInFolder):
                            index = fileInFolder.split('_')[
                                len(fileInFolder.split('_')) - 1]
                            jsonData.append({
                                'id':
                                index,
                                'path':
                                urlparse(self.path).path + '/' + fileInFolder
                            })

                filename = baseFolder + '/list'
                # read json file
                with open(filename, 'w+') as f:
                    str = json.dumps(jsonData)
                    f.write(str)
                    f.close()

                self.send_response(200)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                return
            else:
                return SimpleHTTPRequestHandler.do_GET(self)

        except IOError:
            self.send_error(404, 'File Not Found: %s' % self.path)
Exemple #41
0
 def do_GET(self):
     self.event.wait()
     SimpleHTTPRequestHandler.do_GET(self)
Exemple #42
0
 def do_GET(self):
     LOG.info("do_GET being called....")
     if not self.redirect():
         SimpleHTTPRequestHandler.do_GET(self)