Пример #1
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)
Пример #2
0
def test_create_render():
    templates = {
        u'index':
        u"This is the index page.  Path: {{ request.path }}.  Greeting: {{ greeting }}",
        u'about': u"This is the about page.  Path: {{ request.path }}"
    }

    env = j2.Environment(loader=j2.DictLoader(templates))

    render = wu.create_render(env)

    @render(u"index")
    def index_page(req):
        return {u'greeting': "Hello"}

    @render(u"about")
    def about_page(req):
        return {}

    @render(u"contact")
    def contact(req):
        return wz.redirect(u"/other_page")

    req = wz.Request(utils.MockEnv(u"/", u"GET"))

    res = index_page(req)
    assert res.response[
        0] == "This is the index page.  Path: /.  Greeting: Hello"

    res = about_page(req)
    assert res.response[0] == "This is the about page.  Path: /"

    res = contact(req)
    assert u"Redirecting..." in res.response[0]
    assert u"/other_page" in res.response[0]
Пример #3
0
    def __call__(self, environ, start_response):
        if not self.baseurl:
            return self.app(environ, start_response)

        req = werkzeug.Request(environ)
        script_name = new_script_name = environ.get('SCRIPT_NAME', '')
        http_host = new_http_host = environ.get('HTTP_HOST', '')

        if self.baseurl.startswith('/'):
            new_script_name = self.baseurl
        else:
            parts = self.baseurl.split('/')
            new_script_name = '/'.join(parts[3:]) + script_name
            new_http_host = parts[2]
        if not new_script_name.startswith('/'):
            new_script_name = '/' + new_script_name
        if not new_script_name.endswith('/'):
            new_script_name += '/'

        environ['SCRIPT_NAME'] = new_script_name
        environ['HTTP_HOST'] = environ['SERVER_NAME'] = new_http_host

        self.logger.debug('Fixed script_name to be: %s' % new_script_name)
        self.logger.debug('Fixing host to be: %s' % new_http_host)

        return self.app(environ, start_response)
Пример #4
0
    def __call__(self, environ, start_response):
        try:
            request = werkzeug.Request(environ)
            adapter = self._url_map.bind_to_environ(environ)
            endpoint, values = adapter.match()

            # Dispatch request
            response = endpoint(request, **values)
            response = _json_response(response)
        except werkzeug.exceptions.HTTPException as e:
            response = _json_response(
                {
                    "code": e.code,
                    "name": e.name,
                    "description": e.description
                },
                status=e.code,
            )
        except Exception as e:
            response = _json_response(
                {
                    "code": 500,
                    "name": "Internal Server Error"
                }, status=500)
            print(f"ERROR {e.__class__.__name__}: {str(e)}", file=sys.stderr)
            traceback.print_exc(file=sys.stderr)
        return response(environ, start_response)
Пример #5
0
    def globs(self, environ, **extra):
        req = werkzeug.Request(environ)
        all = {'url_root': req.url_root}
        if environ.get('REMOTE_USER', False):
            all['remote_user'] = environ['REMOTE_USER']

        all.update(extra)
        return all
Пример #6
0
def application(environ, start_response):
    _request = werkzeug.Request(environ)
    _data = json.loads(_request.get_data().decode("utf-8"))

    to_json = {"result": super_additionneur(_data["param1"], _data["param2"])}

    return werkzeug.Response(json.dumps(to_json),
                             mimetype='application/json')(environ,
                                                          start_response)
Пример #7
0
def application(environ, start_response):
    request = werkzeug.Request(environ)
    response = werkzeug.Response()

    if request.method != "GET":
        response.status = 405
    else:
        fetch_content(request, response)

    return response(environ, start_response)
Пример #8
0
def render_best_content_type(environ, title, content):
    """Return a response rendered using talisker.render."""
    request = werkzeug.Request(environ)
    content_type = request.accept_mimetypes.best_match(
        ['text/plain', 'text/html', 'application/json'],
        default='text/plain',
    )
    return (
        content_type,
        render_type(content_type, Head(title), content),
    )
Пример #9
0
 def __call__(self, environ, start_response):
     routes = self.routes.bind_to_environ(environ)
     request = werkzeug.Request(environ)
     try:
         endpoint, arguments = routes.match()
         response = endpoint(request)
     except werkzeug.exceptions.HTTPException as e:
         response = e
     except Exception as e:
         response = werkzeug.exceptions.InternalServerError(str(e))
     return response(environ, start_response)
Пример #10
0
def traced_wsgi_app(pin, wrapped, instance, args, kwargs):
    """
    Wrapper for flask.app.Flask.wsgi_app

    This wrapper is the starting point for all requests.
    """
    # DEV: This is safe before this is the args for a WSGI handler
    #   https://www.python.org/dev/peps/pep-3333/
    environ, start_response = args

    # Create a werkzeug request from the `environ` to make interacting with it easier
    # DEV: This executes before a request context is created
    request = werkzeug.Request(environ)

    # Configure distributed tracing
    trace_utils.activate_distributed_headers(pin.tracer,
                                             int_config=config.flask,
                                             request_headers=request.headers)

    # Default resource is method and path:
    #   GET /
    #   POST /save
    # We will override this below in `traced_dispatch_request` when we have a `RequestContext` and possibly a url rule
    resource = u" ".join((request.method, request.path))
    with pin.tracer.trace(
            "flask.request",
            service=trace_utils.int_service(pin, config.flask),
            resource=resource,
            span_type=SpanTypes.WEB,
    ) as span:
        span.set_tag(SPAN_MEASURED_KEY)
        # set analytics sample rate with global config enabled
        sample_rate = config.flask.get_analytics_sample_rate(
            use_global_config=True)
        if sample_rate is not None:
            span.set_tag(ANALYTICS_SAMPLE_RATE_KEY, sample_rate)

        span._set_str_tag(FLASK_VERSION, flask_version_str)

        start_response = _wrap_start_response(start_response, span, request)

        # DEV: We set response status code in `_wrap_start_response`
        # DEV: Use `request.base_url` and not `request.url` to keep from leaking any query string parameters
        trace_utils.set_http_meta(
            span,
            config.flask,
            method=request.method,
            url=request.base_url,
            query=request.query_string,
            request_headers=request.headers,
        )

        return wrapped(environ, start_response)
Пример #11
0
 def __call__(self, environ, start_response):
     with self.loghandler.threadbound():
         request = werkzeug.Request(environ)
         m = self.mapper.match(environ=environ)
         if m is not None:
             handler = m['handler'](app=self,
                                    request=request,
                                    settings=self.settings)
             try:
                 return handler.handle(**m)(environ, start_response)
             except werkzeug.exceptions.HTTPException, e:
                 return e(environ, start_response)
         # no view found => 404
         return werkzeug.exceptions.NotFound()(environ, start_response)
Пример #12
0
def application(environ, start_response):
    """
    """
    global mapfile
    #global kwargs
    global MAP_CACHE
    req = z.Request(environ)

    if req.method == 'POST' and not req.data == 'Paste mapfile here':
        #import pdb;pdb.set_trace()
        xml_string = req.data
        mapfile = '/tmp/mapfile%s.xml' % random.random()
        tmp = open(mapfile, 'w+b')
        tmp.write(xml_string)
        tmp.seek(0)
        tmp.close()
        MAP_CACHE.mapfile = mapfile
        MAP_CACHE.load_map()

    if req.path in views:
        resp = views[req.path](req)
    elif req.path == '/tiles':
        # Used cached map and projection if instance exists
        if not MAP_CACHE:
            MAP_CACHE = MapResponse(req.values, mapfile)
        resp = MAP_CACHE(req.values)
    elif req.path.rstrip('/').endswith('/js'):
        arg = req.args.get('f')
        resp = get_resource(req, arg)
    elif req.path.startswith('/images'):
        #import pdb;pdb.set_trace()
        resp = get_resource(req, req.path.lstrip('/'))
    else:
        resp = not_found(req)

    return resp(environ, start_response)
Пример #13
0
    def __call__(self, environ, start_response):
        request_line = (environ["REQUEST_METHOD"], environ["PATH_INFO"])
        if any(request_line == (method, path)
               for method, path, *_ in self.exempt):
            # Requests exempted from auth checking are forwarded directly
            response = self.app
        else:
            # All others: Check authorization and then forward to app
            request = werkzeug.Request(environ)
            try:
                user = self._check_authorization(request)
                environ["REMOTE_USER"] = user
                response = self.app
            except Unauthorized as e:
                response = _json_response(
                    {
                        "code": e.code,
                        "name": e.name,
                        "description": e.description
                    },
                    status=e.code,
                )

        return response(environ, start_response)
Пример #14
0
 def wsgi_app(self, environ: Dict[str, Any], start_response: Callable):
     environ['app'] = self
     request = werkzeug.Request(environ)
     response = self._rpc_handle(request)
     return response(environ, start_response)
Пример #15
0
def WsgiApplication(environ, start_response):
    appServer.LastRequestTime = time.time()
    appServer.Local.Request = request = werkzeug.Request(environ)
    response = appServer.ProcessRequest(request)
    return response(environ, start_response)
Пример #16
0
 def from_environment(cls, environment):
     with werkzeug.Request(environment, populate_request=False) as request:
         return cls(request)
Пример #17
0
def traced_wsgi_app(pin, wrapped, instance, args, kwargs):
    """
    Wrapper for flask.app.Flask.wsgi_app

    This wrapper is the starting point for all requests.
    """
    # DEV: This is safe before this is the args for a WSGI handler
    #   https://www.python.org/dev/peps/pep-3333/
    environ, start_response = args

    # Create a werkzeug request from the `environ` to make interacting with it easier
    # DEV: This executes before a request context is created
    request = werkzeug.Request(environ)

    # Configure distributed tracing
    trace_utils.activate_distributed_headers(pin.tracer,
                                             int_config=config.flask,
                                             request_headers=request.headers)

    # Default resource is method and path:
    #   GET /
    #   POST /save
    # We will override this below in `traced_dispatch_request` when we have a `RequestContext` and possibly a url rule
    resource = u"{} {}".format(request.method, request.path)
    with pin.tracer.trace(
            "flask.request",
            service=trace_utils.int_service(pin, config.flask),
            resource=resource,
            span_type=SpanTypes.WEB,
    ) as s:
        s.set_tag(SPAN_MEASURED_KEY)
        # set analytics sample rate with global config enabled
        sample_rate = config.flask.get_analytics_sample_rate(
            use_global_config=True)
        if sample_rate is not None:
            s.set_tag(ANALYTICS_SAMPLE_RATE_KEY, sample_rate)

        s.set_tag(FLASK_VERSION, flask_version_str)

        # Wrap the `start_response` handler to extract response code
        # DEV: We tried using `Flask.finalize_request`, which seemed to work, but gave us hell during tests
        # DEV: The downside to using `start_response` is we do not have a `Flask.Response` object here,
        #   only `status_code`, and `headers` to work with
        #   On the bright side, this works in all versions of Flask (or any WSGI app actually)
        def _wrap_start_response(func):
            def traced_start_response(status_code, headers):
                code, _, _ = status_code.partition(" ")
                try:
                    code = int(code)
                except ValueError:
                    pass

                # Override root span resource name to be `<method> 404` for 404 requests
                # DEV: We do this because we want to make it easier to see all unknown requests together
                #      Also, we do this to reduce the cardinality on unknown urls
                # DEV: If we have an endpoint or url rule tag, then we don't need to do this,
                #      we still want `GET /product/<int:product_id>` grouped together,
                #      even if it is a 404
                if not s.get_tag(FLASK_ENDPOINT) and not s.get_tag(
                        FLASK_URL_RULE):
                    s.resource = u"{} {}".format(request.method, code)

                trace_utils.set_http_meta(s,
                                          config.flask,
                                          status_code=code,
                                          response_headers=headers)
                return func(status_code, headers)

            return traced_start_response

        start_response = _wrap_start_response(start_response)

        # DEV: We set response status code in `_wrap_start_response`
        # DEV: Use `request.base_url` and not `request.url` to keep from leaking any query string parameters
        trace_utils.set_http_meta(
            s,
            config.flask,
            method=request.method,
            url=request.base_url,
            query=request.query_string,
            request_headers=request.headers,
        )

        return wrapped(environ, start_response)
Пример #18
0
                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)
        except werkexc.HTTPException, exc:
            return exc(environ, start_response)

        res = werkzeug.Response(werkzeug.Request(environ).path, status=404)
        return res(environ, start_response)

    def globs(self, environ, **extra):
        req = werkzeug.Request(environ)
        all = {'url_root': req.url_root}
        if environ.get('REMOTE_USER', False):
            all['remote_user'] = environ['REMOTE_USER']

        all.update(extra)
        return all


class SimpleIndexApp(AbstractPyPiApp):
    """Represents one index in the pypi server.
Пример #19
0
def traced_wsgi_app(pin, wrapped, instance, args, kwargs):
    """
    Wrapper for flask.app.Flask.wsgi_app

    This wrapper is the starting point for all requests.
    """
    # DEV: This is safe before this is the args for a WSGI handler
    #   https://www.python.org/dev/peps/pep-3333/
    environ, start_response = args

    # Create a werkzeug request from the `environ` to make interacting with it easier
    # DEV: This executes before a request context is created
    request = werkzeug.Request(environ)

    # Configure distributed tracing
    if config.flask.get('distributed_tracing_enabled', False):
        propagator = HTTPPropagator()
        context = propagator.extract(request.headers)
        # Only need to activate the new context if something was propagated
        if context.trace_id:
            pin.tracer.context_provider.activate(context)

    # Default resource is method and path:
    #   GET /
    #   POST /save
    # We will override this below in `traced_dispatch_request` when we have a `RequestContext` and possibly a url rule
    resource = u'{} {}'.format(request.method, request.path)
    with pin.tracer.trace('flask.request',
                          service=pin.service,
                          resource=resource,
                          span_type=http.TYPE) as s:
        # set analytics sample rate with global config enabled
        sample_rate = config.flask.get_analytics_sample_rate(
            use_global_config=True)
        if sample_rate is not None:
            s.set_tag(ANALYTICS_SAMPLE_RATE_KEY, sample_rate)

        s.set_tag(FLASK_VERSION, flask_version_str)

        # Wrap the `start_response` handler to extract response code
        # DEV: We tried using `Flask.finalize_request`, which seemed to work, but gave us hell during tests
        # DEV: The downside to using `start_response` is we do not have a `Flask.Response` object here,
        #   only `status_code`, and `headers` to work with
        #   On the bright side, this works in all versions of Flask (or any WSGI app actually)
        def _wrap_start_response(func):
            def traced_start_response(status_code, headers):
                code, _, _ = status_code.partition(' ')
                try:
                    code = int(code)
                except ValueError:
                    pass

                # Override root span resource name to be `<method> 404` for 404 requests
                # DEV: We do this because we want to make it easier to see all unknown requests together
                #      Also, we do this to reduce the cardinality on unknown urls
                # DEV: If we have an endpoint or url rule tag, then we don't need to do this,
                #      we still want `GET /product/<int:product_id>` grouped together,
                #      even if it is a 404
                if not s.get_tag(FLASK_ENDPOINT) and not s.get_tag(
                        FLASK_URL_RULE):
                    s.resource = u'{} {}'.format(request.method, code)

                s.set_tag(http.STATUS_CODE, code)
                if 500 <= code < 600:
                    s.error = 1
                elif code in config.flask.get('extra_error_codes', set()):
                    s.error = 1
                return func(status_code, headers)

            return traced_start_response

        start_response = _wrap_start_response(start_response)

        # DEV: We set response status code in `_wrap_start_response`
        # DEV: Use `request.base_url` and not `request.url` to keep from leaking any query string parameters
        s.set_tag(http.URL, request.base_url)
        s.set_tag(http.METHOD, request.method)
        if config.flask.trace_query_string:
            s.set_tag(http.QUERY_STRING,
                      compat.to_unicode(request.query_string))

        return wrapped(environ, start_response)