Python webob 模块,Response() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用webob.Response()

项目:stalker_pyramid    作者:eoyilmaz    | 项目源码 | 文件源码
def append_link_to_daily(request):

    link_id = request.matchdict.get('id')
    link = Link.query.filter_by(id=link_id).first()

    daily_id = request.matchdict.get('did')
    daily = Daily.query.filter_by(id=daily_id).first()

    if not link:
        transaction.abort()
        return Response('There is no link with id: %s' % link_id, 500)

    if not daily:
        transaction.abort()
        return Response('There is no daily with id: %s' % daily_id, 500)

    if link not in daily.links:
        daily.links.append(link)

    request.session.flash(
        'success: Output is added to daily: %s '% daily.name
    )

    return Response('Output is added to daily: %s '% daily.name)
项目:stalker_pyramid    作者:eoyilmaz    | 项目源码 | 文件源码
def remove_link_to_daily(request):

    link_id = request.matchdict.get('id')
    link = Link.query.filter_by(id=link_id).first()

    daily_id = request.matchdict.get('did')
    daily = Daily.query.filter_by(id=daily_id).first()

    if not link:
        transaction.abort()
        return Response('There is no link with id: %s' % link_id, 500)

    if not daily:
        transaction.abort()
        return Response('There is no daily with id: %s' % daily_id, 500)

    if link in daily.links:
        daily.links.remove(link)

    request.session.flash(
        'success: Output is removed from daily: %s '% daily.name
    )

    return Response('Output is removed to daily: %s '% daily.name)
项目:stalker_pyramid    作者:eoyilmaz    | 项目源码 | 文件源码
def delete_budgetentry(request):
    """deletes the budgetentry
    """

    budgetentry_id = request.params.get('id')
    budgetentry = BudgetEntry.query.filter_by(id=budgetentry_id).first()

    if not budgetentry:
        transaction.abort()
        return Response('There is no budgetentry with id: %s' % budgetentry_id, 500)

    if budgetentry.type.name == 'Calendar':
        transaction.abort()
        return Response('You can not delete CalenderBasedEntry', 500)

    delete_budgetentry_action(budgetentry)
项目:meteos    作者:openstack    | 项目源码 | 文件源码
def serialize(self, request, content_type, default_serializers=None):
        """Serializes the wrapped object.

        Utility method for serializing the wrapped object.  Returns a
        webob.Response object.
        """

        if self.serializer:
            serializer = self.serializer
        else:
            _mtype, _serializer = self.get_serializer(content_type,
                                                      default_serializers)
            serializer = _serializer()

        response = webob.Response()
        response.status_int = self.code
        for hdr, value in self._headers.items():
            response.headers[hdr] = six.text_type(value)
        response.headers['Content-Type'] = six.text_type(content_type)
        if self.obj is not None:
            response.body = serializer.serialize(self.obj)

        return response
项目:gateway_manager    作者:binarydud    | 项目源码 | 文件源码
def _call_apex(request):
    node = _lookup_table[request.matched_route.name]
    function_name = node.handler
    try:
        response = run_function(request, function_name)
    except Exception as e:
        partial = functools.partial(filter_on_response_pattern, e)
        response = filter(partial, node.responses)
        if response:
            response = response[0]
            body = build_error_response(response.code, e)

            return Response(body=body, status_code=response.code, content_type=response.body[0].mime_type)
        return e
    else:
        return Response(body=json.dumps(response), content_type='application/json')
项目:baka    作者:baka-framework    | 项目源码 | 文件源码
def http_error(context, request):
    with JSONAPIResponse(request.response) as resp:
        _in = u'Failed'
        code, status = JSONAPIResponse.BAD_REQUEST
        if isinstance(context, webob.Response) \
                and context.content_type == 'application/json':
            return context

        request.response.status = context.status
        status = context.status
        for (header, value) in context.headers.items():
            if header in {'Content-Type', 'Content-Length'}:
                continue
            request.response.headers[header] = value
        if context.message:
            message =  {'message': context.message}
        else:
            message = {'message': context.status}

    return resp.to_json(
        _in, code=code,
        status=status, message=message)
项目:webapp2    作者:GoogleCloudPlatform    | 项目源码 | 文件源码
def _set_status(self, value):
        """The status string, including code and message."""
        message = None
        # Accept long because urlfetch in App Engine returns codes as longs.
        if isinstance(value, six.integer_types):
            code = int(value)
        else:
            if isinstance(value, six.text_type):
                # Status messages have to be ASCII safe, so this is OK.
                value = str(value)

            if not isinstance(value, str):
                raise TypeError(
                    'You must set status to a string or integer (not %s)'
                    % type(value))

            parts = value.split(' ', 1)
            code = int(parts[0])
            if len(parts) == 2:
                message = parts[1]

        message = message or Response.http_status_message(code)
        self._status = '%d %s' % (code, message)
项目:webapp2    作者:GoogleCloudPlatform    | 项目源码 | 文件源码
def redirect_to(_name, _permanent=False, _abort=False, _code=None,
                _body=None, _request=None, _response=None, *args, **kwargs):
    """Convenience function mixing :func:`redirect` and :func:`uri_for`.

    Issues an HTTP redirect to a named URI built using :func:`uri_for`.

    :param _name:
        The route name to redirect to.
    :param args:
        Positional arguments to build the URI.
    :param kwargs:
        Keyword arguments to build the URI.
    :returns:
        A :class:`Response` instance.

    The other arguments are described in :func:`redirect`.
    """
    uri = uri_for(_name, _request=_request, *args, **kwargs)
    return redirect(uri, permanent=_permanent, abort=_abort, code=_code,
                    body=_body, request=_request, response=_response)
项目:qinling    作者:openstack    | 项目源码 | 文件源码
def wrap_pecan_controller_exception(func):
    """Decorator for controllers method.

    This decorator wraps controllers method to manage pecan exceptions:
    In case of expected error it aborts the request with specific status code.
    """

    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except exc.QinlingException as e:
            LOG.error('Error during API call: %s', six.text_type(e))
            return webob.Response(
                status=e.http_code,
                content_type='application/json',
                body=json.dumps(dict(faultstring=six.text_type(e))),
                charset='UTF-8'
            )

    return wrapped
项目:FirewallController    作者:iFedix    | 项目源码 | 文件源码
def create_tap(self, req, **_kwargs):
        # Come delete_tap
        try:
            filter_data = eval(req.body)
            print filter_data
            if not self.is_filter_data_valid(filter_data):
                return Response(status=400)
        except SyntaxError:
            LOG.error('Invalid syntax %s', req.body)
            return Response(status=400)

        if self.tap.create_tap(filter_data):
            return Response(status=200, content_type='application/json', body=json.dumps({'status': 'success'}))
        else:
            LOG.error('Create tap failed')
            return Response(status=501)
项目:Flask    作者:Humbertzhang    | 项目源码 | 文件源码
def rest_controller(cls):
    def replacement(environ, start_response):
        req = Request(environ)
        try:
            instance = cls(req, **req.urlvars)
            action = req.urlvars.get('action')
            if action:
                action += '_' + req.method.lower()
            else:
                action = req.method.lower()

            try:
                method = getattr(instance, action)
            except AttributeError:
                raise exc.HTTPNotFound("No action %s" % action)

            resp = method()
            if isinstance(resp, type("")):
                resp = Response(body=resp)
        except exc.HTTPException as e:
            resp = e
        return resp(environ, start_response)
    return replacement
项目:ryu-lagopus-ext    作者:lagopus    | 项目源码 | 文件源码
def rest_command(func):
    def _rest_command(*args, **kwargs):
        try:
            msg = func(*args, **kwargs)
            return Response(content_type='application/json',
                            body=json.dumps(msg))

        except SyntaxError as e:
            status = 400
            details = e.msg
        except (ValueError, NameError) as e:
            status = 400
            details = e.message

        except NotFoundError as msg:
            status = 404
            details = str(msg)

        msg = {REST_RESULT: REST_NG,
               REST_DETAILS: details}
        return Response(status=status, body=json.dumps(msg))

    return _rest_command
项目:ryu-lagopus-ext    作者:lagopus    | 项目源码 | 文件源码
def _access_module(self, switchid, func, waiters=None):
        try:
            dps = self._OFS_LIST.get_ofs(switchid)
        except ValueError as message:
            return Response(status=400, body=str(message))

        msgs = []
        for f_ofs in dps.values():
            function = getattr(f_ofs, func)
            msg = function() if waiters is None else function(waiters)
            msgs.append(msg)

        body = json.dumps(msgs)
        return Response(content_type='application/json', body=body)

    # GET /firewall/rules/{switchid}
项目:ryu-lagopus-ext    作者:lagopus    | 项目源码 | 文件源码
def _set_rule(self, req, switchid, vlan_id=VLANID_NONE):
        try:
            rule = req.json if req.body else {}
        except ValueError:
            FirewallController._LOGGER.debug('invalid syntax %s', req.body)
            return Response(status=400)

        try:
            dps = self._OFS_LIST.get_ofs(switchid)
            vid = FirewallController._conv_toint_vlanid(vlan_id)
        except ValueError as message:
            return Response(status=400, body=str(message))

        msgs = []
        for f_ofs in dps.values():
            try:
                msg = f_ofs.set_rule(rule, self.waiters, vid)
                msgs.append(msg)
            except ValueError as message:
                return Response(status=400, body=str(message))

        body = json.dumps(msgs)
        return Response(content_type='application/json', body=body)
项目:ryu-lagopus-ext    作者:lagopus    | 项目源码 | 文件源码
def _delete_rule(self, req, switchid, vlan_id=VLANID_NONE):
        try:
            ruleid = req.json if req.body else {}
        except ValueError:
            FirewallController._LOGGER.debug('invalid syntax %s', req.body)
            return Response(status=400)

        try:
            dps = self._OFS_LIST.get_ofs(switchid)
            vid = FirewallController._conv_toint_vlanid(vlan_id)
        except ValueError as message:
            return Response(status=400, body=str(message))

        msgs = []
        for f_ofs in dps.values():
            try:
                msg = f_ofs.delete_rule(ruleid, self.waiters, vid)
                msgs.append(msg)
            except ValueError as message:
                return Response(status=400, body=str(message))

        body = json.dumps(msgs)
        return Response(content_type='application/json', body=body)
项目:reahl    作者:reahl    | 项目源码 | 文件源码
def test_simple_sub_resources(web_fixture):
    """During their construction, Widgets can add SubResources to their View.  The SubResource
       will then be available via a special URL underneath the URL of the Widget's View."""

    fixture = web_fixture

    @stubclass(SubResource)
    class ASimpleSubResource(SubResource):
        sub_regex = 'simple_resource'
        sub_path_template = 'simple_resource'
        @exempt
        def handle_get(self, request):
            return Response()

    @stubclass(Widget)
    class WidgetWithSubResource(Widget):
        def __init__(self, view):
            super(WidgetWithSubResource, self).__init__(view)
            view.add_resource(ASimpleSubResource('uniquename'))

    wsgi_app = fixture.new_wsgi_app(child_factory=WidgetWithSubResource.factory())
    browser = Browser(wsgi_app)
    browser.open('/_uniquename_simple_resource')
项目:multipath-sdn-controller    作者:dariobanfi    | 项目源码 | 文件源码
def change_bucket_weight(self, req, **kwargs):
        '''
        Changes bucket weight for a datapath's GROUP
        Rules are passed in this format port,weight; :
        Example : '1,1;2,1;3,2;4,2'
        '''
        multipath_controller = self.mp_instance

        try:
            dp_id = kwargs['dp_id']
            group_id = kwargs['group_id']
            arg_rules = kwargs['rules']
            rules = {}
            for i in arg_rules.split(';'):
                rules[int(i.split(',')[0])] = int(i.split(',')[1])

            multipath_controller.topo_shape.modify_group(
                multipath_controller.topo_shape.dpid_to_switch[
                    int(dp_id)].dp, int(group_id), rules)
        except:
            traceback.print_exc()

        return Response(content_type='text/html', body='Done!\n')
项目:deb-python-pecan    作者:openstack    | 项目源码 | 文件源码
def root(self):
        class RootController(object):
            @expose()
            def index(self, req, resp):
                assert isinstance(req, webob.BaseRequest)
                assert isinstance(resp, webob.Response)
                return 'Hello, World!'

            @expose()
            def warning(self):
                return ("This should be unroutable because (req, resp) are not"
                        " arguments.  It should raise a TypeError.")

            @expose(generic=True)
            def generic(self):
                return ("This should be unroutable because (req, resp) are not"
                        " arguments.  It should raise a TypeError.")

            @generic.when(method='PUT')
            def generic_put(self, _id):
                return ("This should be unroutable because (req, resp) are not"
                        " arguments.  It should raise a TypeError.")

        return RootController
项目:xblock-video    作者:appsembler    | 项目源码 | 文件源码
def download_transcript(self, request, _suffix=''):
        """
        Download a transcript.

        Arguments:
            request (webob.Request): Request to handle.
            suffix (string): Slug used for routing.
        Returns:
            File with the correct name.
        """
        trans_path = self.get_path_for(request.query_string)
        filename = self.get_file_name_from_path(trans_path)
        transcript = requests.get(request.host_url + request.query_string).text
        response = Response(transcript)
        headerlist = [
            ('Content-Type', 'text/plain'),
            ('Content-Disposition', 'attachment; filename={}'.format(filename))
        ]
        response.headerlist = headerlist
        return response
项目:xblock-video    作者:appsembler    | 项目源码 | 文件源码
def test_download_transcript_handler_response_object(self, get_mock, get_filename_mock):
        """
        Test transcripts downloading works properly.
        """
        # Arrange
        get_filename_mock.return_value = 'transcript.vtt'
        get_mock.return_value.text = 'vtt transcripts'
        request_mock = MagicMock()
        request_mock.host_url = 'test.host'
        request_mock.query_string = '/test-query-string'

        # Act
        vtt_response = self.xblock.download_transcript(request_mock, 'unused suffix')

        # Assert
        self.assertIsInstance(vtt_response, Response)
        self.assertEqual(vtt_response.text, 'vtt transcripts')
        self.assertEqual(vtt_response.headerlist, [
            ('Content-Type', 'text/plain'),
            ('Content-Disposition', 'attachment; filename={}'.format('transcript.vtt'))
        ])
        get_mock.assert_called_once_with('test.host/test-query-string')
项目:xblock-video    作者:appsembler    | 项目源码 | 文件源码
def test_srt_to_vtt(self, convert_caps_to_vtt_mock, requests_mock):
        """
        Test xBlock's srt-to-vtt convertation works properly.
        """
        # Arrange
        request_mock = MagicMock()
        convert_caps_to_vtt_mock.return_value = 'vtt transcripts'
        requests_mock.get.return_value.text = text_mock = PropertyMock()
        text_mock.return_value = 'vtt transcripts'

        # Act
        vtt_response = self.xblock.srt_to_vtt(request_mock, 'unused suffix')

        # Assert
        self.assertIsInstance(vtt_response, Response)
        self.assertEqual(vtt_response.text, 'vtt transcripts')
        convert_caps_to_vtt_mock.assert_called_once_with(text_mock)
项目:blockhooks    作者:EthereumWebhooks    | 项目源码 | 文件源码
def _set_status(self, value):
        """The status string, including code and message."""
        message = None
        # Accept long because urlfetch in App Engine returns codes as longs.
        if isinstance(value, (int, long)):
            code = int(value)
        else:
            if isinstance(value, unicode):
                # Status messages have to be ASCII safe, so this is OK.
                value = str(value)

            if not isinstance(value, str):
                raise TypeError(
                    'You must set status to a string or integer (not %s)' %
                    type(value))

            parts = value.split(' ', 1)
            code = int(parts[0])
            if len(parts) == 2:
                message = parts[1]

        message = message or Response.http_status_message(code)
        self._status = '%d %s' % (code, message)
项目:blockhooks    作者:EthereumWebhooks    | 项目源码 | 文件源码
def redirect_to(_name, _permanent=False, _abort=False, _code=None,
                _body=None, _request=None, _response=None, *args, **kwargs):
    """Convenience function mixing :func:`redirect` and :func:`uri_for`.

    Issues an HTTP redirect to a named URI built using :func:`uri_for`.

    :param _name:
        The route name to redirect to.
    :param args:
        Positional arguments to build the URI.
    :param kwargs:
        Keyword arguments to build the URI.
    :returns:
        A :class:`Response` instance.

    The other arguments are described in :func:`redirect`.
    """
    uri = uri_for(_name, _request=_request, *args, **kwargs)
    return redirect(uri, permanent=_permanent, abort=_abort, code=_code,
                    body=_body, request=_request, response=_response)
项目:pyramid_session_redis    作者:jvanasco    | 项目源码 | 文件源码
def test_existing_session_session_after_invalidate_coe_True_no_exception(
        self
    ):
        # existing session -> invalidate() -> new session
        # cookie_on_exception is True by default, no exception raised
        import webob
        request = self._make_request()
        self._set_session_cookie(request=request,
                                 session_id=self._get_session_id(request))
        session = request.session = self._makeOne(request)
        session.invalidate()
        session['key'] = 'value'
        response = webob.Response()
        request.response_callbacks[0](request, response)
        set_cookie_headers = response.headers.getall('Set-Cookie')
        self.assertEqual(len(set_cookie_headers), 1)
        self._assert_is_a_header_to_set_cookie(set_cookie_headers[0])
项目:pyramid_session_redis    作者:jvanasco    | 项目源码 | 文件源码
def test_existing_session_session_after_invalidate_coe_False_no_exception(
        self
    ):
        # existing session -> invalidate() -> new session
        # cookie_on_exception is False, no exception raised
        import webob
        request = self._make_request()
        self._set_session_cookie(request=request,
                                 session_id=self._get_session_id(request))
        session = request.session = self._makeOne(request,
                                                  cookie_on_exception=False)
        session.invalidate()
        session['key'] = 'value'
        response = webob.Response()
        request.response_callbacks[0](request, response)
        set_cookie_headers = response.headers.getall('Set-Cookie')
        self.assertEqual(len(set_cookie_headers), 1)
        self._assert_is_a_header_to_set_cookie(set_cookie_headers[0])
项目:pyramid_session_redis    作者:jvanasco    | 项目源码 | 文件源码
def test_existing_session_session_after_invalidate_coe_False_exception(
        self
    ):
        # existing session -> invalidate() -> new session
        # cookie_on_exception is False, exception raised
        import webob
        request = self._make_request()
        self._set_session_cookie(request=request,
                                 session_id=self._get_session_id(request))
        session = request.session = self._makeOne(request,
                                                  cookie_on_exception=False)
        session.invalidate()
        session['key'] = 'value'
        request.exception = Exception()
        response = webob.Response()
        request.response_callbacks[0](request, response)
        set_cookie_headers = response.headers.getall('Set-Cookie')
        self.assertEqual(len(set_cookie_headers), 1)
        self.assertIn('Max-Age=0', set_cookie_headers[0])
        # Cancel setting of cookie for new session, but still delete cookie for
        # the earlier invalidate().
项目:pyramid_session_redis    作者:jvanasco    | 项目源码 | 文件源码
def test_existing_session_multiple_invalidates(self):
        # existing session -> invalidate() -> new session -> invalidate()
        # Invalidate more than once, no new session after last invalidate()
        import webob
        request = self._make_request()
        self._set_session_cookie(request=request,
                                 session_id=self._get_session_id(request))
        session = request.session = self._makeOne(request)
        session.invalidate()
        session['key'] = 'value'
        session.invalidate()
        response = webob.Response()
        request.response_callbacks[0](request, response)
        set_cookie_headers = response.headers.getall('Set-Cookie')
        self.assertEqual(len(set_cookie_headers), 1)
        self.assertIn('Max-Age=0', set_cookie_headers[0])
项目:pyramid_session_redis    作者:jvanasco    | 项目源码 | 文件源码
def test_existing_session_multiple_invalidates_no_new_session_in_between(
        self
    ):
        # existing session -> invalidate() -> invalidate()
        # Invalidate more than once, no new session in between invalidate()s,
        # no new session after last invalidate()
        import webob
        request = self._make_request()
        self._set_session_cookie(request=request,
                                 session_id=self._get_session_id(request))
        session = request.session = self._makeOne(request)
        session.invalidate()
        session.invalidate()
        response = webob.Response()
        request.response_callbacks[0](request, response)
        set_cookie_headers = response.headers.getall('Set-Cookie')
        self.assertEqual(len(set_cookie_headers), 1)
        self.assertIn('Max-Age=0', set_cookie_headers[0])
项目:pyramid_session_redis    作者:jvanasco    | 项目源码 | 文件源码
def _load_cookie_session_in_new_request(self, request_old, session_id='existing_session', **session_args):
        import webob
        # we need a request, but must persist the redis datastore
        request = self._make_request(request_old=request_old)

        self._set_session_cookie(request=request,
                                 session_id=session_id,
                                 )
        request.session = self._makeOne(request, **session_args)
        response = webob.Response()
        request.response_callbacks[0](request, response)
        request._process_finished_callbacks()  # runs any persist if needed

        self.assertNotIn('Set-Cookie', response.headers)
        # stored_session_data = self._deserialize_session_stored(request.session)
        return request
项目:masakari    作者:openstack    | 项目源码 | 文件源码
def setUp(self):
        super(TestKeystoneMiddlewareRoles, self).setUp()

        @webob.dec.wsgify()
        def role_check_app(req):
            context = req.environ['masakari.context']

            if "knight" in context.roles and "bad" not in context.roles:
                return webob.Response(status="200 Role Match")
            elif not context.roles:
                return webob.Response(status="200 No Roles")
            else:
                raise webob.exc.HTTPBadRequest("unexpected role header")

        self.middleware = (
            masakari.api.auth.MasakariKeystoneContext(role_check_app))
        self.request = webob.Request.blank('/')
        self.request.headers['X_USER'] = 'testuser'
        self.request.headers['X_TENANT_ID'] = 'testtenantid'
        self.request.headers['X_AUTH_TOKEN'] = 'testauthtoken'
        self.request.headers['X_SERVICE_CATALOG'] = jsonutils.dumps({})

        self.roles = "pawn, knight, rook"
项目:masakari    作者:openstack    | 项目源码 | 文件源码
def test_resource_headers_are_utf8(self):
        resp = webob.Response(status_int=http.ACCEPTED)
        resp.headers['x-header1'] = 1
        resp.headers['x-header2'] = u'header2'
        resp.headers['x-header3'] = u'header3'

        class Controller(object):
            def index(self, req):
                return resp

        req = webob.Request.blank('/tests')
        app = fakes.TestRouter(Controller())
        response = req.get_response(app)
        for val in response.headers.values():
            # All headers must be utf8
            self.assertThat(val, matchers.EncodedByUTF8())
        self.assertEqual(b'1', response.headers['x-header1'])
        self.assertEqual(b'header2', response.headers['x-header2'])
        self.assertEqual(b'header3', response.headers['x-header3'])
项目:masakari    作者:openstack    | 项目源码 | 文件源码
def serialize(self, request, content_type):
        """Serializes the wrapped object.

        Utility method for serializing the wrapped object.  Returns a
        webob.Response object.
        """

        serializer = self.serializer

        body = None
        if self.obj is not None:
            body = serializer.serialize(self.obj)
        response = webob.Response(body=body)
        if response.headers.get('Content-Length'):
            # NOTE: we need to encode 'Content-Length' header,
            # since webob.Response auto sets it if "body" attr is presented.
            # https://github.com/Pylons/webob/blob/1.5.0b0/webob/response.py#L147
            response.headers['Content-Length'] = utils.utf8(
                response.headers['Content-Length'])
        response.status_int = self.code
        for hdr, value in self._headers.items():
            response.headers[hdr] = utils.utf8(value)
        response.headers['Content-Type'] = utils.utf8(content_type)
        return response
项目:sdn    作者:ray6    | 项目源码 | 文件源码
def put_vtable(self, req, **kwargs):
        shortest_switch = self.shortest_switch_spp

        #Check request isn't blank.
        try:
            request_body_size = int(req.environ.get('CONTENT_LENGTH', 0))

        except(ValueError):
            request_body_size = 0

        d = parse_qs(req.body)

        #Interpret vlan input
        for key, value in d.items():
            host = ('00:00:00:00:00:0'+key[4])
            vlan = value[0][4]
            shortest_switch.set_vtable(host, vlan)

        body = self.html()

        return Response(content_type='text/html', body=body)
项目:sdn    作者:ray6    | 项目源码 | 文件源码
def put_vtable(self, req, **kwargs):
        simple_switch = self.simple_switch_spp

        #Check request is not Blank.
        try:
            request_body_size = int(req.environ.get('CONTENT_LENGTH',0))
        except(ValueError):
            request_body_size = 0

        d = parse_qs(req.body)

        #Interpret the vlan list
        for key, value in d.items():
            host = ('00:00:00:00:00:0'+key[4])
            vlan = value[0][4]
            simple_switch.set_vtable(host, vlan)

        body = self.html()

        return Response(content_type='text/html', body=body)
项目:bdocker    作者:indigo-dc    | 项目源码 | 文件源码
def execute_get(self, path, parameters):
        """Execute GET request.

        This method execute a POST request on the endpoint.

        :param path: path of the request
        :param parameters: parameters to include in the request
        :return: json response
        """
        try:
            query_string = get_query_string(parameters)
            req = self._get_req(path, query_string=query_string,
                                method="GET")
            response = req.get_response()
        except Exception as e:
            response = webob.Response(status=500, body=str(e))
        json_response = self._get_from_response(response)
        return json_response
项目:bdocker    作者:indigo-dc    | 项目源码 | 文件源码
def execute_post(self, path, parameters):
        """Execute POST request.

        This method execute a POST request on the endpoint.

        :param path: path of the request
        :param parameters: parameters to include in the request
        :return: json response
        """
        try:
            body = make_body(parameters)
            req = self._get_req(path, content_type="application/json",
                                body=body, method="POST")
            response = req.get_response()
        except Exception as e:
            response = webob.Response(status=500, body=str(e))
        json_response = self._get_from_response(response)
        return json_response
项目:bdocker    作者:indigo-dc    | 项目源码 | 文件源码
def execute_delete(self, path, parameters):
        """Execute DELETE request.

        This method execute a DELETE request on the endpoint.

        :param path: path of the request
        :param parameters: parameters to include in the request
        :return: json response
        """
        try:
            query_string = get_query_string(parameters)
            req = self._get_req(path, method="DELETE",
                                query_string=query_string)
            response = req.get_response(None)
        except Exception as e:
            response = webob.Response(status=500, body=str(e))
        json_response = self._get_from_response(response)
        return json_response
项目:bdocker    作者:indigo-dc    | 项目源码 | 文件源码
def execute_put(self, path, parameters):
        """Execute PUT request.

        This method execute a PUT request on the endpoint.

        :param path: path of the request
        :param parameters: parameters to include in the request
        :return: json response
        """
        try:
            body = make_body(parameters)
            req = self._get_req(path, content_type="application/json",
                                body=body, method="PUT")
            response = req.get_response()
        except Exception as e:
            response = webob.Response(status=500, body=str(e))
        json_response = self._get_from_response(response)
        return json_response
项目:Trusted-Platform-Module-nova    作者:BU-NU-CLOUD-SP16    | 项目源码 | 文件源码
def setUp(self):
        super(TestKeystoneMiddlewareRoles, self).setUp()

        @webob.dec.wsgify()
        def role_check_app(req):
            context = req.environ['nova.context']

            if "knight" in context.roles and "bad" not in context.roles:
                return webob.Response(status="200 Role Match")
            elif context.roles == ['']:
                return webob.Response(status="200 No Roles")
            else:
                raise webob.exc.HTTPBadRequest("unexpected role header")

        self.middleware = nova.api.auth.NovaKeystoneContext(role_check_app)
        self.request = webob.Request.blank('/')
        self.request.headers['X_USER'] = 'testuser'
        self.request.headers['X_TENANT_ID'] = 'testtenantid'
        self.request.headers['X_AUTH_TOKEN'] = 'testauthtoken'
        self.request.headers['X_SERVICE_CATALOG'] = jsonutils.dumps({})

        self.roles = "pawn, knight, rook"
项目:Trusted-Platform-Module-nova    作者:BU-NU-CLOUD-SP16    | 项目源码 | 文件源码
def test_resource_headers_are_utf8(self):
        resp = webob.Response(status_int=202)
        resp.headers['x-header1'] = 1
        resp.headers['x-header2'] = u'header2'
        resp.headers['x-header3'] = u'header3'

        class Controller(object):
            def index(self, req):
                return resp

        req = webob.Request.blank('/tests')
        app = fakes.TestRouter(Controller())
        response = req.get_response(app)
        for val in six.itervalues(response.headers):
            # All headers must be utf8
            self.assertThat(val, matchers.EncodedByUTF8())
        self.assertEqual(b'1', response.headers['x-header1'])
        self.assertEqual(b'header2', response.headers['x-header2'])
        self.assertEqual(b'header3', response.headers['x-header3'])
项目:Trusted-Platform-Module-nova    作者:BU-NU-CLOUD-SP16    | 项目源码 | 文件源码
def serialize(self, request, content_type):
        """Serializes the wrapped object.

        Utility method for serializing the wrapped object.  Returns a
        webob.Response object.
        """

        serializer = self.serializer

        body = None
        if self.obj is not None:
            body = serializer.serialize(self.obj)
        response = webob.Response(body=body)
        if response.headers.get('Content-Length'):
            # NOTE(andreykurilin): we need to encode 'Content-Length' header,
            # since webob.Response auto sets it if "body" attr is presented.
            # https://github.com/Pylons/webob/blob/1.5.0b0/webob/response.py#L147
            response.headers['Content-Length'] = utils.utf8(
                response.headers['Content-Length'])
        response.status_int = self.code
        for hdr, value in self._headers.items():
            response.headers[hdr] = utils.utf8(value)
        response.headers['Content-Type'] = utils.utf8(content_type)
        return response
项目:Trusted-Platform-Module-nova    作者:BU-NU-CLOUD-SP16    | 项目源码 | 文件源码
def delete(self, req, domain_id, id):
        """Delete the entry identified by req and id."""
        context = req.environ['nova.context']
        authorize(context)
        domain = _unquote_domain(domain_id)
        name = id

        try:
            self.network_api.delete_dns_entry(context, name, domain)
        except exception.NotFound as e:
            raise webob.exc.HTTPNotFound(explanation=e.format_message())
        except NotImplementedError:
            msg = _("Unable to delete dns entry")
            raise webob.exc.HTTPNotImplemented(explanation=msg)

        return webob.Response(status_int=202)
项目:Trusted-Platform-Module-nova    作者:BU-NU-CLOUD-SP16    | 项目源码 | 文件源码
def _disassociate_host_only(self, req, id, body):
        context = req.environ['nova.context']
        authorize(context)
        # NOTE(shaohe-feng): back-compatible with db layer hard-code
        # admin permission checks.  call db API objects.Network.associate
        nova_context.require_admin_context(context)

        try:
            self.network_api.associate(context, id, host=None)
        except exception.NetworkNotFound:
            msg = _("Network not found")
            raise exc.HTTPNotFound(explanation=msg)
        except NotImplementedError:
            msg = _('Disassociate host is not implemented by the configured '
                    'Network API')
            raise exc.HTTPNotImplemented(explanation=msg)
        return webob.Response(status_int=202)
项目:Trusted-Platform-Module-nova    作者:BU-NU-CLOUD-SP16    | 项目源码 | 文件源码
def _disassociate_project_only(self, req, id, body):
        context = req.environ['nova.context']
        authorize(context)
        # NOTE(shaohe-feng): back-compatible with db layer hard-code
        # admin permission checks.  call db API objects.Network.associate
        nova_context.require_admin_context(context)

        try:
            self.network_api.associate(context, id, project=None)
        except exception.NetworkNotFound:
            msg = _("Network not found")
            raise exc.HTTPNotFound(explanation=msg)
        except NotImplementedError:
            msg = _('Disassociate project is not implemented by the '
                    'configured Network API')
            raise exc.HTTPNotImplemented(explanation=msg)

        return webob.Response(status_int=202)
项目:Trusted-Platform-Module-nova    作者:BU-NU-CLOUD-SP16    | 项目源码 | 文件源码
def delete(self, req, id):
        context = req.environ['nova.context']
        authorize(context)

        # get the floating ip object
        try:
            floating_ip = self.network_api.get_floating_ip(context, id)
        except (exception.NotFound, exception.InvalidID):
            msg = _("Floating IP not found for ID %s") % id
            raise webob.exc.HTTPNotFound(explanation=msg)
        address = floating_ip['address']

        # get the associated instance object (if any)
        instance = get_instance_by_floating_ip_addr(self, context, address)
        try:
            self.network_api.disassociate_and_release_floating_ip(
                context, instance, floating_ip)
        except exception.Forbidden:
            raise webob.exc.HTTPForbidden()
        except exception.CannotDisassociateAutoAssignedFloatingIP:
            msg = _('Cannot disassociate auto assigned floating IP')
            raise webob.exc.HTTPForbidden(explanation=msg)
        return webob.Response(status_int=202)
项目:stalker_pyramid    作者:eoyilmaz    | 项目源码 | 文件源码
def get_client_users_out_stack(request):

    logger.debug('get_client_users_out_stack is running')

    client_id = request.matchdict.get('id', -1)
    client = Client.query.filter_by(id=client_id).first()
    if not client:
        transaction.abort()
        return Response('Can not find a client with id: %s' % client_id, 500)

    sql_query = """
            select
                "User_SimpleEntities".name,
                "User_SimpleEntities".id
            from "Users"
            left outer join "Client_Users" on "Client_Users".uid = "Users".id
            join "SimpleEntities" as "User_SimpleEntities" on "User_SimpleEntities".id = "Users".id

            where "Client_Users".cid != %(client_id)s or "Client_Users".cid is Null
    """

    sql_query = sql_query % {'client_id': client_id}
    result = DBSession.connection().execute(sql_query)

    users = []
    for r in result.fetchall():
        user = {
            'name': r[0],
            'id': r[1]
        }
        users.append(user)

    resp = Response(
        json_body=users
    )

    return resp
项目:stalker_pyramid    作者:eoyilmaz    | 项目源码 | 文件源码
def update_daily(request):
    """runs when updating a daily
    """

    logged_in_user = get_logged_in_user(request)
    utc_now = local_to_utc(datetime.datetime.now())

    daily_id = request.matchdict.get('id', -1)
    daily = Daily.query.filter(Daily.id == daily_id).first()

    if not daily:
        transaction.abort()
        return Response('No daily with id : %s' % daily_id, 500)

    name = request.params.get('name')
    description = request.params.get('description')

    status_id = request.params.get('status_id')
    status = Status.query.filter(Status.id == status_id).first()

    if not name:
        return Response('Please supply a name', 500)

    if not description:
        return Response('Please supply a description', 500)

    if not status:
        return Response('There is no status with code: %s' % status.code, 500)

    daily.name = name
    daily.description = description
    daily.status = status
    daily.date_updated = utc_now
    daily.updated_by = logged_in_user

    request.session.flash('success: Successfully updated daily')
    return Response('Successfully updated daily')
项目:stalker_pyramid    作者:eoyilmaz    | 项目源码 | 文件源码
def get_assets_types(request):
    """returns the Asset Types
    """
    sql_query = """select
     "Assets_Types_SimpleEntities".id,
     "Assets_Types_SimpleEntities".name

     from "Assets"

     join "SimpleEntities" as "Assets_SimpleEntities" on "Assets_SimpleEntities".id = "Assets".id
     join "SimpleEntities" as "Assets_Types_SimpleEntities" on "Assets_Types_SimpleEntities".id = "Assets_SimpleEntities".type_id

     group by
        "Assets_Types_SimpleEntities".name,
        "Assets_Types_SimpleEntities".id
     order by "Assets_Types_SimpleEntities".name
     """

    result = DBSession.connection().execute(sql_query)

    return_data = [
        {
            'asset_type_id': r[0],
            'asset_type_name': r[1]

        }
        for r in result.fetchall()
    ]

    content_range = '%s-%s/%s'

    type_count = len(return_data)
    content_range = content_range % (0, type_count - 1, type_count)

    logger.debug('content_range : %s' % content_range)

    resp = Response(
        json_body=return_data
    )
    resp.content_range = content_range
    return resp
项目:stalker_pyramid    作者:eoyilmaz    | 项目源码 | 文件源码
def update_budget(request):
    """runs when updating a budget
    """

    logged_in_user = get_logged_in_user(request)
    utc_now = local_to_utc(datetime.datetime.now())

    budget_id = request.matchdict.get('id', -1)
    budget = Budget.query.filter(Budget.id == budget_id).first()

    if not budget:
        transaction.abort()
        return Response('No budget with id : %s' % budget_id, 500)

    name = request.params.get('name')
    description = request.params.get('description')

    status_id = request.params.get('status_id')
    status = Status.query.filter(Status.id == status_id).first()

    if not name:
        return Response('Please supply a name', 500)

    if not description:
        return Response('Please supply a description', 500)

    if not status:
        return Response('There is no status with code: %s' % status.code, 500)

    budget.name = name
    budget.description = description
    budget.status = status
    budget.date_updated = utc_now
    budget.updated_by = logged_in_user

    request.session.flash('success: Successfully updated budget')
    return Response('Successfully updated budget')
项目:stalker_pyramid    作者:eoyilmaz    | 项目源码 | 文件源码
def delete_budgetentry_action(budgetentry):

    logger.debug('delete_budgetentry_action %s' % budgetentry.name)
    budgetentry_name = budgetentry.name
    try:
        DBSession.delete(budgetentry)
        transaction.commit()
    except Exception as e:
        transaction.abort()
        c = StdErrToHTMLConverter(e)
        transaction.abort()
        # return Response(c.html(), 500)
    # return Response('Successfully deleted good with name %s' % budgetentry_name)