Exemplo n.º 1
0
	def do_PUT(self):
		if (self.path == "/src/tasks.json"):
			form = cgi.FieldStorage(
				fp=self.rfile,
				headers=self.headers,
				environ={'REQUEST_METHOD':'PUT', 'CONTENT_TYPE':self.headers['Content-Type']}
			)
			tasks = []
			i = 0;
			while (form.getfirst("tasklist[" + str(i) + "][id]") is not None):
				isComplete = False
				isDeleted = False
				complete_str = form.getfirst("tasklist[" + str(i) + "][isComplete]")
				if (complete_str == 'true'):
					isComplete = True
				delete_str = form.getfirst("tasklist[" + str(i) + "][isDeleted]")
				if (delete_str == 'true'):
					isDeleted = True
				tasks.append({
					u"id": int(form.getfirst("tasklist[" + str(i) + "][id]")),
					u"isComplete": isComplete,
					u"isDeleted": isDeleted,
					u"text": form.getfirst("tasklist[" + str(i) + "][text]"),
					u"dateDue": form.getfirst("tasklist[" + str(i) + "][dateDue]")
				})
				i += 1
			with open('./src/tasks.json', 'w') as outfile:
				json.dump(tasks, outfile)
			sendJSON(self)
		else:
			SimpleHTTPRequestHandler.do_PUT(self)
Exemplo n.º 2
0
 def __init__(self, request, client_address, server):
     try:
         SimpleHTTPRequestHandler.__init__(self, request, client_address,
                                           server)
     except Exception as e:
         DEBUG("Request from client %s has failed." % (client_address[0]))
         DEBUG(str(e))
Exemplo n.º 3
0
    def __init__(self, *args, **kwargs):
        """
        :arg root: The path to the folder to serve

        """
        self.root = kwargs.pop('root')  # required kwarg
        SimpleHTTPRequestHandler.__init__(self, *args, **kwargs)
Exemplo n.º 4
0
 def do_HEAD(self):
     if is_static_path(self.path):
         # noinspection PyAttributeOutsideInit
         self.path = self._translate_overlay_path(self.path)
         SimpleHTTPRequestHandler.do_HEAD(self)
     else:
         self.send_error(405)
Exemplo n.º 5
0
 def do_HEAD(self):
     if is_proxied(self.path):
         self.do_proxied()
     elif self.path == "/config.js":
         self.do_config_js()
     else:
         SimpleHTTPRequestHandler.do_HEAD(self)
Exemplo n.º 6
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
Exemplo n.º 7
0
 def send_head(self):
     content_type = 'text/html; charset=utf-8'
     param = ''
     req_path = self.path
     if req_path.find('?') > 0:
         req_path, param = req_path.split('?')
     if req_path in ('/'):
         self.path = '/www/index.html'
         return SimpleHTTPRequestHandler.send_head(self)
     elif req_path in ('/curr'):
         iplist = [[ip.duration, ip.ip, ip.country, ip.timeString] for ip in gIpScanner.currBuff]
         html = json.dumps({'name': 'curr', 'data': iplist, 'columns': ['duration', 'ip', 'country', 'time']})
     elif req_path in ('/average'):
         history = [[ip.duration, ip.ip, ip.country, ip.timeString] for ip in gIpScanner.avgBuff]
         html = json.dumps({'name': 'history', 'data': history, 'columns': ['average', 'ip', 'country', 'time']})
     elif req_path in ('/ip_history'):
         param = param.strip()
         data = [
             [ip.duration, ip.ip, ip.country, ip.timeString]
             for ip in gIpScanner.historyBuff
             if not param or ip.ip == param
         ]
         html = json.dumps({'name': 'ip_history', 'data': data, 'columns': ['t', 'ip', 'country', 'time']})
     elif req_path in ('/ss'):
         html = json.dumps({'status': gIpScanner.status})
     else:
         return SimpleHTTPRequestHandler.send_head(self)
     f = StringIO.StringIO(html)
     self.send_response(200)
     self.send_header("Content-type", content_type)
     self.send_header("Content-Length", str(f.len))
     self.send_header("Last-Modified", self.date_time_string())
     self.end_headers()
     return f
    def do_GET(self):
        if not self.server.keys:
            if __name__ == '__main__':
                Handler.do_GET(self)
            return True

        auth_header = self.headers.get('Authorization')
        if auth_header is None:
            self.send_auth_request()
            self.wfile.write('<h1>Authorization Required</h1>'.encode())
            print('no auth header received')
            return False

        elif auth_header[len('Basic '):] in self.server.keys:
            if __name__ == '__main__':
                Handler.do_GET(self)
            return True

        else:
            self.send_auth_request()
            self.wfile.write('<h1>Authorization Required</h1>'.encode())
            auth = re.sub('^Basic ', '', auth_header)
            print('Authentication failed! %s' %
                  base64.b64decode(auth).decode())
            return False
Exemplo n.º 9
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)
Exemplo n.º 10
0
 def setup(self):
     '''Sets a timeout on the socket
     Abandon request handling when client has not responded
     for socket_timeout time.
     '''
     self.request.settimeout(self.socket_timeout)
     SimpleHTTPRequestHandler.setup(self)
Exemplo n.º 11
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 send_head(self):

        body = None

        if self.path=='/':
            body = self.parse_index()
        else:
            try:
                spell_end = self.path.index('/', 1)
            except:
                return SimpleHTTPRequestHandler.send_head(self)
            if spell_end>1:
                spell_name = unquote_plus(self.path[1:spell_end])
                for spell in self.json_data:
                    if spell['title']==spell_name:
                        body = self.parse_spell(spell)
                    elif spell['title'].lower()==spell_name:
                        body = self.parse_spell(spell)
                if body is None:
                    self.send_error(404, "Spell '%s' not found." % spell_name)
                    return None

        # Send body or default handler
        if body:
            self.send_response(200)
            self.send_header("Content-type", "text/html")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            return StringIO(body)
        else:
            return SimpleHTTPRequestHandler.send_head(self)
Exemplo n.º 13
0
 def handle(self):
     global active
     debug("$$$$$$$$$$$$$$$$$$$$$$$$$\n")
     active += 1
     SimpleHTTPRequestHandler.handle(self)
     active -= 1
     debug("$$$$$$$$$$$$$$$$$$$$$$$$$ ACTIVE: %0d\n" % active)
Exemplo n.º 14
0
    def __init__(self, *args, **kwargs):
        self.server_version = "IvrSimulator/"
        self.sys_version = ""

        statistical.inc_tas_requests()

        SimpleHTTPRequestHandler.__init__(self, *args, **kwargs)
Exemplo n.º 15
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)
Exemplo n.º 16
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
Exemplo n.º 17
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)
    def handle(self):
        #needed when wfile is used, or when self.close_connection is not used

        #
        #catch errors in SimpleHTTPRequestHandler.handle() after socket disappeared
        #due to loss of network connection

        self.log_message("handle entry on worker thread %d" %
                         threading.current_thread().ident)
        try:
            SimpleHTTPRequestHandler.handle(self)
        except (socket.error, ) as err:
            self.log_message(
                "handle(): Exception: in SimpleHTTPRequestHandler.handle(): %s"
                % str(err.args))
            print(
                "handle(): Exception: in SimpleHTTPRequestHandler.handle(): %s"
                % str(err.args))
        except (TypeError, ) as err:
            self.log_message(
                "handle(): Exception: in SimpleHTTPRequestHandler.handle(): %s"
                % str(err))
            print(
                "handle(): Exception: in SimpleHTTPRequestHandler.handle(): %s"
                % str(err))
        self.log_message("handle done on worker thread %d" %
                         threading.current_thread().ident)
Exemplo n.º 19
0
    def __init__(self, wikidb, conf, links_cache, request, client_address,
                 server):
        # pullcord is currently offline
        # self.reporturl = 'pullcord.laptop.org:8000'
        self.reporturl = False
        self.ip = conf['ip']
        self.port = conf['port']
        self.lang = conf['lang']
        self.templateprefix = conf['templateprefix']
        self.templateblacklist = set(conf['templateblacklist'])
        self.wpheader = conf['wpheader']
        self.wpfooter = conf['wpfooter']
        self.resultstitle = conf['resultstitle']
        self.base_path = os.path.dirname(conf['path'])
        self.links_cache = links_cache
        self._xo_color = conf['xocolor']

        if 'editdir' in conf:
            self.editdir = conf['editdir']
        else:
            self.editdir = False
        if 'giturl' in conf:
            self.giturl = conf['giturl']
        else:
            self.giturl = False

        self.wikidb = wikidb

        self.client_address = client_address

        SimpleHTTPRequestHandler.__init__(
            self, request, client_address, server)
Exemplo n.º 20
0
 def do_GET(self):
     print 'PATH: ', self.path[:5]
     if self.path[:5] == '/data':
         print 'path:', self.path
         self.path = DATA_DIR + self.path[5:]
         print 'new path:', self.path
     Handler.do_GET(self)
Exemplo n.º 21
0
    def __init__(self, wikidb, index, conf, request, client_address, server):
        # pullcord is currently offline
        # self.reporturl = 'pullcord.laptop.org:8000'
        self.reporturl = False
        self.index = index
        self.port = conf['port']
        self.lang = conf['lang']
        self.templateprefix = conf['templateprefix']
        self.templateblacklist = set(conf['templateblacklist'])
        self.wpheader = conf['wpheader']
        self.wpfooter = conf['wpfooter']
        self.resultstitle = conf['resultstitle']

        if 'editdir' in conf:
            self.editdir = conf['editdir']
        else:
            self.editdir = False
        if 'giturl' in conf:
            self.giturl = conf['giturl']
        else:
            self.giturl = False

        # init search index
        self.base_path = os.path.dirname(conf['path'])
        self.ix = open_dir(os.path.join(self.base_path, "index_dir"))

        self.wikidb = wikidb

        self.client_address = client_address
        SimpleHTTPRequestHandler.__init__(self, request, client_address,
                                          server)
        def __init__(self, *args, **kwargs):

            self.config = config

            self._logger = logging.getLogger(__name__)

            self.api = FSRest()
            self.close_mjpeg_stream = False

            self.ROUTES = (
                # [url_prefix ,  directory_path]
                ['/upload/preview/', ''],
                ['/settings.mjpeg', ''],
                ['/adjustment.mjpeg', ''],
                ['/scans', self.config.folders.scans],
                ['/scan', self.config.folders.scans],
                ['', self.config.folders.www
                 ],  # empty string for the 'default' match
            )
            try:
                SimpleHTTPRequestHandler.__init__(self, *args, **kwargs)
            except StandardError, e:
                self.close_mjpeg_stream = True
                #self.scanprocessor.stop()
                self._logger.debug("MJPEG Stream closed by client.")
Exemplo n.º 23
0
	def end_headers(self):
		query_components = parse_qs(urlparse(self.path).query)
		if 't' in query_components.keys():
			v = query_components['t'][0]
			print v
			self.send_header('Content-Type',v)
		SimpleHTTPRequestHandler.end_headers(self)
Exemplo n.º 24
0
 def __init__(self, request, client_address, server):
     self.builder = server.builder
     if PY2:
         SimpleHTTPRequestHandler.__init__(self, request, client_address,
                                           server)
     else:
         super().__init__(request, client_address, server)
 def do_HEAD(self):
     if is_proxied(self.path):
         self.do_proxied()
     elif self.path == "/config.js":
         self.do_config_js()
     else:
         SimpleHTTPRequestHandler.do_HEAD(self)
Exemplo n.º 26
0
    def __init__(self, wikidb, conf, links_cache, request, client_address,
                 server):
        # pullcord is currently offline
        # self.reporturl = 'pullcord.laptop.org:8000'
        self.reporturl = False
        self.ip = conf['ip']
        self.port = conf['port']
        self.lang = conf['lang']
        self.templateprefix = conf['templateprefix']
        self.templateblacklist = set(conf['templateblacklist'])
        self.wpheader = conf['wpheader']
        self.wpfooter = conf['wpfooter']
        self.resultstitle = conf['resultstitle']
        self.base_path = os.path.dirname(conf['path'])
        self.links_cache = links_cache
        self._xo_color = conf['xocolor']

        if 'editdir' in conf:
            self.editdir = conf['editdir']
        else:
            self.editdir = False
        if 'giturl' in conf:
            self.giturl = conf['giturl']
        else:
            self.giturl = False

        self.wikidb = wikidb

        self.client_address = client_address

        SimpleHTTPRequestHandler.__init__(self, request, client_address,
                                          server)
Exemplo n.º 27
0
 def do_POST(self):
     # pylint: disable=E1101
     if self.path == '/RPC2':
         SimpleJSONRPCRequestHandler.do_POST(self)
     else:
         __pychecker__ = 'no-classattr'
         SimpleHTTPRequestHandler.do_POST(self)
Exemplo n.º 28
0
    def __init__(self, wikidb, conf, links_cache, request, client_address, server):
        # pullcord is currently offline
        # self.reporturl = 'pullcord.laptop.org:8000'
        self.reporturl = False
        self.port = conf["port"]
        self.lang = conf["lang"]
        self.templateprefix = conf["templateprefix"]
        self.templateblacklist = set(conf["templateblacklist"])
        self.wpheader = conf["wpheader"]
        self.wpfooter = conf["wpfooter"]
        self.resultstitle = conf["resultstitle"]
        self.base_path = os.path.dirname(conf["path"])
        self.links_cache = links_cache

        if "editdir" in conf:
            self.editdir = conf["editdir"]
        else:
            self.editdir = False
        if "giturl" in conf:
            self.giturl = conf["giturl"]
        else:
            self.giturl = False

        self.wikidb = wikidb

        self.client_address = client_address

        SimpleHTTPRequestHandler.__init__(self, request, client_address, server)
Exemplo n.º 29
0
    def __init__(self, handlers, browser, *args, **kwargs):
        '''Initialises handler for use with BaseHTTPRequestHandler

        handlers - mapping of paths to handler objects;
        browser - browser for downloading .torrent files from topic urls.

        There should be '*' handler in handlers dict.
        There should be page_template.auth_path in handlers dict for authetification.

        On request server checks if user if authorized (via cookie).
        If not - it draws authorisation page from page_template.authorize, or
        processes authorisation via page_template.auth_handler path.
        If the user is authorized server checks path and calls
        corresponding handler's process method. If no such path->handler
        mapping - then it calls '*' handler.

        Cause this class needs to initialise parent's class, please wrap it
        with functools like:
            functools.partial(tserv.TorrentServHandler, handlers, browser)
        '''

        self.handlers = handlers
        self.browser = browser
        self.body = None
        BaseRequestHandler.__init__(self, *args, **kwargs)
Exemplo n.º 30
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)
Exemplo n.º 31
0
 def setup(self):
     '''Sets a timeout on the socket
     Abandon request handling when client has not responded
     for socket_timeout time.
     '''
     self.request.settimeout(self.socket_timeout)
     SimpleHTTPRequestHandler.setup(self)
Exemplo n.º 32
0
 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)
Exemplo n.º 33
0
    def __init__(self, handlers, browser, *args, **kwargs):
        '''Initialises handler for use with BaseHTTPRequestHandler

        handlers - mapping of paths to handler objects;
        browser - browser for downloading .torrent files from topic urls.

        There should be '*' handler in handlers dict.
        There should be page_template.auth_path in handlers dict for authetification.

        On request server checks if user if authorized (via cookie).
        If not - it draws authorisation page from page_template.authorize, or
        processes authorisation via page_template.auth_handler path.
        If the user is authorized server checks path and calls
        corresponding handler's process method. If no such path->handler
        mapping - then it calls '*' handler.

        Cause this class needs to initialise parent's class, please wrap it
        with functools like:
            functools.partial(tserv.TorrentServHandler, handlers, browser)
        '''

        self.handlers = handlers
        self.browser = browser
        self.body = None
        BaseRequestHandler.__init__(
                self, *args, **kwargs
        )
Exemplo n.º 34
0
 def do_GET(self):
     if root_redir and self.path == '/':
         self.send_response(301)
         self.send_header("Location", root_redir)
         self.end_headers()
         return
     SimpleHTTPRequestHandler.do_GET(self)
Exemplo n.º 35
0
 def handle_one_request(self):
     # try:
     if self.handshake_done:
         self.read_next_message()
         # a read or a write timed out.  Discard this connection
     else:
         SimpleHTTPRequestHandler.handle_one_request(self)
Exemplo n.º 36
0
 def do_GET(self):
     if os.path.splitext(self.path)[1] == '.html':
         self.send_response(200)
         self.send_header("Content-type", 'text/html')
         self.send_header("Last-Modified", self.date_time_string())
         self.end_headers()
         self.wfile.write(
             '<!DOCTYPE html><html><head><meta charset="utf-8"><script src="../ckeditor/ckeditor.js"></script></head><body><textarea cols="1" id="editor1" name="editor1" rows="1"></textarea><script>CKEDITOR.replace("editor1",{on: {}});</script></body></html>'
         )
     elif os.path.splitext(self.path)[1] == '.jpg':
         try:
             bI = _gdI[self.path[1:]]
         except:
             with io.BytesIO() as bIO:
                 ip = photos.pick_image(show_albums=True)
                 ip.save(bIO, ip.format)
                 bI = bIO.getvalue()
                 _gdI[self.path[1:]] = bI
         self.send_response(200)
         self.send_header("Content-type", 'image/jpeg')
         self.send_header("Content-Length", str(len(bI)))
         self.send_header("Last-Modified", self.date_time_string())
         self.end_headers()
         self.wfile.write(bI)
     else:
         SimpleHTTPRequestHandler.do_GET(self)
Exemplo n.º 37
0
 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)
Exemplo n.º 38
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
Exemplo n.º 39
0
	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()
Exemplo n.º 40
0
    def __init__(self, *args, **kwargs):
        """
        :arg root: The path to the folder to serve

        """
        self.root = kwargs.pop('root')  # required kwarg
        SimpleHTTPRequestHandler.__init__(self, *args, **kwargs)
Exemplo n.º 41
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()
Exemplo n.º 42
0
 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)
Exemplo n.º 43
0
    def do_GET(self):
        ''' Present frontpage with user authentication. '''
        if self.headers.getheader('Authorization') is None:
            self.do_authhead()
            self.wfile.write('no auth header received')
        elif self.headers.getheader('Authorization') == 'Basic ' + self.KEY:
            SimpleHTTPRequestHandler.do_GET(self)
        else:
            self.do_authhead()
            self.wfile.write(self.headers.getheader('Authorization'))
            self.wfile.write('not authenticated')

        if self.path == '/':
            self.path = "index.html"
            return SimpleHTTPRequestHandler.do_GET(self)

        if self.path == "/tank-service":
            os.system("sudo systemctl restart tankmanager.service")
            logging.info("Tank manager service is reload")
            self._set_response()

        if self.path == "/reboot":
            os.system("sudo reboot")
            logging.info("System reboot")
            self._set_response()
Exemplo n.º 44
0
    def send_head(self):

        body = None

        if self.path == '/':
            body = self.parse_index()
        else:
            try:
                spell_end = self.path.index('/', 1)
            except:
                return SimpleHTTPRequestHandler.send_head(self)
            if spell_end > 1:
                spell_name = unquote_plus(self.path[1:spell_end])
                for spell in self.json_data:
                    if spell['title'] == spell_name:
                        body = self.parse_spell(spell)
                    elif spell['title'].lower() == spell_name:
                        body = self.parse_spell(spell)
                if body is None:
                    self.send_error(404, "Spell '%s' not found." % spell_name)
                    return None

        # Send body or default handler
        if body:
            self.send_response(200)
            self.send_header("Content-type", "text/html")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            return StringIO(body)
        else:
            return SimpleHTTPRequestHandler.send_head(self)
Exemplo n.º 45
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()
Exemplo n.º 46
0
 def __init__(self, req, client_addr, server):
     try:
         SimpleHTTPRequestHandler.__init__(self, req, client_addr, server)
         self.server = server
         self.req = req
     except socket.error:
         pass
Exemplo n.º 47
0
 def do_HEAD(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_HEAD(self)
         
     return
Exemplo n.º 48
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()
Exemplo n.º 49
0
 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'))
Exemplo n.º 50
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
Exemplo n.º 51
0
 def do_HEAD(self):
     if is_static_path(self.path):
         # noinspection PyAttributeOutsideInit
         self.path = self._translate_overlay_path(self.path)
         SimpleHTTPRequestHandler.do_HEAD(self)
     else:
         self.send_error(405)
Exemplo n.º 52
0
    def do_HEAD(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_HEAD(self)

        return
Exemplo n.º 53
0
 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)
Exemplo n.º 54
0
 def log_request(self, code='-', size='-'):
     # Don't log HEAD requests because these are very spammy with livejs turned on
     if self.command == 'HEAD':
         return
     if platform.python_version_tuple()[0] == '2':
         SimpleHTTPRequestHandler.log_request(self, code, size)
     else:
         super().log_request(code, size)
Exemplo n.º 55
0
 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)
 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)
Exemplo n.º 57
0
    def __init__(self, req, client_addr, server):
        #        self._request = req
        #        self._address = client_addr
        self._logger = PytoLogging(self.__class__.__name__)
        self._api = PytomationAPI()
        self._server = server

        SimpleHTTPRequestHandler.__init__(self, req, client_addr, server)
Exemplo n.º 58
0
 def log_request(self, code='-', size='-'):
     # Don't log HEAD requests because these are very spammy with livejs turned on
     if self.command == 'HEAD':
         return
     if platform.python_version_tuple()[0] == '2':
         SimpleHTTPRequestHandler.log_request(self, code, size)
     else:
         super().log_request(code, size)
Exemplo n.º 59
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)