Example #1
0
    def _serve_tiles(self, request):
        tile_config = request.path[len("/data/plugin/WSI/tiles/"):].split("/")

        id = int(tile_config[0])

        if id == self._cache_slide_id:
            slide = self._cache_slide
        else:
            slide_path = self._cache_slide_prop[id]["slide_path"]
            slide = DeepZoomGenerator(open_slide(slide_path))
            self._cache_slide = slide
            self._cache_slide_id = id

        if len(tile_config) <= 2:
            response = werkzeug.Response(slide.get_dzi("jpeg"))
            response.headers.set('Content-Type', 'application/xml')
            return response
        else:
            level, colrow = tile_config[1:]
            level = int(level)
            col, row = map(int, colrow[:-1 * len(".jpeg"):].split("_"))

            tile = slide.get_tile(level, (col, row))

            buf = PILBytesIO()
            tile.save(buf, "jpeg", quality=75)
            response = werkzeug.Response(buf.getvalue())
            response.headers.set('Content-Type', 'image/jpeg')
            return response
Example #2
0
    def _new_window(self, request):
        """Create a new WebRTC window on request."""
        if not self.data_reader.is_active():  # no data
            response = json.dumps({"window_id": -1, "logdir": self._logdir})
            return werkzeug.Response(response,
                                     content_type="application/json",
                                     headers=self._HEADERS)

        if self._gui is None:
            self._start_gui()

        win_width = min(3840,
                        max(640, int(float(request.args.get('width', 1024)))))
        win_height = min(2400,
                         max(480, int(float(request.args.get('height', 768)))))

        this_window = Open3DPluginWindow(self.data_reader,
                                         "Open3D for Tensorboard", win_width,
                                         win_height)
        with self.window_lock:
            self._windows[this_window.window.uid] = this_window

        response = json.dumps({
            "window_id": this_window.window.uid,
            "logdir": self._logdir
        })
        this_window.init_done.wait()  # Wait for WebRTC initialization
        return werkzeug.Response(response,
                                 content_type="application/json",
                                 headers=self._HEADERS)
Example #3
0
def _json_response(data, status=200):
    if data is None:
        return werkzeug.Response(status=status)
    else:
        data = json.dumps(data, indent=2) + "\n"
        return werkzeug.Response(data,
                                 status=status,
                                 mimetype="application/json")
    def git(self, request, repo, **kw):
        self.authorize(request)
        if not request.env.uid or request.env.user.login == 'public':
            return werkzeug.Response(headers=[('WWW-Authenticate', 'Basic')],
                                     status=401)

        try:
            repository = request.env['galicea_git.repository'].search([
                ('system_name', '=', repo)
            ])
        except AccessError:
            return werkzeug.Response(status=403)
        if not repository.exists():
            return werkzeug.Response(status=404)

        http_environment = request.httprequest.environ
        git_env = {
            'REQUEST_METHOD': http_environment['REQUEST_METHOD'],
            'QUERY_STRING': http_environment['QUERY_STRING'],
            'CONTENT_TYPE': request.httprequest.headers.get('Content-Type'),
            'REMOTE_ADDR': http_environment['REMOTE_ADDR'],
            'GIT_PROJECT_ROOT': os.path.join(config['data_dir'], 'git'),
            'GIT_HTTP_EXPORT_ALL': '1',
            'PATH_INFO': http_environment['PATH_INFO'][4:],
            'REMOTE_USER': request.env.user.login
        }

        command_env = os.environ.copy()
        for var in git_env:
            command_env[var] = git_env[var]

        git = subprocess.Popen(['/usr/lib/git-core/git-http-backend'],
                               stdin=subprocess.PIPE,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE,
                               env=command_env,
                               shell=True)
        stdout, stderr = git.communicate(http_input_stream(request).read())
        headers_str, body = stdout.split(b"\r\n\r\n", 2)

        http_status_code = 200
        headers = []
        for header in headers_str.split(b"\r\n"):
            name, value = header.split(b': ', 2)
            if name == 'Status':
                http_code = int(value.split(b' ')[0])
            else:
                headers.append((name.decode('ascii'), value.decode('ascii')))

        return werkzeug.Response(body,
                                 status=http_status_code,
                                 headers=headers)
def openlayers(req, path='ol_merc.html'):
    global html
    if not html:
        try:
            f = open(path, 'rb')
            html = f.read()
            f.close()
        except IOError:
            return z.Response('Openlayers HTML/JS file not found: %s' % path,
                              status=404,
                              mimetype='text/html')

    return z.Response(html, status=200, mimetype='text/html')
Example #6
0
 def wrapper(self, *args, **kwargs):
     data = method(self, *args, **kwargs)
     s = simplejson.dumps(data, default=jsonconverter)
     if self.request.args.has_key("callback"):
         callback = self.request.args.get("callback")
         s = "%s(%s)" % (callback, s)
         response = werkzeug.Response(s)
         response.content_type = "application/javascript"
     else:
         response = werkzeug.Response(s)
         response.content_type = "application/json"
     for a, v in that.headers.items():
         response.headers[a] = v
     return response
Example #7
0
    def trace_route(self, request):
        name = request.args.get("run")
        worker = request.args.get("worker")

        run = self.get_run(name)
        profile = run.get_profile(worker)
        fopen = open
        with fopen(profile.trace_file_path, 'rb') as f:
            raw_data = f.read()
        if profile.trace_file_path.endswith('.gz'):
            headers = []
            headers.append(('Content-Encoding', 'gzip'))
            return werkzeug.Response(raw_data, content_type="application/json", headers=headers)
        else:
            return werkzeug.Response(raw_data, content_type="application/json")
def get_resource(request, filename):
    """Return a static resource from the js folder."""
    if not filename:
        return z.Response('Not Found no filename', status=404)
    else:
        filename = os.path.join(os.path.dirname(__file__), 'js', filename)

    if os.path.isfile(filename):
        mimetype = guess_type(filename)[0] or 'application/octet-stream'
        f = file(filename, 'rb')
        try:
            return z.Response(f.read(), mimetype=mimetype)
        finally:
            f.close()
    return z.Response('Not Found: %s' % filename, status=404)
Example #9
0
 def _serve_view(self, request):
     filename = request.args.get("file")
     filepath = os.path.join(os.path.dirname(__file__), "static", filename)
     with open(filepath) as infile:
         contents = infile.read()
     return werkzeug.Response(contents,
                              content_type="application/javascript")
Example #10
0
    def _serve_slide_prop(self, request):
        run = request.args.get("run")
        tag = request.args.get("tag")
        runtag = run + tag
        if runtag in self._ids:
            id = self._ids[runtag]
            slide_mpp = self._cache_slide_prop[id]["slide_mpp"]
        else:
            if run is None or tag is None:
                raise werkzeug.exceptions.BadRequest("Must specify run and tag")
            try:
                slide_path = [
                    tensor_util.make_ndarray(event.tensor_proto)
                        .item()
                        .decode("utf-8")
                    for event in self._multiplexer.Tensors(run, tag)
                ][-1]
            except KeyError:
                raise werkzeug.exceptions.BadRequest("Invalid run or tag")

            try:
                slide = open_slide(slide_path)
                mpp_x = slide.properties[openslide.PROPERTY_NAME_MPP_X]
                mpp_y = slide.properties[openslide.PROPERTY_NAME_MPP_Y]
                slide_mpp = (float(mpp_x) + float(mpp_y)) / 2
            except (KeyError, ValueError):
                slide_mpp = 0

            id = len(self._cache_slide_prop)
            self._ids[runtag] = id
            self._cache_slide_prop.append({"slide_path": slide_path, "slide_mpp": slide_mpp})

        data = {"id": id, "mpp": slide_mpp}
        contents = json.dumps(data, sort_keys=True)
        return werkzeug.Response(contents, content_type="application/json")
Example #11
0
    def __call__(self, environ, start_response):
        if self.urlmap is None:
            raise NotImplementedError('Please provide urlmap')

        urls = self.urlmap.bind_to_environ(environ)
        self.logger.debug(self.__class__.__name__ + ': handling request')
        res = None
        try:
            endpoint, kwargs = urls.match()

            res = getattr(self, 'subapp_' + endpoint, None)
            if res is not None:
                utils.pop_path(environ)
                return res(environ, start_response)

            res = getattr(self, 'app_' + endpoint, None)
            if res is not None:
                return res(environ, start_response)

            attr = getattr(self, 'respond_' + endpoint, None)
            if attr is not None:
                res = attr(werkzeug.Request(environ), **kwargs)
                return res(environ, start_response)

        except werkexc.NotFound, exc:
            tmpl = self.templates.get_template('404.html')
            req = werkzeug.Request(environ)
            res = werkzeug.Response(tmpl.render(exc=exc,
                                                url_root=req.url_root,
                                                version=__version__),
                                    content_type='text/html; charset=UTF-8',
                                    status=404)
            return res(environ, start_response)
Example #12
0
    def _serve_js(self, request):
        """Serve frontend JS files on request."""
        if request.is_multiprocess:
            return werkzeug.exceptions.ExpectationFailed(
                "Open3D plugin does not run on a multi-process web server.",
                response=self._ERROR_RESPONSE)

        js_file = request.path.split('/')[-1]
        if js_file == "index.js":
            js_file = os.path.join(os.path.dirname(__file__), "frontend",
                                   js_file)
        elif js_file == "webrtcstreamer.js":
            js_file = os.path.join(self._RESOURCE_PATH, "html", js_file)
        elif js_file == "adapter.min.js":
            js_file = os.path.join(self._RESOURCE_PATH, "html", "libs",
                                   js_file)
        else:
            raise werkzeug.exceptions.NotFound(
                description=f"JS file {request.path} does not exist.",
                response=self._ERROR_RESPONSE)

        with open(js_file) as infile:
            return werkzeug.Response(infile.read(),
                                     content_type="application/javascript",
                                     headers=self._HEADERS)
Example #13
0
    def _serve_greetings(self, request):
        """Serves greeting data for the specified tag and run.

        For details on how to use tags and runs, see
        https://github.com/tensorflow/tensorboard#tags-giving-names-to-data
        """
        run = request.args.get("run")
        tag = request.args.get("tag")
        ctx = plugin_util.context(request.environ)
        experiment = plugin_util.experiment_id(request.environ)

        if run is None or tag is None:
            raise werkzeug.exceptions.BadRequest("Must specify run and tag")
        read_result = self.data_provider.read_tensors(
            ctx,
            downsample=1000,
            plugin_name=metadata.PLUGIN_NAME,
            experiment_id=experiment,
            run_tag_filter=provider.RunTagFilter(runs=[run], tags=[tag]),
        )

        data = read_result.get(run, {}).get(tag, [])
        if not data:
            raise werkzeug.exceptions.BadRequest("Invalid run or tag")
        event_data = [datum.numpy.item().decode("utf-8") for datum in data]

        contents = json.dumps(event_data, sort_keys=True)
        return werkzeug.Response(contents, content_type="application/json")
Example #14
0
 def _serve_css(self, unused_request):
     with open(
             os.path.join(os.path.dirname(__file__), "frontend",
                          "style.css")) as cssfile:
         return werkzeug.Response(cssfile.read(),
                                  content_type="text/css",
                                  headers=self._HEADERS)
Example #15
0
    def trace_route(self, request):
        profile = self._get_profile_for_request(request)

        if not profile.has_kernel:  # Pure CPU.
            raw_data = self._cache.read(profile.trace_file_path)
            if not profile.trace_file_path.endswith('.gz'):
                raw_data = gzip.compress(raw_data, 1)
        else:
            file_with_gpu_metrics = self._gpu_metrics_file_dict.get(
                profile.trace_file_path)
            if file_with_gpu_metrics:
                raw_data = io.read(file_with_gpu_metrics)
            else:
                raw_data = self._cache.read(profile.trace_file_path)
                if profile.trace_file_path.endswith('.gz'):
                    raw_data = gzip.decompress(raw_data)
                raw_data = profile.append_gpu_metrics(raw_data)

                # write the data to temp file
                fp = tempfile.NamedTemporaryFile('w+b',
                                                 suffix='.json.gz',
                                                 delete=False)
                fp.close()
                # Already compressed, no need to gzip.open
                with open(fp.name, mode='wb') as file:
                    file.write(raw_data)
                self._gpu_metrics_file_dict[profile.trace_file_path] = fp.name

        headers = [('Content-Encoding', 'gzip')]
        headers.extend(TorchProfilerPlugin.headers)
        return werkzeug.Response(raw_data,
                                 content_type="application/json",
                                 headers=headers)
Example #16
0
def upload_complete(digest: str) -> typing.Union[werkzeug.Response,
                                                 typing.Tuple[str, int]]:

    if not tooltool_api.utils.is_valid_sha512(digest):
        raise werkzeug.exceptions.BadRequest('Invalid sha512 digest')

    # if the pending upload is still valid, then we can't check this file
    # yet, so return 409 Conflict.  If there is no PU, or it's expired,
    # then we can proceed.
    file = tooltool_api.models.File.query.filter(tooltool_api.models.File.sha512 == digest).first()
    if file:
        for pending_upload in file.pending_uploads:
            until = pending_upload.expires.replace(tzinfo=pytz.UTC) - tooltool_api.utils.now()
            if until > datetime.timedelta(0):
                # add 1 second to avoid rounding / skew errors
                headers = {'X-Retry-After': str(1 + int(until.total_seconds()))}
                return werkzeug.Response(status=409, headers=headers)

    exchange = f'exchange/{flask.current_app.config["PULSE_USER"]}/{tooltool_api.config.PROJECT_NAME}'
    logger.info(f'Sending digest `{digest}` to queue `{exchange}` for route `{tooltool_api.config.PULSE_ROUTE_CHECK_FILE_PENDING_UPLOADS}`.')
    try:
        flask.current_app.pulse.publish(
            exchange,
            tooltool_api.config.PULSE_ROUTE_CHECK_FILE_PENDING_UPLOADS,
            dict(digest=digest),
        )
    except Exception as e:
        import traceback
        msg = 'Can\'t send notification to pulse.'
        trace = traceback.format_exc()
        logger.error(f'{msg}\nException:{e}\nTraceback: {trace}')

    return '{}', 202
Example #17
0
 def wrapper(*args, **kwargs):
     try:
         # is login?
         uid = get_session_uid()
         username = ext_user_id(uid)
         if not username:
             raise Exception(
                 'login expected',
                 'invalid_request',
             )
         if userclass == 'admin':
             config.read("conf/api.ini")
             ok = config['users']['admin'].find(username) >= 0
             if not ok:
                 raise Exception(
                     'login incorrect',
                     'protected zone',
                 )
         response = endpoint(*args, **kwargs)
         return response
     except Exception as e:
         error_message = "error: {0}".format(e)
         return werkzeug.Response(
             response=json.dumps({
                 'error': 'access error',
                 'error_message': error_message
             }),
             status=400,
             headers={}  #cors_headers
         )
Example #18
0
    def _webrtc_http_api(self, request):
        """Relay WebRTC connection setup messages coming as HTTP requests."""
        try:
            entry_point = request.path[(len(self._PLUGIN_DIRECTORY_PATH_PART) -
                                        1):]
            query_string = (b'?' + request.query_string
                            if request.query_string else b'')
            data = request.get_data()
            if len(self._windows) == 0:
                raise werkzeug.exceptions.BadRequest(
                    description="No windows exist to service this request: "
                    f"{request}",
                    response=self._ERROR_RESPONSE)

            with self._http_api_lock:
                response = webrtc_server.call_http_api(entry_point,
                                                       query_string, data)

        except RuntimeError:
            raise werkzeug.exceptions.BadRequest(
                description="Request is not a function call, ignored: "
                f"{request}",
                response=self._ERROR_RESPONSE)
        else:
            return werkzeug.Response(response,
                                     content_type="application/json",
                                     headers=self._HEADERS)
Example #19
0
 def _serve_wit(self, request):
     del request  # unused
     filepath = os.path.join(os.path.dirname(__file__), "static",
                             "wit_tb_bin.html")
     with open(filepath) as infile:
         contents = infile.read()
     return werkzeug.Response(contents, content_type="text/html")
Example #20
0
    def _serve_page(cls):
        req_page = request.httprequest.path
        page_domain = [('url', '=', req_page)
                       ] + request.website.website_domain()

        published_domain = page_domain
        # specific page first
        page = request.env['website.page'].sudo().search(
            published_domain, order='website_id asc', limit=1)

        if page:
            # prefetch all menus (it will prefetch website.page too)
            request.website.menu_id

        if page and (request.website.is_publisher() or page.is_visible):
            need_to_cache = False
            cache_key = page._get_cache_key(request)
            if (page.cache_time  # cache > 0
                    and request.httprequest.method == "GET" and request.env.
                    user._is_public()  # only cache for unlogged user
                    and 'nocache'
                    not in request.params  # allow bypass cache / debug
                    and not request.session.debug and len(cache_key)
                    and cache_key[-1] is not None  # nocache via expr
                ):
                need_to_cache = True
                try:
                    r = page._get_cache_response(cache_key)
                    if r['time'] + page.cache_time > time.time():
                        response = werkzeug.Response(r['content'],
                                                     mimetype=r['contenttype'])
                        response._cached_template = r['template']
                        response._cached_page = page
                        return response
                except KeyError:
                    pass

            _, ext = os.path.splitext(req_page)
            response = request.render(page.view_id.id, {
                'deletable': True,
                'main_object': page,
            },
                                      mimetype=_guess_mimetype(ext))

            if need_to_cache and response.status_code == 200:
                r = response.render()
                page._set_cache_response(
                    cache_key, {
                        'content':
                        r,
                        'contenttype':
                        response.headers['Content-Type'],
                        'time':
                        time.time(),
                        'template':
                        getattr(response, 'qcontext',
                                {}).get('response_template')
                    })
            return response
        return False
Example #21
0
 def _response(self, headers, body, status=200):
     try:
         fixed_headers = {str(k): v for k, v in headers.items()}
     except:
         fixed_headers = headers
     response = werkzeug.Response(response=body, status=status, headers=fixed_headers)
     return response
Example #22
0
 def _forward_post(self, url_path, proxy_info, model_inst, params):
     """The CMIS Browser binding is designed to be queried from the browser
     Therefore, the parameters in a POST are expected to be submitted as
     HTTP multipart forms. Therefore each parameter in the request is
     forwarded as a part of a multipart/form-data.
     :return: :class:`Response <Response>` object
     :rtype: werkzeug.Response
     """
     files = {}
     if 'content' in params:
         # we are in a mulitpart form data'
         content = params.pop('content')
         files['content'] = (content.filename, content.stream,
                             content.mimetype)
     for k, v in params.iteritems():
         # no filename for parts dedicated to HTTP Form data
         files[k] = (None, v, 'text/plain;charset=utf-8')
     url = self._get_redirect_url(proxy_info, url_path)
     r = requests.post(url,
                       files=files,
                       auth=(proxy_info['username'],
                             proxy_info['password']))
     r.raise_for_status()
     if r.text:
         return self._prepare_json_response(r.json(),
                                            dict(r.headers.items()),
                                            proxy_info, model_inst)
     else:
         response = werkzeug.Response()
     return response
Example #23
0
 def _run(self, *args):
     try:
         stdout = subprocess.check_output(*args, stderr=subprocess.STDOUT)
     except subprocess.CalledProcessError as e:
         raise werkzeug.exceptions.InternalServerError(e.stdout)
     else:
         return werkzeug.Response(json.dumps({"output": stdout.decode()}),
                                  200, {"Content-Type": "application/json"})
Example #24
0
 def func(*args, **kwargs):
     values = f(*args, **kwargs)
     try:
         values.update({u'request': args[0]})
     except (TypeError, AttributeError):
         return values
     body = env.get_template(template_name).render(values)
     return wz.Response(body, mimetype=mimetype)
Example #25
0
 def setUp(self):
     super(EmptyPathRedirectMiddlewareTest, self).setUp()
     app = werkzeug.Request.application(
         lambda req: werkzeug.Response(req.path))
     app = empty_path_redirect.EmptyPathRedirectMiddleware(app)
     app = self._lax_strip_foo_middleware(app)
     self.app = app
     self.server = werkzeug_test.Client(self.app, werkzeug.BaseResponse)
Example #26
0
    def respond_pypi_action(self, req):
        #remote_user = req.environ.get('REMOTE_USER', None)
        #if not remote_user:
        #    res = werkzeug.Response('Unauthorized', status=401)
        #    return res

        params = req.values.to_dict()
        params.update(req.files)
        action = params.pop(':action')

        try:
            self.pypi.perform_action(action, **params)
            res = werkzeug.Response(content_type='text/plain; charset=UTF-8')
            res.response = 'OK'
        except pypi.SecurityError, err:
            res = werkzeug.Response('Forbidden', 403)
            res.response = str(err)
Example #27
0
 def _serve_wit_js(self, request):
     del request  # unused
     filepath = os.path.join(os.path.dirname(__file__), "static",
                             "wit_tb_bin.js")
     with io.open(filepath, encoding='utf-8') as infile:
         contents = infile.read()
     return werkzeug.Response(contents,
                              content_type="application/javascript")
Example #28
0
 def _serve_js(self, request):
     del request  # unused
     filepath = os.path.join(os.path.dirname(__file__), "static", "index.js")
     with open(filepath) as infile:
         contents = infile.read()
     return werkzeug.Response(
         contents, content_type="application/javascript"
     )
Example #29
0
 def __redirect(self, url, params, response_mode):
     location = '{}{}{}'.format(url,
                                '?' if response_mode == 'query' else '#',
                                werkzeug.url_encode(params))
     return werkzeug.Response(
         headers={'Location': location},
         response=None,
         status=302,
     )
Example #30
0
 def static_file_route(self, request):
     filename = os.path.basename(request.path)
     extension = os.path.splitext(filename)[1]
     if extension == '.html':
         mimetype = 'text/html'
     elif extension == '.css':
         mimetype = 'text/css'
     elif extension == '.js':
         mimetype = 'application/javascript'
     else:
         mimetype = 'application/octet-stream'
     filepath = os.path.join(os.path.dirname(__file__), 'static', filename)
     try:
         with open(filepath, 'rb') as infile:
             contents = infile.read()
     except IOError:
         return werkzeug.Response('404 Not Found', 'text/plain', code=404)
     return werkzeug.Response(contents, content_type=mimetype)