Example #1
0
    def __call__(self, environ, start_response):
        req = webob.Request(environ)
        if req.path == WS_ENDPOINT:
            return self.proxy_connection(environ, start_response)
        else:
            if req.path == '/':
                fname = '/vnc_auto.html'
            else:
                fname = req.path

            fname = (self.wwwroot + fname).replace('//', '/')
            if not fname in self.whitelist:
                start_response('404 Not Found',
                               [('content-type', 'text/html')])
                return "Not Found"

            base, ext = os.path.splitext(fname)
            if ext == '.js':
                mimetype = 'application/javascript'
            elif ext == '.css':
                mimetype = 'text/css'
            elif ext in ['.svg', '.jpg', '.png', '.gif']:
                mimetype = 'image'
            else:
                mimetype = 'text/html'

            start_response('200 OK', [('content-type', mimetype)])
            return open(os.path.join(fname)).read()
Example #2
0
    def test_not_match_version_string(self):
        version_negotiation = vn.VersionNegotiationFilter(
            self._version_controller_factory, None, None)
        request = webob.Request({})

        match = version_negotiation._match_version_string("invalid", request)
        self.assertFalse(match)
  def __call__(self, environ, start_response):
    """Handles WSGI requests.

    Args:
      environ: An environ dict for the current request as defined in PEP-333.
      start_response: A function with semantics defined in PEP-333.

    Returns:
      An iterable over strings containing the body of the HTTP response.
    """
    request = webob.Request(environ)

    try:
      result = stub_dispatcher.dispatch(request.method, request.headers,
                                        request.url, request.body)
    except ValueError as e:
      status_message = httplib.responses.get(e.args[1], '')
      start_response('%d %s' % (e.args[1], status_message), [])
      return [e.args[0]]

    # The metadata headers must be convereted from unicode to string.
    headers = []
    for k, v in result.headers.iteritems():
      headers.append((str(k), str(v)))

    # GCS uses non-standard HTTP 308 status code.
    status_code = result.status_code
    if status_code == 308:
      status_message = HTTP_308_STATUS_MESSAGE
    else:
      status_message = httplib.responses.get(status_code, '')

    start_response('%d %s' % (status_code, status_message), headers)

    return [result.content]
Example #4
0
    def __call__(self, environ, start_response):
        request = webob.Request(environ)

        try:
            result = stub_dispatcher.dispatch(request.method, request.headers,
                                              request.url, request.body)
        except ValueError as e:
            status_message = httplib.responses.get(e.args[1], '')
            start_response('%d %s' % (e.args[1], status_message), [])
            return [e.args[0]]

        # The metadata headers must be convereted from unicode to string.
        headers = []
        for k, v in result.headers.iteritems():
            headers.append((str(k), str(v)))

        # GCS uses non-standard HTTP 308 status code.
        status_code = result.status_code
        if status_code == 308:
            status_message = HTTP_308_STATUS_MESSAGE
        else:
            status_message = httplib.responses.get(status_code, '')

        start_response('%d %s' % (status_code, status_message), headers)

        return [result.content]
Example #5
0
    def _application(self, environment, start_response):
        """WSGI application for conductor JSON RPC."""
        request = webob.Request(environment)
        if request.method != 'POST':
            body = {
                'error': {
                    'code': 405,
                    'message': _('Only POST method can be used')
                }
            }
            return webob.Response(status_code=405,
                                  json_body=body)(environment, start_response)

        if json_rpc.auth_strategy() == 'keystone':
            roles = (request.headers.get('X-Roles') or '').split(',')
            if 'admin' not in roles:
                LOG.debug(
                    'Roles %s do not contain "admin", rejecting '
                    'request', roles)
                body = {'error': {'code': 403, 'message': _('Forbidden')}}
                return webob.Response(status_code=403,
                                      json_body=body)(environment,
                                                      start_response)

        result = self._call(request)
        if result is not None:
            response = webob.Response(content_type='application/json',
                                      charset='UTF-8',
                                      json_body=result)
        else:
            response = webob.Response(status_code=204)
        return response(environment, start_response)
Example #6
0
 def test_poll(self):
     self.api(
         webob.Request({
             'REQUEST_METHOD': 'PUT',
             'PATH_INFO': '/poll/'
         }))
     self.ctl.run.assert_called_with(['--debug', 'poll'])
Example #7
0
    def __call__(self, environ, start_response):
        """ Process a request.

        Do one of two things::

            - If this request is for a raptor resource (image, sound, js
              code).  Ignore the next WSGI layer in the call chain and just
              serve the resource myself.
            - Call the next layer in the WSGI call chain and retrieve its
              output.  Determine if I should actually raptorize this request
              and if so, insert our magic javascript in the <head> tag.
        """
        __app__ = None
        if self.serve_resources and 'raptorizemw' in environ['PATH_INFO']:
            __app__ = self.resources_app
        else:
            __app__ = self.app

        req = webob.Request(environ)
        resp = req.get_response(__app__, catch_exc_info=True)

        if self.should_raptorize(req, resp):
            resp = self.raptorize(resp)

        return resp(environ, start_response)
Example #8
0
    def handle(environ, start_response):

        req = webob.Request(environ)
        vers = aiohttp.HttpVersion10 if req.http_version == 'HTTP/1.0' else aiohttp.HttpVersion11
        message = aiohttp.RawRequestMessage(
            req.method, req.path_qs, vers, aiohttp.CIMultiDict(req.headers),
            req.headers, False, False)
        payload = aiohttp.StreamReader(loop=loop_)
        payload.feed_data(req.body)
        payload.feed_eof()
        factory = aiohttp.web.RequestHandlerFactory(
            app_, app_.router, loop=loop_, keep_alive_on=False)
        handler = factory()
        handler.transport = io.BytesIO()
        handler.transport.is_closing = lambda: False
        handler.transport._conn_lost = 0
        handler.transport.get_extra_info = lambda s: ('127.0.0.1', 80)
        handler.writer = aiohttp.parsers.StreamWriter(
            handler.transport, handler, handler.reader, handler._loop)
        coro = handler.handle_request(message, payload)
        if loop_.is_running():
            raise RuntimeError('Client cannot start durring another coroutine is running.')

        loop_.run_until_complete(coro)
        handler.transport.seek(9)
        res = webob.Response.from_file(handler.transport)
        start_response(res.status, res.headerlist)
        return res.app_iter
def app(environ, start_response):
    # webob.Request继承自BaseRequest
    request = webob.Request(environ)
    # 显示请求头部
    print(request.headers)
    # 显示请求方法
    print(request.method)
    # 显示请求资源的路径
    print(request.path)
    # 显示查询字符串
    print(request.query_string)
    # GET方法的所有数据
    print(request.GET)
    # POST方法的所有数据
    print(request.POST)
    # # 所有数据
    # print(request.params)
    # 定义状态码
    status = '200 ok'
    # 定义头部信息
    headers = [('Content-Type', 'text/html;charset=utf-8')]
    # 返回Response头部信息
    start_response(status, headers)
    # 返回可迭代对象
    html = '<h1>hello word</h1>'.encode('utf-8')
    # 返回可迭代对象,所以把html放到一个列表中
    return [html]
 def test_authorized(self):
     req = webob.Request.blank('/v1/AUTH_cfa/c/o')
     req.headers['Authorization'] = 'access:signature'
     req.headers['X-Storage-Token'] = 'token'
     resp = webob.Request(req.get_response(self.middleware).environ)
     self.assertTrue(resp.path.startswith('/v1/AUTH_TENANT_ID'))
     self.assertEqual(resp.headers['X-Auth-Token'], 'TOKEN_ID')
Example #11
0
    def __call__(self, environ, start_response):
        """ Process a request. """

        req = webob.Request(environ)

        if not self.will_serve(environ['PATH_INFO']):
            resp = webob.Response(status="404 Not Found")
            return resp(environ, start_response)

        filename = os.sep.join([self.here] +
                               environ['PATH_INFO'].split('/')[2:])

        ct, enc = mimetypes.guess_type(os.path.basename(filename))

        try:
            stream = open(filename)
        except IOError as e:
            resp = webob.Response(status="404 Not Found")
        else:
            stream = wsgiref.util.FileWrapper(stream)
            resp = webob.Response(request=req,
                                  app_iter=stream,
                                  content_type=ct)
            if enc:
                resp.content_type_params['charset'] = enc
        resp.cache_control = {'max-age': int(self.res_max_age)}
        return resp(environ, start_response)
    def __call__(self, environ, start_response):
        """ Process a request. """

        req = webob.Request(environ)

        if self.should_respond(req):
            # Is this an ajax request asking for fedmsg.text information?
            # If so.. forget everything else and just handle that before anyone
            # else notices ;o
            resp = self.serve_response(req)
            return resp(environ, start_response)

        # Register our fancy widget with the moksha middleware.
        PopupNotification.display()

        # Pass the request on to the app that we wrap.
        resp = req.get_response(self.app, catch_exc_info=True)

        # Should we modify their response and inject the moksha_socket?
        # We'll do so in a hopefully delicate manner that
        # doesn't disturb other javascript (like jQuery).
        if self.should_inject(req, resp):
            resp = self.inject(resp)

        return resp(environ, start_response)
Example #13
0
 def setUp(self):
     self.module = XModule(descriptor=Mock(),
                           field_data=Mock(),
                           runtime=Mock(),
                           scope_ids=Mock())
     self.module.handle_ajax = Mock(return_value='{}')
     self.request = webob.Request({})
 def set_environment(environ, start_response):
     req = webob.Request(environ)
     urls.application_url = req.application_url
     try:
         return app(req.environ, start_response)
     except webob.exc.WSGIHTTPException as wsgi_exception:
         return wsgi_exception(environ, start_response)
Example #15
0
    def request(self, xblock, handler_name, content, request_method="POST", response_format=None):
        """Make a request to an XBlock handler.

        Args:
            xblock (XBlock): The XBlock instance that should handle the request.
            handler_name (str): The name of the handler.
            content (unicode): Content of the request.

        Keyword Arguments:
            request_method (str): The HTTP method of the request (defaults to POST)
            response_format (None or str): Expected format of the response string.
                If `None`, return the raw response content; if 'json', parse the
                response as JSON and return the result.

        Raises:
            NotImplementedError: Response format not supported.

        Returns:
            Content of the response (mixed).
        """
        # Create a fake request
        request = webob.Request(dict())
        request.method = request_method
        request.body = content

        # Send the request to the XBlock handler
        response = self.runtime.handle(xblock, handler_name, request)

        # Parse the response (if a format is specified)
        if response_format is None:
            return response.body
        elif response_format == 'json':
            return json.loads(response.body)
        else:
            raise NotImplementedError(f"Response format '{response_format}' not supported")
Example #16
0
    def __call__(self, environ, start_response):
        try:
            req = webob.Request(environ)
            LOG.info("Request: %s", req)
            token = req.params.get('token')
            if not token:
                LOG.info("Request made with missing token: %s", req)
                start_response('400 Invalid Request',
                               [('content-type', 'text/html')])
                return "Invalid Request"

            ctxt = context.get_admin_context()

            try:
                connect_info = objects.ConsoleAuthToken.validate(
                    ctxt, token).to_dict()
            except exception.InvalidToken:
                LOG.info("Request made with invalid token: %s", req)
                start_response('401 Not Authorized',
                               [('content-type', 'text/html')])
                return "Not Authorized"

            return self.proxy_connection(req, connect_info, start_response)
        except Exception as e:
            LOG.info("Unexpected error: %s", e)
Example #17
0
 def test_workers_debug(self):
     self.api(
         webob.Request({
             'REQUEST_METHOD': 'PUT',
             'PATH_INFO': '/workers/debug/'
         }))
     self.ctl.run.assert_called_with(['--debug', 'workers', 'debug'])
Example #18
0
    def wrapped_func(request, *args, **kwds):
        orig_request = request
        # Convert the incoming request object into a webob.Request.
        if isinstance(orig_request, webob.Request):
            pass
        # A requests.PreparedRequest object?
        elif requests and isinstance(orig_request, requests.PreparedRequest):
            # Copy over only the details needed for the signature.
            # WebOb doesn't code well with bytes header names,
            # so we have to be a little careful.
            request = webob.Request.blank(orig_request.url)
            request.method = orig_request.method
            for k, v in iteritems(orig_request.headers):
                if not isinstance(k, str):
                    k = k.decode('ascii')
                request.headers[k] = v
        # A WSGI environ dict?
        elif isinstance(orig_request, dict):
            request = webob.Request(orig_request)
        # A bytestring?
        elif isinstance(orig_request, bytes):
            request = webob.Request.from_bytes(orig_request)
        # A file-like object?
        elif all(hasattr(orig_request, attr) for attr in ("read", "readline")):
            request = webob.Request.from_file(orig_request)

        # The wrapped function might modify headers.
        # Write them back if the original request object is mutable.
        try:
            return func(request, *args, **kwds)
        finally:
            if requests and isinstance(orig_request, requests.PreparedRequest):
                orig_request.headers.update(request.headers)
    def test_request_path_is_empty(self, mock_vc):
        vnf = vn.VersionNegotiationFilter(None, None)
        request = webob.Request({'PATH_INFO': '/'})

        response = vnf.process_request(request)

        self.assertIs(mock_vc.return_value, response)
Example #20
0
def app(environ, start_response):
    request = webob.Request(environ)
    if request.path == '/redirect':
        start_response("301 MOVED", [("Location", "/foo")])
        return "301 MOVED"
    elif request.path == '/needs_auth':
        auth = request.headers.get('Authorization')
        if auth and auth.startswith("Basic"):
            user, passwd = auth.split()[-1].decode("base64").split(":")
        else:
            user = None

        if user != 'john':
            start_response("401 Unauthorized",
                           [('WWW-Authenticate', "Basic realm=\"default\"")])
            return "401 Unauthorized"

    start_response("200 OK", [("Content-Type", "text/plain")])
    retval = ["Path: %s" % request.path]
    keys = request.params.keys()
    keys.sort()
    for k in keys:
        v = request.params[k]
        if hasattr(v, 'file'):
            v = v.file.read()
        retval.append("%s: %s" % (k, v))
    return "\n".join(retval)
Example #21
0
    def __call__(self, environ, start_response):
        req = wo.Request(environ)
        try:
            path = environ['PATH_INFO']
            path = path[len(self.config.res_prefix):]

            if path not in self._paths:
                if '..' in path:  # protect against directory traversal
                    raise IOError()
                for d in self._dirs:
                    if path.startswith(d.replace('\\', '/')):
                        break
                else:
                    raise IOError()
            modname, filename = path.lstrip('/').split('/', 1)
            ct, enc = mimetypes.guess_type(os.path.basename(filename))
            if modname and modname != '__anon__':
                stream = pr.resource_stream(modname, filename)
            else:
                stream = open(filename)
        except IOError:
            resp = wo.Response(status="404 Not Found")
        else:
            stream = wsgiref.util.FileWrapper(stream, self.config.bufsize)
            resp = wo.Response(app_iter=stream, content_type=ct)
            if enc:
                resp.content_type_params['charset'] = enc
        resp.cache_control = {'max-age': int(self.config.res_max_age)}
        return resp(environ, start_response)
Example #22
0
    def handle(self, env, start_response):
        start_response('200 OK', [('Content-Type', 'text/html')])

        #Handle Possible Post values
        self.handle_POST(webob.Request(env))

        return self.line_string
Example #23
0
def application(environ, start_response):
    try:
        application = bottle.app()
        application.catchall = False
        application = JsonApiMiddleware(application)
        return application(environ, start_response)

    except:
        rollbar.report_exc_info(sys.exc_info(), webob.Request(environ))

        # Bare bones 500 handler
        content = b''
        if environ.get('JSON'):
            content = '{"__status_code__": 500}'
            content_type = 'application/json; charset=UTF-8'
        else:
            dirname = os.path.dirname(__file__)
            five_hundred_path = os.path.join(dirname,
                                             'app/html/five_hundred.html')
            with open(five_hundred_path, 'r', encoding='utf-8') as f:
                content = f.read()
            content_type = 'text/html; charset=UTF-8'
        content = content.encode('utf-8')
        start_response('500 Internal Server Error',
                       [('Content-Type', content_type),
                        ('Content-Length', str(len(content)))], sys.exc_info())
        environ['wsgi.errors'] = content
        return [content]
Example #24
0
    def __call__(self, environ, start_response):
        query = environ['QUERY_STRING']
        if ('state=' in query) and (('code=' in query) or ('error=' in query)):
            request = webob.Request(environ)
            environ['QUERY_STRING'] += ('&' + request.params['state'])

        return super(WSGIApp, self).__call__(environ, start_response)
Example #25
0
    def handle_publish(self, env, start_response):
        request = webob.Request(env)

        self.hub.publish(request.path, str(request.body))

        start_response('200 OK', [('Content-Type', 'text/plain')])
        return ["OK\n"]
def application(environ, start_response):
    req = webob.Request(environ)
    resp = webob.Response()
    if req.method == 'GET':
        filename = req.path_info.strip('/') or 'index.html'
        if filename in ('302', ):
            redirect = req.params['redirect']
            resp = webob.exc.HTTPFound(location=redirect)
            return resp(environ, start_response)
        if filename.isdigit():
            resp.status = filename
            filename = 'index.html'
        filename = os.path.join(files, 'html', filename)
        if os.path.isfile(filename):
            kw = dict(message=req.params.get('message', ''),
                      redirect=req.params.get('redirect', ''))
            with open(filename) as f:
                resp.unicode_body = u(f.read()) % kw
            _, ext = os.path.splitext(filename)
            if ext == '.html':
                resp.content_type = 'text/html'
            elif ext == '.js':
                resp.content_type = 'text/javascript'
            elif ext == '.json':
                resp.content_type = 'application/json'
    else:
        redirect = req.params.get('redirect', '')
        if redirect:
            resp = webob.exc.HTTPFound(location=redirect)
        else:
            resp.body = req.body
    return resp(environ, start_response)
Example #27
0
def demo_app_my(environ: dict, start_response):
    request = webob.Request(environ)
    res = webob.Response()
    res.status_code = 200
    html = "<html>nihaoma</html>".encode("utf-8")
    res.body = html
    return res(environ, start_response)  #__call__
Example #28
0
def simple_app(environ, start_response):
    req = wo.Request(environ)
    ct = 'text/html' if req.path == '/' else 'test/plain'
    resp = wo.Response(request=req, content_type="%s; charset=UTF8" % ct)
    inject_widget.display()
    resp.body = html
    return resp(environ, start_response)
Example #29
0
    def __call__(self, environ, start_response):
        try:
            req = webob.Request(environ)
            LOG.audit(_("Request: %s"), req)
            token = req.params.get('token')
            if not token:
                LOG.audit(_("Request made with missing token: %s"), req)
                start_response('400 Invalid Request',
                               [('content-type', 'text/html')])
                return "Invalid Request"

            ctxt = context.get_admin_context()
            connect_info = rpc.call(ctxt, FLAGS.consoleauth_topic, {
                'method': 'check_token',
                'args': {
                    'token': token
                }
            })

            if not connect_info:
                LOG.audit(_("Request made with invalid token: %s"), req)
                start_response('401 Not Authorized',
                               [('content-type', 'text/html')])
                return "Not Authorized"

            return self.proxy_connection(req, connect_info, start_response)
        except Exception as e:
            LOG.audit(_("Unexpected error: %s"), e)
Example #30
0
    def __call__(self, environ, start_response):
        """Put the user object into the WSGI environment."""

        # Create our own request object
        request = webob.Request(environ, charset='utf-8')

        # Save the login path, we might require it in template tags
        environ['ao.social.login'] = self._build_absolute_uri(
            environ, self._login_path)

        # We need beaker sessions for this middleware
        session = environ['beaker.session']

        # Check if the user already has a session
        environ['ao.social.user'] = None
        if 'ao.social.user' in session:
            environ['ao.social.user'] = self._user_class.get_user(
                session['ao.social.user'])

        # Try to log in the user
        for method in ('facebook', 'twitter', 'google', 'linkedin'):
            if request.path_info == self._login_path % method:
                response = self._handle_user(request, method, 'login')
                if response is not None:
                    return response(environ, start_response)

        # Call the downstream application
        return self._app(environ, start_response)