Exemple #1
0
def test_if_range_match_etag_weak():
    ir = IfRange.parse('W/"ETAG"')
    eq_(str(ir), '')
    assert Response(etag='ETAG') not in ir
    assert Response(etag='W/"ETAG"') not in ir
Exemple #2
0
 def get_dpids(self, req, **_kwargs):
     dps = list(self.dpset.dps.keys())
     body = json.dumps(dps)
     return Response(content_type='application/json', body=body)
    def set_tcp_port(self, ip_src, ip_dst, tcp1, tcp2, vlan_src, vlan_dst,
                     inport, outport, mode):
        flows = []
        if mode == 'add':
            cmd = self.dp.ofproto.OFPFC_ADD
        elif mode == 'delete':
            cmd = self.dp.ofproto.OFPFC_DELETE_STRICT

        match = {
            "in_port": inport,
            "dl_vlan": int(vlan_src),
            "ip_proto": 6,
            "tcp_dst": int(tcp1),
            "ipv4_src": ip_src,
            "ipv4_dst": ip_dst,
            "eth_type": 2048
        }
        actions = [{
            "type": "POP_VLAN",
            "ethertype": 33024
        }, {
            "type": "PUSH_VLAN",
            "ethertype": 33024
        }, {
            "type": "SET_FIELD",
            "field": "vlan_vid",
            "value": 4096 + int(vlan_dst)
        }, {
            "type": "SET_FIELD",
            "field": "tcp_dst",
            "value": int(tcp2)
        }, {
            "type": "OUTPUT",
            "port": outport
        }]

        flow = self._to_of_flow(priority=1000, match=match, actions=actions)
        flows.append(flow)

        try:
            ofctl_v1_3.mod_flow_entry(self.dp, flow, cmd)
        except:
            raise ValueError('Invalid rule parameter.')

        match = {
            "in_port": outport,
            "dl_vlan": int(vlan_dst),
            "ipv4_src": ip_dst,
            "ip_proto": 6,
            "tcp_src": int(tcp2),
            "ipv4_dst": ip_src,
            "eth_type": 2048
        }
        actions = [{
            "type": "POP_VLAN",
            "ethertype": 33024
        }, {
            "type": "PUSH_VLAN",
            "ethertype": 33024
        }, {
            "type": "SET_FIELD",
            "field": "vlan_vid",
            "value": 4096 + int(vlan_src)
        }, {
            "type": "SET_FIELD",
            "field": "tcp_src",
            "value": int(tcp1)
        }, {
            "type": "OUTPUT",
            "port": inport
        }]

        flow = self._to_of_flow(priority=1000, match=match, actions=actions)
        flows.append(flow)

        try:
            ofctl_v1_3.mod_flow_entry(self.dp, flow, cmd)
        except:
            raise ValueError('Invalid rule parameter.')

        msg = json.dumps({'result': 'Rules added!'})
        return Response(content_type='application/json', body=msg)
Exemple #4
0
 def test_app(req):
     return Response('%s: %s' % (req.POST['speaker'],
                                 req.POST['words']))
Exemple #5
0
 def test_app(req):
     return Response('whoa')
Exemple #6
0
        if not add_form:
            for field_name in project_schema.fields.keys():
                defaults[field_name] = getattr(project, field_name)

            if defaults['start_date']:
                defaults['start_date'] = defaults['start_date'].strftime(
                    '%d.%m.%Y')
            if defaults['end_date']:
                defaults['end_date'] = defaults['end_date'].strftime(
                    '%d.%m.%Y')

    form = render_template('templates/project_edit.pt',
                           project=project,
                           add_form=add_form,
                           api=TemplateAPI(request))
    # FormEncode fills template with default values
    form = htmlfill.render(form, defaults=defaults, errors=errors)
    return Response(form)


def project_view(context, request):

    project = context
    competence_cloud = project_competence_cloud_view(context, request)

    return dict(api=TemplateAPI(request),
                project=project,
                request=request,
                comments_view=comments_view,
                competence_cloud=competence_cloud)
Exemple #7
0
    def getFeed(self):
        """Get XML representing information in the middleware"""

        entries_xml = []

        for entry in self.middleware.entries:
            request = entry['request']
            response = entry.get('response')
            begin = time.localtime(request['begin'])
            entry_id = self._generateEntryTagURI(entry)
            entry_title = '%s %s ' % (request['method'], request['url'])

            short_url = request['url']
            max_url_len = 40
            if len(short_url) > max_url_len:
                prefix = short_url[:9]
                suffix = short_url[-max_url_len + 9:]
                short_url = prefix + '...' + suffix
            entry_title = '%s %s ' % (request['method'], short_url)

            # Make the <rz:cgi_variable> nodes into a string
            cgivars = ""
            for k, v in request['cgi_variables']:
                newv = cgi.escape(str(v))
                s = cgi_variable_fmt % (k, newv)
                cgivars = cgivars + s

            # Make the <rz:cgi_variable> nodes into a string
            wsgivars = ""
            for k, v in request['wsgi_variables']:
                newv = cgi.escape(str(v))
                s = wsgi_variable_fmt % (k, newv)
                wsgivars = wsgivars + s

            # Make the <rz:request> node
            rzrequest = rzrequest_fmt % {
                'begin': request['begin'],
                'cgi_variables': cgivars,
                'wsgi_variables': wsgivars,
                'method': request['method'],
                'url': request['url'],
            }

            if response is not None:
                # Make the <rz:request> node
                headers = ''
                for k, v in response['headers']:
                    newv = cgi.escape(str(v))
                    s = header_fmt % (k, newv)
                    headers = headers + s

                rzresponse = rzresponse_fmt % {
                    'begin': response['begin'],
                    'end': response['end'],
                    'content-length': response['content-length'],
                    'headers': headers,
                    'status': response['status'],
                    'body': cgi.escape(response['body']),
                }
            else:
                rzresponse = ''

            # Make the atom:entry/atom:content node
            content = contentfmt % {
                'logentry_id': entry_id,
                'rzrequest': rzrequest,
                'rzresponse': rzresponse,
            }

            entry_xml = entryfmt % {
                'entry_id': entry_id,
                'entry_title': cgi.escape(entry_title),
                'updated': time.strftime('%Y-%m-%dT%H:%M:%SZ', begin),
                'summary': cgi.escape(pprint.pformat(entry)),
                'content': content,
            }
            entries_xml.append(entry_xml)

        now = time.time()

        body = feedfmt % {
            'title': 'repoze.debug feed for pid %s' % self.middleware.pid,
            'entries': '\n'.join(entries_xml),
            'feed_id': self._generateFeedTagURI(now, self.middleware.pid),
            'updated': time.strftime('%Y-%m-%dT%H:%M:%SZ',
                                     time.localtime(now)),
        }

        resp = Response(content_type='application/atom+xml', body=body)
        return resp
Exemple #8
0
def main(request):
    return Response("this is a man page")
Exemple #9
0
    def result_service_handler(self, request, suffix=''):
        """
        Handler function for LTI 2.0 JSON/REST result service.

        See http://www.imsglobal.org/lti/ltiv2p0/uml/purl.imsglobal.org/vocab/lis/v2/outcomes/Result/service.html
        An example JSON object:
        {
         "@context" : "http://purl.imsglobal.org/ctx/lis/v2/Result",
         "@type" : "Result",
         "resultScore" : 0.83,
         "comment" : "This is exceptional work."
        }
        For PUTs, the content type must be "application/vnd.ims.lis.v2.result+json".
        We use the "suffix" parameter to parse out the user from the end of the URL.  An example endpoint url is
        http://localhost:8000/courses/org/num/run/xblock/i4x:;_;_org;_num;_lti;_GUID/handler_noauth/lti_2_0_result_rest_handler/user/<anon_id>
        so suffix is of the form "user/<anon_id>"
        Failures result in 401, 404, or 500s without any body.  Successes result in 200.  Again see
        http://www.imsglobal.org/lti/ltiv2p0/uml/purl.imsglobal.org/vocab/lis/v2/outcomes/Result/service.html
        (Note: this prevents good debug messages for the client, so we might want to change this, or the spec)

        Arguments:
            request (xblock.django.request.DjangoWebobRequest):  Request object for current HTTP request
            suffix (unicode):  request path after "lti_2_0_result_rest_handler/".  expected to be "user/<anon_id>"

        Returns:
            webob.response:  response to this request.  See above for details.
        """
        lti_consumer = LtiConsumer(self)

        if self.runtime.debug:
            lti_provider_key, lti_provider_secret = self.lti_provider_key_secret
            log_authorization_header(request, lti_provider_key,
                                     lti_provider_secret)

        if not self.accept_grades_past_due and self.is_past_due:
            return Response(
                status=404
            )  # have to do 404 due to spec, but 400 is better, with error msg in body

        try:
            anon_id = parse_handler_suffix(suffix)
        except LtiError:
            return Response(
                status=404
            )  # 404 because a part of the URL (denoting the anon user id) is invalid
        try:
            lti_consumer.verify_result_headers(request,
                                               verify_content_type=True)
        except LtiError:
            return Response(
                status=401)  # Unauthorized in this case.  401 is right

        user = self.runtime.get_real_user(anon_id)
        if not user:  # that means we can't save to database, as we do not have real user id.
            msg = _("[LTI]: Real user not found against anon_id: {}").format(
                anon_id)
            log.info(msg)
            return Response(
                status=404
            )  # have to do 404 due to spec, but 400 is better, with error msg in body

        try:
            # Call the appropriate LtiConsumer method
            args = []
            if request.method == 'PUT':
                # Request body should be passed as an argument
                # to result handler method on PUT
                args.append(request.body)
            response_body = getattr(lti_consumer, "{}_result".format(
                request.method.lower()))(user, *args)
        except (AttributeError, LtiError):
            return Response(status=404)

        return Response(
            json.dumps(response_body),
            content_type=LtiConsumer.CONTENT_TYPE_RESULT_JSON,
        )
Exemple #10
0
def hello(request):
    name = request.params.get('name', 'anon')
    body = 'hello {}'.format(escape(name))
    return Response(body)
Exemple #11
0
def favicon(request):
    with open('favicon.ico', 'rb') as f:
        resp = Response(body=f.read(), content_type='image/x-icon')
        return resp
Exemple #12
0
    def delete(self, req, id):
        """
        Deletes the image and all its chunks from the Glance

        :param req: The WSGI/Webob Request object
        :param id: The opaque image identifier

        :raises HttpBadRequest if image registry is invalid
        :raises HttpNotFound if image or any chunk is not available
        :raises HttpUnauthorized if image or any chunk is not
                deleteable by the requesting user
        """
        self._enforce(req, 'delete_image')

        image = self.get_image_meta_or_404(req, id)
        if image['protected']:
            msg = _("Image is protected")
            LOG.debug(msg)
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")

        if image['status'] == 'pending_delete':
            msg = (_("Forbidden to delete a %s image.") % image['status'])
            LOG.debug(msg)
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        elif image['status'] == 'deleted':
            msg = _("Image %s not found.") % id
            LOG.debug(msg)
            raise HTTPNotFound(explanation=msg,
                               request=req,
                               content_type="text/plain")

        if image['location'] and CONF.delayed_delete:
            status = 'pending_delete'
        else:
            status = 'deleted'

        ori_status = image['status']

        try:
            # Update the image from the registry first, since we rely on it
            # for authorization checks.
            # See https://bugs.launchpad.net/glance/+bug/1065187
            image = registry.update_image_metadata(req.context, id,
                                                   {'status': status})

            try:
                # The image's location field may be None in the case
                # of a saving or queued image, therefore don't ask a backend
                # to delete the image if the backend doesn't yet store it.
                # See https://bugs.launchpad.net/glance/+bug/747799
                if image['location']:
                    upload_utils.initiate_deletion(req, image['location'], id,
                                                   CONF.delayed_delete)
            except Exception as e:
                registry.update_image_metadata(req.context, id,
                                               {'status': ori_status})
                raise e
            registry.delete_image_metadata(req.context, id)
        except exception.NotFound as e:
            msg = _("Failed to find image to delete: %(e)s") % {'e': e}
            for line in msg.split('\n'):
                LOG.info(line)
            raise HTTPNotFound(explanation=msg,
                               request=req,
                               content_type="text/plain")
        except exception.Forbidden as e:
            msg = _("Forbidden to delete image: %(e)s") % {'e': e}
            for line in msg.split('\n'):
                LOG.info(line)
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        else:
            self.notifier.info('image.delete', redact_loc(image))
            return Response(body='', status=200)
Exemple #13
0

_ = TranslationStringFactory('cone.app')


@view_config('settings_tab_content', xhr=True, permission='manage')
def settings_tab_content(model, request):
    """Used by jquerytools tabs plugin to get settings section content.
    """
    try:
        rendered = render_tile(model, request, 'content')
    except Exception, e:
        localizer = get_localizer(request)
        error = localizer.translate(_('error', default='Error'))
        rendered = '<div>%s: %s</div>' % (error, format_traceback())
    return Response('<div class="%s">%s</div>' % (model.name, rendered))


@tile('content', 'templates/settings.pt',
      interface=AppSettings, permission='manage')
class AppSettings(Tile):

    @property
    def tabs(self):
        ret = list()
        for val in self.model.values():
            ret.append({
                'title': val.metadata.title,
                'target': make_url(self.request,
                                   node=val,
                                   resource='settings_tab_content'),
Exemple #14
0
 def t(tag, res, raw, strong):
     eq_(Response(etag=tag).etag, res)
     eq_(Response(etag=tag).headers.get('etag'), raw)
     eq_(Response(etag=tag).etag_strong, strong)
Exemple #15
0
def get_cookie(req):
    cookies = ['%s: %s' % i for i in sorted(req.cookies.items())]
    return Response('\n'.join(cookies))
 def __call__(self, environ, start_response):
     req = Request(environ)
     path_info = req.path_info
     resp = self.serve_file(req)
     resp = resp or Response(status="404 Not Found")
     return resp(environ, start_response)
    def upload_url(self, data, suffix=''):  # pylint: disable=unused-argument
        """
        Request a URL to be used for uploading content related to this
        submission.

        Returns:
            A URL to be used to upload content associated with this submission.

        """
        file = data.POST['file'].file
        data = json.loads(data.POST['objArr'])
        if 'contentType' not in data or 'filename' not in data:
            return {
                'success': False,
                'msg': self._(u"There was an error uploading your file.")
            }
        content_type = data['contentType']
        file_name = data['filename']
        file_name_parts = file_name.split('.')
        file_num = int(data.get('filenum', 0))
        file_ext = file_name_parts[-1] if len(file_name_parts) > 1 else None

        if self.file_upload_type == 'image' and content_type not in self.ALLOWED_IMAGE_MIME_TYPES:
            return {
                'success': False,
                'msg': self._(u"Content type must be GIF, PNG or JPG.")
            }

        if self.file_upload_type == 'pdf-and-image' and content_type not in self.ALLOWED_FILE_MIME_TYPES:
            return {
                'success': False,
                'msg': self._(u"Content type must be PDF, GIF, PNG or JPG.")
            }

        if self.file_upload_type == 'custom' and file_ext.lower(
        ) not in self.white_listed_file_types:
            return {
                'success':
                False,
                'msg':
                self._(u"File type must be one of the following types: {}").
                format(', '.join(self.white_listed_file_types))
            }

        if file_ext in self.FILE_EXT_BLACK_LIST:
            return {
                'success': False,
                'msg': self._(u"File type is not allowed.")
            }
        try:
            key = self._get_student_item_key(file_num)
            url = file_upload_api.get_upload_url(key, content_type, file)
            return Response(json.dumps({
                'success': True,
                'url': url
            }),
                            content_type='application/json')
        except FileUploadError:
            logger.exception(
                "FileUploadError:Error retrieving upload URL for the data:{data}."
                .format(data=data))
            return {
                'success': False,
                'msg': self._(u"Error retrieving upload URL.")
            }
Exemple #18
0
 def get_stats(self, req, **kwargs):
     res = Response(content_type='application/json',
                    body=json.dumps(self.port_stats_app.statistics,
                                    cls=StatsEncoder))
     res.headers['Access-Control-Allow-Origin'] = '*'
     return res
Exemple #19
0
 def list_Flow_Stat(self, req, **kwargs):
     return Response(content_type='application/json',
                     body=self.simple_switch_app.flowStat)
Exemple #20
0
 def create_response(self, return_value):
     return Response(body='success: method was called %s times' %
                     fixture.method_called)
Exemple #21
0
 def test_app(req):
     return Response(resp_str)
Exemple #22
0
 def create_exception_response(self, exception):
     return Response(body='exception: method was called %s times' %
                     fixture.method_called)
Exemple #23
0
 def test_app(req):
     self.assertEqual(req.method, 'PUT')
     return Response(req.body)
Exemple #24
0
    def handle_get_token(self, req):
        """
        Handles the various `request for token and service end point(s)` calls.
        There are various formats to support the various auth servers in the
        past. Examples::

            GET <auth-prefix>/v1/<act>/auth
                X-Auth-User: <act>:<usr>  or  X-Storage-User: <usr>
                X-Auth-Key: <key>         or  X-Storage-Pass: <key>
            GET <auth-prefix>/auth
                X-Auth-User: <act>:<usr>  or  X-Storage-User: <act>:<usr>
                X-Auth-Key: <key>         or  X-Storage-Pass: <key>
            GET <auth-prefix>/v1.0
                X-Auth-User: <act>:<usr>  or  X-Storage-User: <act>:<usr>
                X-Auth-Key: <key>         or  X-Storage-Pass: <key>

        On successful authentication, the response will have X-Auth-Token and
        X-Storage-Token set to the token to use with Swift and X-Storage-URL
        set to the URL to the default Swift cluster to use.

        :param req: The webob.Request to process.
        :returns: webob.Response, 2xx on success with data set as explained
                  above.
        """
        # Validate the request info
        try:
            pathsegs = split_path(req.path_info, minsegs=1, maxsegs=3,
                                  rest_with_last=True)
        except ValueError:
            return HTTPNotFound(request=req)
        if pathsegs[0] == 'v1' and pathsegs[2] == 'auth':
            account = pathsegs[1]
            user = req.headers.get('x-storage-user')
            if not user:
                user = req.headers.get('x-auth-user')
                if not user or ':' not in user:
                    return HTTPUnauthorized(request=req)
                account2, user = user.split(':', 1)
                if account != account2:
                    return HTTPUnauthorized(request=req)
            key = req.headers.get('x-storage-pass')
            if not key:
                key = req.headers.get('x-auth-key')
        elif pathsegs[0] in ('auth', 'v1.0'):
            user = req.headers.get('x-auth-user')
            if not user:
                user = req.headers.get('x-storage-user')
            if not user or ':' not in user:
                return HTTPUnauthorized(request=req)
            account, user = user.split(':', 1)
            key = req.headers.get('x-auth-key')
            if not key:
                key = req.headers.get('x-storage-pass')
        else:
            return HTTPBadRequest(request=req)
        if not all((account, user, key)):
            return HTTPUnauthorized(request=req)
        # Authenticate user
        account_user = account + ':' + user
        if account_user not in self.users:
            return HTTPUnauthorized(request=req)
        if self.users[account_user]['key'] != key:
            return HTTPUnauthorized(request=req)
        # Get memcache client
        memcache_client = cache_from_env(req.environ)
        if not memcache_client:
            raise Exception('Memcache required')
        # See if a token already exists and hasn't expired
        token = None
        memcache_user_key = '%s/user/%s' % (self.reseller_prefix, account_user)
        candidate_token = memcache_client.get(memcache_user_key)
        if candidate_token:
            memcache_token_key = \
                '%s/token/%s' % (self.reseller_prefix, candidate_token)
            cached_auth_data = memcache_client.get(memcache_token_key)
            if cached_auth_data:
                expires, groups = cached_auth_data
                if expires > time():
                    token = candidate_token
        # Create a new token if one didn't exist
        if not token:
            # Generate new token
            token = '%stk%s' % (self.reseller_prefix, uuid4().hex)
            expires = time() + self.token_life
            groups = [account, account_user]
            groups.extend(self.users[account_user]['groups'])
            if '.admin' in groups:
                groups.remove('.admin')
                account_id = self.users[account_user]['url'].rsplit('/', 1)[-1]
                groups.append(account_id)
            groups = ','.join(groups)
            # Save token
            memcache_token_key = '%s/token/%s' % (self.reseller_prefix, token)
            memcache_client.set(memcache_token_key, (expires, groups),
                                timeout=float(expires - time()))
            # Record the token with the user info for future use.
            memcache_user_key = \
                '%s/user/%s' % (self.reseller_prefix, account_user)
            memcache_client.set(memcache_user_key, token,
                                timeout=float(expires - time()))
        return Response(request=req,
            headers={'x-auth-token': token, 'x-storage-token': token,
                     'x-storage-url': self.users[account_user]['url']})
Exemple #25
0
 def test_app(req):
     return Response('Say wha!?')
Exemple #26
0
def redirect(req):
    loc = req.params['to']
    resp = Response("You are being redirected to %s" % loc)
    resp.location = loc
    resp.status = int(req.params.get('type', 302))
    return resp
 def get_ovs(self, req, **kwargs):
     body = json.dumps({'ovs': self.ovs})
     return Response(content_type='application/json', body=body)
Exemple #28
0
def echo_one(req):
    resp = repr(req.environ.get(req.params['var']))
    return Response(resp)
Exemple #29
0
    def get_conf_handler(self, req, **kwargs):

        body = json.dumps({'dst': self.dst,
                           'channels': self.channels})

        return Response(content_type='application/json', body=body)
Exemple #30
0
 def check_status(self, status, awaiting_status=None):
     resp = Response()
     resp.request = Request.blank('/')
     resp.status = status
     return self.app._check_status(awaiting_status, resp)