Exemplo n.º 1
0
def app(environ, respond):
    print("request_uri=", util.request_uri(environ))

    if util.request_uri(environ).endswith("/request?cmd=reboot"):
        print("### reboot")
        os.system("sudo reboot")
        respond('200 OK', [('Content-Type', 'application/json; charset=utf-8')])
        return [json.dumps({'message':'reboot requested'}).encode("utf-8")]
    if util.request_uri(environ).endswith("/request?cmd=shutdown"):
        print("### shutdown")
        os.system("sudo shutdown -h now")
        respond('200 OK', [('Content-Type', 'application/json; charset=utf-8')])
        return [json.dumps({'message':'shutdown requested'}).encode("utf-8")]
    if util.request_uri(environ).endswith("/request?cmd=upgrade"):
        print("### upgrade")
        respond('200 OK', [('Content-Type', 'application/json; charset=utf-8')])
        os.system("git pull origin master")
        os.system("cd config && git pull origin master && cd ..")
        os.system("sudo reboot")
        return [json.dumps({'message':'upgrade requested'}).encode("utf-8")]

    name = environ['PATH_INFO'][1:]
    if name in filenames:
        fn = filenames[name]
    else:
        fn = filenames["index.html"]
    type = mimetypes.guess_type(fn)[0]
    if os.path.exists(fn):
        respond('200 OK', [('Content-Type', type)])
        return util.FileWrapper(open(fn, "rb"))
    else:
        respond('404 Not Found', [('Content-Type', 'text/plain')])
        return [b'not found']
Exemplo n.º 2
0
 def __iter__(self):
     self.request_date.url_path_info = util.shift_path_info(self.environ)
     self.start(self.request_date.route().status_code,
                self.request_date.get_headers())
     print(self.start)
     yield from util.FileWrapper(
         open(self.request_date.route().file_request, "rb"))
Exemplo n.º 3
0
    def dispatch_request(self, request):

        if request.path.startswith('/static'):
            fn = os.path.join(path, request.path[1:])
            if '.' not in fn.split(os.path.sep)[-1]:
                fn = os.path.join(fn, 'index.html')
            type = mimetypes.guess_type(fn)[0]

            if os.path.exists(fn):
                self.status = '200 OK'
                self.headers.add_header('Content-type', type)
                return util.FileWrapper(open(fn, "rb"))
            else:
                self.status = '404 Not Found'
                self.headers.add_header('Content-type', 'text/plain')
                return [b'not found']

        try:

            self.status = '200 OK'
            body = json.loads(request.body.decode('utf-8'))
            #rule = request.url_rule
            #return self.view_functions[rule.endpoint](**req.view_args)
            return body
        except Exception as e:
            self.status = '500 server error'
            return str(e)
Exemplo n.º 4
0
def application(environ, respond):

    print("arg", sys.argv)
    path = os.path.dirname(os.path.realpath(__file__))
    print("mypath", path)
    #printenv(environ)

    #print("path", environ['PATH_INFO'])
    #print("qqq", environ['QUERY_STRING'])

    print("pwd", os.getcwd())
    os.chdir(path)
    print("pwd", os.getcwd())

    #fn = os.path.join(path, environ['PATH_INFO'][1:])
    fn = environ['PATH_INFO'][1:]
    #print("Request:",  fn)

    # Empty file name, index wanted
    if (fn.split(os.path.sep)[-1] == ""):
        fn = os.path.join(fn, 'index.html')

    #print("Calc Request:",  fn)

    type = mimetypes.guess_type(fn)[0]
    if not type:
        type = "text/plain"

    if os.path.exists(fn):
        respond('200 OK', [('Content-Type', type + ';charset=UTF-8')])
        fp = util.FileWrapper(open(fn, "rb"))
        return fp
    else:
        respond('404 Not Found', [('Content-Type', 'text/plain')])
        return [b'not found']
Exemplo n.º 5
0
def app(environ, respond):

    fn = os.path.join(path, environ['PATH_INFO'][1:])
    if '.' not in fn.split(os.path.sep)[-1]:
        fn = os.path.join(fn, 'index.html')
    type = mimetypes.guess_type(fn)[0]

    if os.path.exists(fn):
        respond('200 OK', [('Content-Type', type)])
        return util.FileWrapper(open(fn, "rb"))
    else:
        respond('404 Not Found', [('Content-Type', 'text/plain')])
        return [b'not found']
Exemplo n.º 6
0
 def __call__(self, instance, environ, start_response):
     """Create Request, call thing, unwrap results and respond."""
     req = Request(environ, start_response, self.extra_props)
     body = self.app(instance, req)
     req.save_to_environ()
     if body is None:
         body = req.res.body
     if not req.start_response_called:
         req.start_response(req.res.status, req.res._headers, req.exc_info)
         req.start_response_called = True
     if isinstance(body, str):
         return [body]
     elif isiterable(body):
         return body
     else:
         return util.FileWrapper(body)
Exemplo n.º 7
0
def frontend(environ, respond):

    if 'css' in environ['PATH_INFO']:
        type = 'text/css'
        fn = os.path.join('templates/', environ['PATH_INFO'][1:])
        respond('200 OK', [('Content-Type', type)])
        return util.FileWrapper(open(fn, "rb"))

    env = Environment(loader=FileSystemLoader('templates/'))
    if environ['PATH_INFO'] == '/': 
        page_name = 'authorized.html' if environ['wsgi_authorised'] else 'register.html'

    if environ['PATH_INFO'] == '/login.html':
        page_name = 'authorized.html' if environ['wsgi_authorised'] else 'login.html'

    type = 'text/html'
    template = env.get_template(page_name)
    response = bytes(template.render(), 'utf-8')
    if 'session_id' in environ:
        respond('200 OK', [('Content-Type', type), ("set-cookie", "session_id" + "=" + str(environ['session_id']))])
    else:
        respond('200 OK', [('Content-Type', type)])
    return [response]
 def make_it(text=text, size=size):
     return util.FileWrapper(StringIO(text), size)
Exemplo n.º 9
0
 def test_filewrapper_getitem_deprecation(self):
     wrapper = util.FileWrapper(StringIO('foobar'), 3)
     with self.assertWarnsRegex(DeprecationWarning,
                                r'Use iterator protocol instead'):
         # This should have returned 'bar'.
         self.assertEqual(wrapper[1], 'foo')
Exemplo n.º 10
0
def handle_download_file_path(file_path, file_name, mime_type=''):
    file_obj = util.FileWrapper(open(file_path, "rb"))
    return handle_download(file_obj, file_name, mime_type)
Exemplo n.º 11
0
def sendfile(env, start_response):
    pprint.pprint(env)
    path = env["PATH_INFO"]
    start_response("200 OK", [("content-type", "text/plain"),
                              ("content-length", str(os.path.getsize(path)))])
    return util.FileWrapper(open(path, "rb"))