예제 #1
1
    def do_GET(self):
        parsed_path = urllib.parse.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.encode('utf-8'))
        elif parsed_path.path.startswith("/redirect"):
            self.send_response(301)
            self.send_header('Location', "/echo")
            self.end_headers()
        else:
            SimpleHTTPRequestHandler.do_GET(self)

        return
예제 #2
0
    def do_GET(self):
        params = urlparse(self.path)

        if params.path in self.handlers:
            self.handlers[params.path](self)
        else:
            SimpleHTTPRequestHandler.do_GET(self)
예제 #3
0
 def do_GET(self):
     if self.path == "/shutdown/":
         self.wfile.write("HTTP/1.1 200 OK\n\nShutting down...".encode())
         self.send_response(200)
         subprocess.Popen(["shutdown", "-h", "now"]).wait()
     else:
         SimpleHTTPRequestHandler.do_GET(self)
예제 #4
0
 def do_GET(self):
     """Handle GET request. Calls handle_websocket(). If unsuccessful,
     and web server is enabled, SimpleHTTPRequestHandler.do_GET will be called."""
     if not self.handle_websocket():
         if self.only_upgrade:
             self.send_error(405, "Method Not Allowed")
         else:
             SimpleHTTPRequestHandler.do_GET(self)
예제 #5
0
 def do_GET(self):
     if self.path == '/+CSCOE+/logon.html':
         self.redirect('/+CSCOE+/logon.html?fcadbadd=1')
         return
     elif self.path.startswith('/+CSCOE+/logon.html?') and 'reason=1' in self.path:
         self.wfile.write(self.send_file('logon_failure').getvalue())
         return
     SimpleHTTPRequestHandler.do_GET(self)
예제 #6
0
파일: server.py 프로젝트: kevinbeaty/mvw
 def do_GET(self):
     """Serve a GET request."""
     content = self._regenerate(self.path)
     if content:
         self._send_regenerated_head(content)
         self.wfile.write(content)
     else:
         SimpleHTTPRequestHandler.do_GET(self)
예제 #7
0
 def do_GET(self,*args,**kwds):
   tmp = self.path.split('/')
   # redirect?
   if (len(tmp) == 3) and (tmp[0] == tmp[2]) and tmp[0] == '':
     self.send_response(301)
     self.send_header('Location', self.path + 'html/')
   else:
     SimpleHTTPRequestHandler.do_GET(self,*args,**kwds)
예제 #8
0
파일: standalone.py 프로젝트: a-tsioh/brat
 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)
예제 #9
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)
예제 #10
0
 def do_POST(self):
     """Handle POST request. If web server is enabled,
     SimpleHTTPRequestHandler.do_GET will be called."""
     if self.only_upgrade:
         self.send_error(405, "Method Not Allowed")
     else:
         # SimpleHTTPRequestHandler has no do_POST function, but we don't need
         # anything special, just to respond in the same way as the GET
         SimpleHTTPRequestHandler.do_GET(self)
예제 #11
0
 def do_GET(self, method='GET'):
     #copy all data into a place we can see later.
     self.wfile = FileWrapper(self.wfile)
     #give the actual work of handling the request to SimpleHTTPRequestHandler
     SimpleHTTPRequestHandler.do_GET(self)
     #by this time, the shim file object we created previously is
     #full of the response data and is ready to display.
     print('')
     print(self._heading('HTTP Response'))
     print(self.wfile)
 def do_GET(self):
     pr = urllib.parse.urlparse(self.path)
     if pr.path == '/v':
         params = urllib.parse.parse_qs(pr.query)
         self.send_response(200)
         self.send_header("Content-type", "text/html")
         self.end_headers()
         self.wfile.write(self.getPost(pr.path, params['p'][0]).encode())
         self.wfile.flush()
     else:
         SimpleHTTPRequestHandler.do_GET(self)
예제 #13
0
    def do_GET(s):
        print(s.path)
        if s.path.lower().endswith(".stl"):
            filename = "." + s.path
            if os.path.exists(filename):
                stream_mesh_file(s, filename)
                return

        # if we get here, we didn't get an stl file to stream
        # call the parent's get
        C_simple_handler.do_GET(s)
예제 #14
0
 def do_GET( self ):
     urlParams = urlparse(self.path)
     if os.access( '.' + os.sep + urlParams.path, os.R_OK ):
         SimpleHTTPRequestHandler.do_GET(self);
     else:
         self.send_response(200)
         self.send_header( 'Content-type', 'text/html' )
         self.end_headers()
         with open('index.html', 'r') as f:
             html = f.read()
         self.wfile.write( html.encode() )
예제 #15
0
 def do_GET(self):
     with open('index.html') as index_file_handle:
         url_params = urlparse.urlparse(self.path)
         if os.access('.{}{}'.format(
             os.sep, url_params.path), os.R_OK
         ):
             SimpleHTTPRequestHandler.do_GET(self)
         else:
             self.send_response(200)
             self.send_header('Content-type', 'text/html')
             self.end_headers()
             self.wfile.write(index_file_handle.read().encode('utf8'))
예제 #16
0
    def do_GET(self):
        if (self.headers.get('upgrade') and
                self.headers.get('upgrade').lower() == 'websocket'):

            # Just indicate that an WebSocket upgrade is needed
            self.last_code = 101
            self.last_message = "101 Switching Protocols"
        elif self.only_upgrade:
            # Normal web request responses are disabled
            self.last_code = 405
            self.last_message = "405 Method Not Allowed"
        else:
            SimpleHTTPRequestHandler.do_GET(self)
예제 #17
0
 def do_GET(self):
     if self.path not in ('/', '/termlib.js'):
         self.send_response(404)
         self.send_header('Content-type', 'text/plain')
         self.end_headers()
         self.wfile.write(b'404')
         return
     os.chdir(os.path.dirname(__file__))
     if PY3:
         super().do_GET()
     else:
         SimpleHTTPRequestHandler.do_GET(self)
     os.chdir(cwd)
예제 #18
0
    def do_GET(self):
        """
        /packages.tar  - serve the contents of the folder referenced in
                         self.server.packages as a streamd .tar file
        /packages/*    - serve the files of the folder referenced in
                         self.server.packages (chrooting into it)
        /*             - serve the files of the folder referenced in
                         self.server.chroot

        """
        if self.path == "/packages.tar":
            self._serve_folder_as_tar(self.server.packages)
            return

        SimpleHTTPRequestHandler.do_GET(self)
예제 #19
0
    def do_GET(self):
        if self.path == "/":
            self.send_response(200)
            self.send_header('Content-Type', 'text/plain')
            self.end_headers()
            user_agent = self.headers.get('User-Agent')
            messages = ('Have a nice day', 'So long', 'Come again soon')
            self.write("""
Hello person from %s.
Your user agent is %s.
%s.
""" % (self.client_address[0], user_agent or "unknown", choice(messages)))
            return
        
        SimpleHTTPRequestHandler.do_GET(self)
예제 #20
0
    def do_GET(self):
        if self.headers.get("upgrade") and self.headers.get("upgrade").lower() == "websocket":

            if self.headers.get("sec-websocket-key1") or self.headers.get("websocket-key1"):
                # For Hixie-76 read out the key hash
                self.headers.__setitem__("key3", self.rfile.read(8))

            # Just indicate that an WebSocket upgrade is needed
            self.last_code = 101
            self.last_message = "101 Switching Protocols"
        elif self.only_upgrade:
            # Normal web request responses are disabled
            self.last_code = 405
            self.last_message = "405 Method Not Allowed"
        else:
            SimpleHTTPRequestHandler.do_GET(self)
예제 #21
0
        def do_GET(self):
            # Parse query string, make sure we have a callback.
            url = urlparse(self.path)
            if '.jsonp' != url.path[-6:]: return SimpleHTTPRequestHandler.do_GET(self)
            query = parse_qs(url.query)
            if 'callback' not in query: raise Exception('No callback specified')
            callback = query['callback'][-1]

            # Get data for different JSONp calls
            try:
                if '/colorvalue.jsonp' == url.path:
                    data = color.colorvalue(query['colordef'][0], query['txo[]'])
                elif '/makeconversion.jsonp' == url.path:
                    data = color.makeconversion(loads(query['txspec'][0]))
                elif '/receive.jsonp' == url.path:
                    data = message.receive()
                elif '/send.jsonp' == url.path:
                    data = message.send(query['subject'][0], query['body'][0])
                elif '/signrawtransaction.jsonp' == url.path:
                    data = bitcoin.signrawtransaction(
                        query['rawtx'][0],
                        loads(query['inputs'][0]),
                        query['keys[]']
                    )
                else:
                    data = {'error': 'Did not understand ' + url.path}

            except (KeyError, ValueError): data = {'error': 'Wrong parameters', 'query': query}

            # Send the reply as jsonp
            self.send_response(200)
            self.send_header('Content-type', 'application/javascript')
            self.end_headers()
            self.wfile.write(bytes(callback + '(' + dumps(data) + ');', 'UTF-8'))
 def do_GET(self, method='GET'):
     """Handles a GET request the same way as
     SimpleHTTPRequestHandler, but also prints the full text of the
     response to standard output."""
     #Replace the file object being used to output response with a
     #shim that copies all outgoing data into a place we can see
     #later. Then, give the actual work of handling the request to
     #SimpleHTTPRequestHandler.
     self.wfile = FileWrapper(self.wfile)
     SimpleHTTPRequestHandler.do_GET(self)
     #By this time, the shim file object we created previously is
     #full of the response data, and is ready to be displayed. The
     #request has also been displayed, since it was logged by
     #log_request() (called by SimpleHTTPRequestHandler's do_GET)
     print("")
     print(self._heading("HTTP Response"))
     print(self.wfile)
예제 #23
0
    def do_GET(self):
        abspath = os.path.realpath("." + (self.path.split("?")[0]))
        if self.headers.get("upgrade") and self.headers.get("upgrade").lower() == "websocket":

            # Just indicate that an WebSocket upgrade is needed
            self.last_code = 101
            self.last_message = "101 Switching Protocols"
        elif self.only_upgrade:
            # Normal web request responses are disabled
            self.last_code = 405
            self.last_message = "405 Method Not Allowed"
        elif self.file_only and not os.path.isfile(abspath):
            self.send_response(404, "No such file")
        elif self.no_parent and not abspath.startswith(self.webroot):
            self.send_response(403, "Hidden resources")
        else:
            SimpleHTTPRequestHandler.do_GET(self)
예제 #24
0
    def do_GET(self):
        """
        Artificially slow down the response to make sure there are no race
        conditions.
        """

        sleep(0.5)

        return SimpleHTTPRequestHandler.do_GET(self)
예제 #25
0
 def do_GET(self):
   if self.path == '/ip':
     self.send_response(200)
     self.send_header('Content-type', 'text/html')
     self.end_headers()
     self.wfile.write('ip adresiniz %s' % self.client_address[0])
     return
   else:
     return SimpleHTTPRequestHandler.do_GET(self)
 def do_GET(self):
     if self.path == "/style.css" or self.path == "/favicon.ico":
         SimpleHTTPRequestHandler.do_GET(self)
     else:
         self.write_html_headers()
         self.write_template("header")
         parsed_query = parse_qs(urlparse(self.path).query)
         if self.path == "/":
             self.write_template("index")
         elif self.path == "/single/":
             table, row = poprandomrow(get_table(self.filename))
             row.update(dict(timestamp=formatted_time()))
             self.write_template("single", substitution=row)
         elif "/edit" in self.path:
             uri = parsed_query.get("uri")
             if(uri):
                 for row in get_table(self.filename):
                     if(uri[0] == row["uri"]):
                         row.update(dict(timestamp=formatted_time()))
                         self.write_template("single", substitution=row)
             else:
                 self.write_template("new",
                                 substitution=dict(timestamp=formatted_time()))
         #elif self.path == "/archive/": #TODO merge into /search/
         #    for row in get_table(self.filename):
         #        if(row["rating"] == 0): # rating==never, thus inactive
         #            self.write_template("archive",
         #                                substitution=row) #TODO doesnt work any longer correctly: notes/mdnotes
         elif "/search" in self.path:
             q = parsed_query.get("q")
             minratings = parsed_query.get("minrating")
             minrating = int(minratings[0]) if minratings else 0
             maxratings = parsed_query.get("maxrating")
             maxrating = int(maxratings[0]) if maxratings else 0
             regex = re.compile(q[0], re.IGNORECASE) if q else re.compile("")
             for row in get_table(self.filename):
                 if(minrating <= row["rating"] <= maxrating):
                     if(regex.search(row["notes"]) or
                        regex.search(row["title"])):
                         self.write_template("all",
                                             substitution=row)
         else:
             self.write_template("error")
         self.write_template("footer")
예제 #27
0
파일: httpd.py 프로젝트: Miyurz/SuperNET
  def do_GET(self):
    # Browsing to ?quit=1 will kill the server cleanly.
    _, _, _, query, _ = urlsplit(self.path)
    if query:
      params = parse_qs(query)
      if '1' in params.get('quit', []):
        self._SendNothingAndDie()
        return

    return SimpleHTTPRequestHandler.do_GET(self)
예제 #28
0
    def do_GET(self):
        key = re.search('ajpvnc_key=' + str(self.session) + r';*[\s|$]', str(self.headers))
        if not key: # Wrong security cookie
            print ('No key!')
            self.last_code = 403
            self.last_message = "403 Forbidden"
            return None
        if (self.headers.get('upgrade') and
                self.headers.get('upgrade').lower() == 'websocket'):

            if (self.headers.get('sec-websocket-key1') or
                    self.headers.get('websocket-key1')):
                # For Hixie-76 read out the key hash
                self.headers.__setitem__('key3', self.rfile.read(8))

            # Just indicate that an WebSocket upgrade is needed
            self.last_code = 101
            self.last_message = "101 Switching Protocols"
        elif self.only_upgrade:
            # Normal web request responses are disabled
            self.last_code = 405
            self.last_message = "405 Method Not Allowed"
        else:
            SimpleHTTPRequestHandler.do_GET(self)
예제 #29
0
 def do_GET(self):
     #global auth_key
     ''' Present frontpage with user authentication. '''
     if self.headers.get('authorization') == None:
         self.do_AUTHHEAD()
         self.wfile.write(b'no auth header received')
         pass
     elif self.headers.get('authorization') == auth_keyWord_b64:
         return SimpleHTTPRequestHandler.do_GET(self)
         pass
     else:
         self.do_AUTHHEAD()
         #print(self.headers.get('authorization'))
         self.wfile.write(b'not authenticated')
         pass
예제 #30
0
    def do_GET(self):
        url = urlparse(self.path)
        print("url: '%s' url.path: '%s'" % (url, url.path))
        if url.path == "" or url.path == "/":
            self.redirect("/login.html")

        if url.path == "/authenticate":
            self.redirect("/homepage.html")
            return

        if url.path == '/admin/shutdown':
            print("server shutdown has been requested")
            os.kill(os.getpid(), signal.SIGHUP)

        return SimpleHTTPRequestHandler.do_GET(self)
예제 #31
0
    def downloadFile(self, relPath, parameters):
        print("Downloading: " + relPath)
        fullPath = base_dir(relPath)
        if not os.path.isfile(fullPath):
            return self.notFound(relpath)
        
        if "i" in parameters and parameters["i"]:
            SimpleHTTPRequestHandler.do_GET(self)
            return

        derp, ext = os.path.splitext(relPath)
        ext = ext[1:].lower()
        f = open(fullPath, 'rb')
        self.send_response(200)
        if ext == "html" or ext == "htm":
            self.send_header('Content-type', 'text/html;charset=utf-8')
        dat = f.read()
        self.send_header("Content-length", len(dat))
        if config.protocol == "HTTP/1.1":
            self.send_header('Connection', 'Close')
        self.end_headers()
        self.wfile.write(dat)
        self.wfile.flush()
        f.close()
    def do_GET(self):
        url = urlparse(self.path)
        print("url: '%s' url.path: '%s'" % (url, url.path))
        if url.path == "" or url.path == "/":
            self.redirect("/login.html")

        if url.path == "/authenticate":
            self.redirect("/homepage.html")
            return

        if url.path == '/admin/shutdown':
            print("server shutdown has been requested")
            os.kill(os.getpid(), signal.SIGHUP)

        return SimpleHTTPRequestHandler.do_GET(self)
예제 #33
0
    def do_GET(self):
        """ Present frontpage with user authentication. """
        global api_key
        match = self.token_pattern.search(self.path)
        if match:
            prefix_length = len(match.group(0)) - 1
            new_path = self.path[prefix_length:]
            found_api_key = match.group(1)
            if found_api_key == api_key:
                self.path = new_path
                return SimpleHTTPRequestHandler.do_GET(self)

        self.send_response(403)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(b"no valid api key received")
예제 #34
0
 def do_GET(self):
     if self.path == '/':
         self.path = 'public/index.html'
         return SimpleHTTPRequestHandler.do_GET(self)
     elif self.path == '/negotiate':
         token = build_authentication_token(
             sys.argv[1],
             'stream',
             roles=[
                 'webpubsub.sendToGroup.stream',
                 'webpubsub.joinLeaveGroup.stream'
             ])
         print(token)
         self.send_response(200)
         self.send_header('Content-Type', 'application/json')
         self.end_headers()
         self.wfile.write(json.dumps({'url': token['url']}).encode())
예제 #35
0
    def do_GET(self):

        current_time = time.localtime()
        elapsed_time = time.time() - server_start

        string_current_t = time.strftime("%a, %d %b %Y %H:%M:%S", current_time)
        #string_elapsed_t = time.strftime("%a, %d %b %Y %H:%M:%S", elapsed_time)

        cpu_usage = psutil.cpu_percent()
        memory_usage = psutil.virtual_memory()

        process_list = ''

        for process in psutil.process_iter():
            try:
                process_info = process.as_dict(attrs=['pid', 'name'])
                process_list += "PID " + str(
                    process_info['pid']
                ) + " " + "NAME " + process_info['name'] + "\n    "
            except psutil.NoSuchProcess:
                pass
        path = '/usr/bin/serverscripts/index_bkp.html'
        index_file = open(path)
        f = index_file.read()
        index_file.close()

        f = re.sub(r"hhh", process_list, f)
        f = re.sub(r"aaa", string_current_t, f)
        f = re.sub(r"bbb", str(elapsed_time), f)
        f = re.sub(r"ccc", processor, f)
        f = re.sub(r"ddd", str(cpu_usage), f)
        f = re.sub(r"eee", str(memory_usage), f)
        f = re.sub(r"ggg", linux, f)

        self.path = '/usr/bin/serverscripts/index.html'
        index_file = open(self.path, 'w')
        index_file.write(f)
        index_file.close()

        print("connection recieved")

        return SimpleHTTPRequestHandler.do_GET(self)
예제 #36
0
    def do_GET(self):
        path, qs = self.path.split("?") if '?' in self.path else [
            self.path, ""
        ]
        switcher = {
            "/hello": get_page_hello,
            "/goodbye": get_page_goodbye,
            "/pages": get_page_about_me,
            "/pages/hobby": get_page_hobby,
        }
        if path in switcher:
            msg = switcher[path](qs)

            self.send_response(200)
            self.send_header("content-type", "text/plain")
            self.send_header("content-length", str(len(msg)))
            self.end_headers()
            self.wfile.write(msg.encode())
        else:
            return SimpleHTTPRequestHandler.do_GET(self)
예제 #37
0
    def do_GET(self):
        path, qs = self.path.split("?") if '?' in self.path else [
            self.path, ""
        ]
        path = path.rstrip('/')
        switcher = {
            "/hello": page_hello,
            "/goodbye": page_goodbye,
            "/resume": page_p
        }
        if path in switcher:
            msg = switcher[path](qs)

            self.send_response(200)
            self.send_header("Content-type", "text/plain")
            self.send_header("Content-length", str(len(msg)))
            self.end_headers()
            self.wfile.write(msg.encode())
        else:
            return SimpleHTTPRequestHandler.do_GET(self)
 def do_GET(self):
     try:
         # Get code from Raindrop
         code = parse_qs(urlparse(self.path).query).get("code", str)[0]
     except TypeError:
         # If a request was made without a code, just display an error message
         self.path = "/auth_error.html"
     else:
         # We got the code, so we use that to request a token from Raindrop, which we use a PHP script to do
         # because of issues with SSL root certificates in some versions of Python on macOS,
         # which makes this unreliable to do in Python if we should keep this thing small and simple but still safe.
         token_result = os.popen("/usr/bin/php raindrop-get-token.php '" +
                                 code.replace("'", "'\\''") + "'").read()
         if token_result == "success":
             # If we succeeded in getting the token, display information about the authentication being successful
             self.path = "/auth_info.html"
         else:
             # If we failed to get the token, display information about the authentication having failed
             self.path = "/auth_error.html"
     # Stop the webserver in 2 seconds, so we have time to display the info web page before it quits
     os.system("sleep 2 && " + kill_command + " &")
     return SimpleHTTPRequestHandler.do_GET(self)
예제 #39
0
    def do_GET(self):
        MOVE_PREFIX = '/move/'

        if self.path == '/init':
            environment = Environment(INIT_ENVIRONMENT)
            # return self.__send_json({'env' : environment.get(), 'actor' : environment.get_actor_state()})
            return self.__send_json(environment.get())

        elif self.path == '/':
            self.path = '/web/index.html'

        elif self.path.startswith(MOVE_PREFIX):
            env = json.loads(unquote(self.path[len(MOVE_PREFIX):]))
            env_text = '\n'.join(map(lambda r: ' '.join(r), env))
            environment = Environment(env_text)

            state = environment.get_actor_state()

            strategy = build_strategy()
            load_from_file(strategy)
            action = strategy.next_action(state, 0)
            environment.perform_action(action)

            response = {
                'env': environment.get(),
                'terminal': environment.actor_in_terminal_state,
                'stats': {
                    'ε': strategy.ε,
                    'scores': strategy.scores,
                    'episode': strategy.episode
                }
            }

            return self.__send_json(response)

        return SimpleHTTPRequestHandler.do_GET(self)
예제 #40
0
    def do_POST(self):
        print('got POST to {path}'.format(path=self.path))

        global Session
        session = Session()
        request_ip, request_port = self.request.getpeername()
        content_length = int(self.headers.get('Content-Length'))

        content_type, pdict = cgi.parse_header(
            self.headers.get('content-type'))
        data = dict()

        if content_type == 'application/json':
            post_body = self.rfile.read(content_length)
            data = simplejson.loads(post_body)
        elif content_type == 'multipart/form-data':
            # ошибка если использовать str
            pdict['boundary'] = bytes(pdict['boundary'], 'utf-8')
            data = cgi.parse_multipart(self.rfile, pdict)

        print('post data', data)

        if '{api}/service/diag'.format(api=API_VERSION) == self.path:
            self.create_diagnostic(request_ip, data, session)
            return

        if '{api}/service'.format(api=API_VERSION) == self.path:
            self.create_service(request_ip, data, session)
            return

        if '{api}/runner'.format(api=API_VERSION) == self.path:
            self.create_runner(request_ip, data, session)
            self.change_workplace(request_ip, data, session)
            return

        return SimpleHTTPRequestHandler.do_GET(self)
예제 #41
0
    def do_GET(self):
        if re.search('/api/global_regex', self.path):
            print(self.path.split('/'))
            #This URL will trigger our sample function and send what it returns back to the browser
            self.send_response(200)
            self.send_header('Content-type', 'application/json; charset=UTF-8')
            self.end_headers()
            f = open("api/global_regex.json", "r")
            # all_regex = json.loads(f.read())
            self.wfile.write(f.read().encode())  # call sample function here
            return

            if re.search('/api/regex/.*', self.path):
                token = self.path.split('/')[-1]
            #This URL will trigger our sample function and send what it returns back to the browser
            self.send_response(200)
            self.send_header('Content-type', 'application/json; charset=UTF-8')
            self.end_headers()

            f = open("api/global_regex.json", "r")
            all_regex = json.loads(f.read())
            res_regex = [x for x in all_regex if x["token"] == token][0]

            self.wfile.write(
                json.dumps(res_regex).encode())  #call sample function here
            return

        # Path que redirecciona que carga el fichero index.html pero con los datos de pyramid_globals modificados
        if re.search('/api/r/.*', self.path):
            return
            # pyramid_globals = {
            # 	"regex": "Test",
            # 	"description": "No description",
            # 	"title": "Untitled Regex",
            # 	"strFlags": "",
            # 	"testString": "My test data",
            # 	"isOwner": true,
            # 	"token": "MpF1RYmqLxOyd2E0",
            # 	"tier": "",
            # 	"flavor": "javascript",
            # 	"unitTests": "[]",
            # 	"email": ""
            # }

        if re.search('/tools/off', self.path):
            self.send_response(200)
            self.send_header('Content-type', 'text/html; charset=UTF-8')
            self.end_headers()

            self.wfile.write("Bye!".encode())
            time.sleep(2)

            server.socket.close()
            quit()

        else:
            #serve files, and directory listings by following self.path from
            #current working directory
            try:
                SimpleHTTPRequestHandler.do_GET(self)
            except Exception as err:
                print(err)
                server.socket.close()
                quit()
예제 #42
0
    def do_GET(self):
        from confply import pushd
        query_list = None

        # split the query out if need be
        if "?" in self.path:
            self.path, query_list = self.path.split("?")
            if "&" in query_list:
                query_list = query_list.split("&")
            else:
                query_list = [query_list]

        # put the queries into a dict
        queries = {}
        if query_list is not None:
            for q in query_list:
                k, v = q.split("=")
                queries[k] = v
        if self.path.startswith("/api/") and launcher_path is not None:
            response = {"ok": False}
            headers = {}
            headers["Content-Type"] = "text/json"
            if "/api/get.aliases" == self.path:
                response["ok"] = True
                response["aliases"] = aliases
                pass
            elif "/api/get.launcher" == self.path:
                response["ok"] = True
                response["path"] = launcher_path
                pass
            elif "/api/get.config.dict" == self.path:
                with pushd(os.path.dirname(launcher_path)):
                    if "path" in queries and os.path.exists(queries["path"]):
                        response["ok"] = True
                        config = get_config_dict(queries["path"])
                        # #todo: deal with functions.
                        response["dict"] = {**config}
                    else:
                        response["ok"] = False
                        response["error"] = "invalid path"
            elif "/api/get.configs" == self.path:
                response["ok"] = True
                response["configs"] = list(configs)
            else:
                self.send_response(404)
                for k, v in headers.items():
                    self.send_header(k, v)
                response["error"] = "api call not found "+self.path
                self.end_headers()
                self.wfile.write(bytes(json.dumps(response), "utf-8"))
                return

            self.send_response(200)
            for k, v in headers.items():
                self.send_header(k, v)
            self.end_headers()
            self.wfile.write(bytes(json.dumps(response), "utf-8"))
            return

        in_path = self.translate_path(self.path)
        in_path = os.path.relpath(in_path, self.directory)
        if in_path in whitelist:
            SimpleHTTPRequestHandler.do_GET(self)
        else:
            self.send_response(404)
            self.end_headers()
        pass
예제 #43
0
 def do_GET(self):
     # self.path = 'dist/' + self.path
     SimpleHTTPRequestHandler.do_GET(self)
예제 #44
0
파일: server.py 프로젝트: Ge-lx/tomato-cam
 def do_FILE(self, path):
     self.path = path
     return ReqHandler.do_GET(self)
예제 #45
0
def takeVideo(self):
    SimpleHTTPRequestHandler.do_GET(self)
예제 #46
0
 def do_GET(self):
     SimpleHTTPRequestHandler.do_GET(self)
예제 #47
0
	def do_GET(self):
		# List of pages.
		pages = ['home', 'add', 'datasets', 'detector']

		# Homepage on root.
		if self.path == '/':
			self.path = '/home'

		# Selected page.
		page = self.path.split('/')[1]

		# Check if the current request is a page.
		if page in pages:
			# Get the response page template.
			lookup = TemplateLookup(directories=['templates/'])
			template = lookup.get_template(page + '.mako')

			# Set the response page headers.
			self.send_response(200)
			self.send_header('Content-Type', 'text/html; charset=utf-8')
			self.end_headers()

			# Page specific fields.
			fields = {}

			if page == 'datasets':
				# Datasets page, get the list of datasets.
				fields['datasets'] = getAllDatasets()
			elif page == 'detector':
				# Detector page, get the dataset id.
				datasetId = self.path.split('/')[2]

				# Get the dataset name.
				name = getDatasetName(datasetId)

				# Add the name to the fields.
				fields['name'] = name

				# Open the dataset.
				with open('uploads/' + datasetId + '.csv', 'r') as file:
					# Read the CSV column names.
					columnIdsLine = file.readline().rstrip()
					columnIds = columnIdsLine.split(',')

					# Make a dictonary for the column names.
					columnNames = {}

					# Get the column names.
					allFields = getFields()
					category = ''

					# Get the descriptions for the columns.
					for field in allFields:
						if field['isCategory'] == '1':
							category = field['description']
						elif field['id'] in columnIds:
							label = ''

							if category != '':
								label += category + ' - '

							label += field['description']

							columnNames[field['id']] = label
					
					# Add the column names to the fields.
					fields['columns'] = columnNames

			# Render the response page template.
			self.wfile.write(bytes(template.render(fields=fields), 'utf-8'))

			# Get response is ready.
			return

		# Else, give back the file from the public folder.
		self.path = 'public' + self.path
		return SimpleHTTPRequestHandler.do_GET(self)
예제 #48
0
    def do_GET(self):
        """
        Handle GET request
        """
        config = configparser.ConfigParser()
        config.read('config.ini')

        consumer_key = config['APP']['XERO_CONSUMER_KEY']
        consumer_secret = config['APP']['XERO_CONSUMER_SECRET']
        callback_url = config['APP']['CALLBACK_URL']
        accounts_and_vendors_files_path = config['APP'][
            'ACCOUNTS_AND_VENDORS_FILES_PATH']
        vendors_file_name = config['APP']['VENDORS_FILE_NAME']
        accounts_file_name = config['APP']['ACCOUNTS_FILE_NAME']

        if consumer_key is None or consumer_secret is None:
            raise KeyError(
                'Please define both XERO_CONSUMER_KEY and XERO_CONSUMER_SECRET variables in config.ini file'
            )

        if callback_url is None:
            raise KeyError('Please define callback_url in config.ini file')

        if accounts_and_vendors_files_path is None or vendors_file_name is None or vendors_file_name is None:
            raise KeyError(
                'Please define Account and Vendors file names and paths in config.ini file'
            )

        print("Serving path: {}".format(self.path))
        path = urlparse(self.path)

        if path.path == '/do-auth':
            credentials = PublicCredentials(consumer_key,
                                            consumer_secret,
                                            callback_uri=callback_url)

            # Save generated credentials details to persistent storage
            for key, value in credentials.state.items():
                OAUTH_PERSISTENT_SERVER_STORAGE.update({key: value})

            # Redirect to Xero at url provided by credentials generation
            self.redirect_response(credentials.url)
            return

        elif path.path == '/oauth':
            params = dict(parse_qsl(path.query))
            if 'oauth_token' not in params or 'oauth_verifier' not in params or 'org' not in params:
                self.send_error(500, message='Missing parameters required.')
                return

            stored_values = OAUTH_PERSISTENT_SERVER_STORAGE
            credentials = PublicCredentials(**stored_values)

            try:
                credentials.verify(params['oauth_verifier'])

                # Resave our verified credentials
                for key, value in credentials.state.items():
                    OAUTH_PERSISTENT_SERVER_STORAGE.update({key: value})

            except XeroException as e:
                self.send_error(500,
                                message='{}: {}'.format(
                                    e.__class__, e.message))
                return

            # Once verified, api can be invoked with xero = Xero(credentials)
            self.redirect_response('/verified')
            return

        elif path.path == '/verified':
            stored_values = OAUTH_PERSISTENT_SERVER_STORAGE
            credentials = PublicCredentials(**stored_values)

            try:
                xero = Xero(credentials)

            except XeroException as e:
                self.send_error(500,
                                message='{}: {}'.format(
                                    e.__class__, e.message))
                return

            page_body = ''

            vendors = xero.contacts.filter(IsSupplier=True)
            accounts = xero.accounts.all()

            if vendors:
                vendors_file = accounts_and_vendors_files_path + '/' + vendors_file_name
                with open(vendors_file, 'w') as fileVendors:
                    json.dump(vendors,
                              fileVendors,
                              indent=4,
                              sort_keys=True,
                              default=str)
                page_body += ('Check vendors list in ' +
                              accounts_and_vendors_files_path + '/' +
                              vendors_file_name + '<br>')
            else:
                page_body += 'No vendors.\n'

            if accounts:
                accounts_file = accounts_and_vendors_files_path + '/' + accounts_file_name
                with open(accounts_file, 'w') as fileAccounts:
                    json.dump(accounts,
                              fileAccounts,
                              indent=4,
                              sort_keys=True,
                              default=str)
                    page_body += ('Check account list in ' +
                                  accounts_and_vendors_files_path + '/' +
                                  accounts_file_name)
            else:
                page_body += 'No accounts.\n'

            self.page_response(title='Downloading vendor and account files',
                               body=page_body)
            return

        SimpleHTTPRequestHandler.do_GET(self)
예제 #49
0
    def do_GET(self):
        if ('/index.html' in self.path) or (self.path == '/' in self.path):
            data_banco = self.node.get_data('cadastro', '*', 'data_cadastro = (select max(data_cadastro) from cadastro)')[0]
            #datatime(year, month, day, hour, minute, second, microsecond)

            f = self.send_head_custom()
            if f:
                aux= f.read()
                aux= array('B',struct.unpack('B'*len(aux),aux))
                #aux = str(f.read(), 'utf-8').strip('\'b')
                #print(aux)

                colunas = []
                linha =[]

                if data_banco[7] != None:
                    colunas.append('Modo')
                    if data_banco[7] == 1:
                        linha.append('Horário e intervalo de irrigação')
                    if data_banco[7] == 2:
                        linha.append('Umidade mínima e máxima')
                    if data_banco[7] == 3:
                        linha.append('Umidade mínima e intervalo de irrigação')
                    if data_banco[7] == 4:
                        linha.append('Temperatura mínima e máxima')
                    if data_banco[7] == 5:
                        linha.append('Temperatura máxima e intervalo de irrigação')
                    if data_banco[7] == 6:
                        linha.append('Umidade e Temperatura')
                if data_banco[1] != None:
                    colunas.append('Data de Cadastro')
                    string = data_banco[1].strftime('%d %b,%Y %H:%M')
                    linha.append(string)
                if data_banco[8] != None:
                    colunas.append('Horário de Irrigação')
                    hora = int(data_banco[8]/60)
                    minutos = data_banco[8]%60
                    linha.append(str(hora) + ":" + str(minutos))
                if data_banco[2] != None:
                    colunas.append('Intervalo de Irrigação')
                    linha.append(data_banco[2])
                if data_banco[3] != None:
                    colunas.append('Umidade Mínima')
                    linha.append(data_banco[3])
                if data_banco[4] != None:
                    colunas.append('Umidade Máxima')
                    linha.append(data_banco[4])
                if data_banco[5] != None:
                    colunas.append('Temperatura Mínima')
                    linha.append(data_banco[5])
                if data_banco[6] != None:
                    colunas.append('Temperatura Máxima')
                    linha.append(data_banco[6])

                html = '<table class=\"table\"><thead><tr>'
                for coluna in colunas:
                    html += '<th scope=\"col\">' + str(coluna) + '</th>'
                html += '</tr></thead><tbody><tr>'
                for l in linha:
                    html += '<td>'+str(l)+'</td>'
                html += '</tr></tbody></table>'

                html= html.encode('utf-8')
                to_format= array('B',struct.unpack('B'*len(html),html))

                idx = aux.index(123)
                while idx < len(aux):
                    if aux[idx+1]==123 and aux[idx+2]==125 and aux[idx+3]==125:
                        aux= aux[:idx]+to_format+aux[idx+4:]
                        break
                    idx += aux[idx+1:].index(123)
                #aux = aux.format(*to_format)
                self.send_header("Content-Length", len(aux))
                self.end_headers()
                self.wfile.write(aux)
                f.close()
        else:
            SimpleHTTPRequestHandler.do_GET(self)
예제 #50
0
 def do_GET(self):
     if self.pre_check():
         SimpleHTTPRequestHandler.do_GET(self)
예제 #51
0
 def do_GET(self):
     logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path),
                  str(self.headers))
     SimpleHTTPRequestHandler.do_GET(self)
예제 #52
0
 def do_GET(self):
     SimpleHTTPRequestHandler.do_GET(self)
     self.delete_temp_files()
예제 #53
0
    def do_GET(self):
        """
        Handles the browser access (GET requests).
        """
        client_host, client_port, is_ipv6 = \
            RequestHandler._get_client_host_port(self.client_address)
        self.auth_session = self.__check_session_cookie()
        username = self.auth_session.user if self.auth_session else 'Anonymous'
        LOG.debug("%s:%s -- [%s] GET %s",
                  client_host if not is_ipv6 else '[' + client_host + ']',
                  client_port, username, self.path)

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

        if self.path == '/live':
            self.__handle_liveness()
            return

        if self.path == '/ready':
            self.__handle_readiness()
            return

        if self.server.manager.is_enabled and not self.auth_session \
                and routing.is_protected_GET_entrypoint(path):
            # If necessary, prompt the user for authentication.
            returnto = '?returnto=' + \
                urllib.parse.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(b'')
            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 '%s' does not exist.",
                         product_endpoint)
                self.send_error(
                    404,
                    "The product {0} does not exist.".format(product_endpoint))
                return

            # 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 '%s' is not connected! "
                    "Attempting reconnect...", 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.__has_access_permission(product):
                LOG.warning(
                    "User '%s' does not have permission to access "
                    "the '%s' product.", username, product_endpoint)

                self.send_response(307)  # 307 Temporary Redirect
                self.send_header('Location', '/products.html')
                self.send_header('Connection', 'close')
                self.end_headers()
                self.wfile.write(b'')
                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.info("Redirecting user from /%s to /%s/index.html",
                         product_endpoint, 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.info("Redirecting '/' to ONLY product '/%s'",
                                 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.error("ONLY product '/%s' has database issues...",
                                  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'

            self.send_response(200)  # 200 OK

        SimpleHTTPRequestHandler.do_GET(self)  # Actual serving of file.
예제 #54
0
 def do_GET(self):
     if self.only_upgrade:
         self.send_error(405, "Method Not Allowed")
     else:
         SimpleHTTPRequestHandler.do_GET(self)
예제 #55
0
    def do_GET(self):
        url = urlparse(self.path)
        if url.path.endswith('.html'):
            SimpleHTTPRequestHandler.do_GET(self)
            return

        tables = Base.metadata.tables
        table_name = url.path[1:]

        if table_name in tables.keys():
            database = tables[table_name]
        else:
            self.send_response(404)
            return

        # here, so as not to override __init__
        # pylint: disable=W0201
        self.queries = {}
        if url.query:
            self.queries = parse_qs(url.query)

        self.send_headers()

        # here, so as not to override __init__
        # pylint: disable=W0201
        self.deltas = { \
            'minutes_ago':  minutes_ago, \
            'hours_ago':    hours_ago, \
            'days_ago':     days_ago, \
            'weeks_ago':    weeks_ago, \
            'months_ago':   months_ago, \
            'years_ago':    years_ago \
        }

        if table_name == 'connections' and 'geoip' in self.queries:
            self.geoip()
            return
        elif 'chartjs' in self.queries:
            self.chartjs(table_name)
            return
        elif 'passwords' in self.queries:
            self.get_top_passwords()
            return
        elif 'usernames' in self.queries:
            self.get_top_usernames()
            return
        elif 'attacks' in self.queries:
            self.get_daily_attacks()
            return

        query = select([database])

        for delta in self.deltas:
            if delta in self.queries:
                diff = int(self.queries[delta][0])
                query = session.query(database).join(Connections) \
                    .filter(Connections.created_at > self.deltas[delta](diff))
                break

        results = session.execute(query)

        if 'handd' in self.queries:
            self.header_and_data(database, results)
            return

        dump = json.dumps([dict(r) for r in results], default=alchemyencoder)

        # JSONP
        if 'callback' in self.queries:
            self.wfile.write(self.queries['callback'][0].encode() + b'(')
            self.wfile.write(dump[1:-1].encode())
            self.wfile.write(b')')
        else:
            self.wfile.write(dump.encode())
예제 #56
0
 def do_GET(self):
     logging.error(self.headers)
     SimpleHTTPRequestHandler.do_GET(self)
예제 #57
0
 def do_GET(self):
     try:
         SimpleHTTPRequestHandler.do_GET(self)
     except Exception as e:
         self.handle_exception(e)
예제 #58
0
 def do_GET(self):
     if self.path != '/cam':
         return SimpleHTTPRequestHandler.do_GET(self)
     self.serving = True
예제 #59
0
 def serve(self, http_handler, page: dict, config: dict, site: KartDict,
           map: KartMap):
     http_handler.path = self.base_url + http_handler.path
     return SimpleHTTPRequestHandler.do_GET(http_handler)
예제 #60
0
    def do_GET(self):
        """
        Handle GET request
        """
        consumer_key = os.environ.get('XERO_CONSUMER_KEY')
        consumer_secret = os.environ.get('XERO_CONSUMER_SECRET')

        if consumer_key is None or consumer_secret is None:
            raise KeyError(
                'Please define both XERO_CONSUMER_KEY and XERO_CONSUMER_SECRET environment variables'
            )

        print("Serving path: {}".format(self.path))
        path = urlparse(self.path)

        if path.path == '/do-auth':
            credentials = PublicCredentials(
                consumer_key,
                consumer_secret,
                callback_uri='http://localhost:8000/oauth')

            # Save generated credentials details to persistent storage
            for key, value in credentials.state.items():
                OAUTH_PERSISTENT_SERVER_STORAGE.update({key: value})

            # Redirect to Xero at url provided by credentials generation
            self.redirect_response(credentials.url)
            return

        elif path.path == '/oauth':
            params = dict(parse_qsl(path.query))
            if 'oauth_token' not in params or 'oauth_verifier' not in params or 'org' not in params:
                self.send_error(500, message='Missing parameters required.')
                return

            stored_values = OAUTH_PERSISTENT_SERVER_STORAGE
            credentials = PublicCredentials(**stored_values)

            try:
                credentials.verify(params['oauth_verifier'])

                # Resave our verified credentials
                for key, value in credentials.state.items():
                    OAUTH_PERSISTENT_SERVER_STORAGE.update({key: value})

            except XeroException as e:
                self.send_error(500,
                                message='{}: {}'.format(
                                    e.__class__, e.message))
                return

            # Once verified, api can be invoked with xero = Xero(credentials)
            self.redirect_response('/verified')
            return

        elif path.path == '/verified':
            stored_values = OAUTH_PERSISTENT_SERVER_STORAGE
            credentials = PublicCredentials(**stored_values)

            try:
                xero = Xero(credentials)

            except XeroException as e:
                self.send_error(500,
                                message='{}: {}'.format(
                                    e.__class__, e.message))
                return

            page_body = 'Your contacts:<br><br>'

            contacts = xero.contacts.all()

            if contacts:
                page_body += '<br>'.join(
                    [str(contact) for contact in contacts])
            else:
                page_body += 'No contacts'
            self.page_response(title='Xero Contacts', body=page_body)
            return

        SimpleHTTPRequestHandler.do_GET(self)