Пример #1
2
def browse_view(request, format=None):
    return Response({
        'manuscripts': reverse('manuscript-list', request=request, format=format),
        'chants': reverse('chant-list', request=request, format=format),
        'folios': reverse('folio-list', request=request, format=format),
        'concordances': reverse('concordance-list', request=request, format=format)
    })
Пример #2
1
 def get_links(self, obj):
     request = self.context['request']
     username = obj.get_username()
     return {
         'self': reverse('user_detail', kwargs={User.USERNAME_FIELD: username}, request=request),
         'task': '{}?assigned={}'.format(reverse('task-list', request=request), username)
     }
def api_root(request, format=None):
    return Response({
        'posts': reverse('post-list', request=request, format=format),
        'author': reverse('author-list', request=request, format=format),
        'images': reverse('images', request=request, format=format),
        'friendrequest': reverse('friendrequest', request=request, format=format),
    })
Пример #4
0
def api_root(request, format=None):
    return Response({
        'users':
        reverse('user-list', request=request, format=format),
        'snippets':
        reverse('snippet-list', request=request, format=format)
    })
Пример #5
0
 def get_links(self, obj):
     request = self.context["request"]
     username = obj.get_username()
     return {
         "self": reverse("user-detail", kwargs={User.USERNAME_FIELD: username}, request=request),
         "tasks": "{}?assigned={}".format(reverse("task-list", request=request), username),
     }
Пример #6
0
    def to_representation(self, course_overview):
        course_id = unicode(course_overview.id)
        request = self.context.get('request')
        return {
            # identifiers
            'id': course_id,
            'name': course_overview.display_name,
            'number': course_overview.display_number_with_default,
            'org': course_overview.display_org_with_default,

            # dates
            'start': course_overview.start,
            'start_display': course_overview.start_display,
            'start_type': course_overview.start_type,
            'end': course_overview.end,

            # notification info
            'subscription_id': course_overview.clean_id(padding_char='_'),

            # access info
            'courseware_access': has_access(
                request.user,
                'load_mobile',
                course_overview
            ).to_json(),

            # various URLs
            # course_image is sent in both new and old formats
            # (within media to be compatible with the new Course API)
            'media': {
                'course_image': {
                    'uri': course_overview.course_image_url,
                    'name': 'Course Image',
                }
            },
            'course_image': course_overview.course_image_url,
            'course_about': get_link_for_about_page(course_overview),
            'course_sharing_utm_parameters': get_encoded_course_sharing_utm_params(),
            'course_updates': reverse(
                'course-updates-list',
                kwargs={'course_id': course_id},
                request=request,
            ),
            'course_handouts': reverse(
                'course-handouts-list',
                kwargs={'course_id': course_id},
                request=request,
            ),
            'discussion_url': reverse(
                'discussion_course',
                kwargs={'course_id': course_id},
                request=request,
            ) if course_overview.is_discussion_tab_enabled() else None,

            'video_outline': reverse(
                'video-summary-list',
                kwargs={'course_id': course_id},
                request=request,
            ),
        }
 def _add_to_basket(self, product_id, quantity=1):
     url = reverse('api-basket-add-product')
     data = {
         "url": reverse('product-detail', args=[product_id]),
         "quantity": quantity
     }
     return self.client.post(url, data)
Пример #8
0
    def test_update(self, user1, node1):
        client = APIClient()
        client.force_authenticate(user=user1)

        response = client.patch(
            reverse('node-detail', kwargs={"pk": node1.id}),
            data={
                "meta": "different whatever",
                "enc_version": 2,
            })

        assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED

        response = client.put(
            reverse('node-detail', kwargs={"pk": node1.id}),
            data={
                "name": "whatever",
                "meta": "different whatever",
                "type": 1,
                "enc_version": 2,
            })

        assert response.status_code == status.HTTP_200_OK

        response = client.put(
            reverse('node-detail', kwargs={"pk": 9999}),
            data={
                "name": "whatever",
                "meta": "different whatever",
                "type": 1,
                "enc_version": 2,
            })

        assert response.status_code == status.HTTP_404_NOT_FOUND
Пример #9
0
    def test_setting_reviews_to_order_by_level_works(self):
        self.client.force_login(self.user)

        level_4_review = create_review(create_vocab("level4"), self.user)
        level_4_review.vocabulary.readings.create(level=4, character="level4", kana="level4")

        level_5_review = create_review(create_vocab("level5"), self.user)
        level_5_review.vocabulary.readings.create(level=5, character="level5", kana="level5")

        level_3_review = create_review(create_vocab("level3"), self.user)
        level_3_review.vocabulary.readings.create(level=3, character="level3", kana="level3")

        response = self.client.get(reverse("api:review-current"))
        reviews = response.data["results"]
        actual_review_order = [review["vocabulary"]["readings"][0]["level"] for review in reviews]

        assert len(reviews) == 4
        assert [3, 4, 5, 5] != actual_review_order

        self.user.profile.order_reviews_by_level = True
        self.user.profile.save()

        response = self.client.get(reverse("api:review-current"))
        reviews = response.data["results"]
        actual_review_order = [review["vocabulary"]["readings"][0]["level"] for review in reviews]

        assert len(reviews) == 4
        assert [3, 4, 5, 5] == actual_review_order
Пример #10
0
 def test_change_product_photo(self):
     # create dummy image and upload image      
     imgfile = StringIO.StringIO('GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;')
     imgfile.name = 'test_img_file.gif'
     data = {'image': imgfile} 
     url = reverse('vendor-products-photo-add')       
     photo_response = self.client.post(url, data, format='multipart')
     self.assertEqual(photo_response.status_code, status.HTTP_201_CREATED)
     self.assertEqual(photo_response.data['id'], 1)    
     
     # add image to product
     url =  reverse('vendor-products-details', kwargs={'product_id': '2'})
     data = {'photo': photo_response.data['id']}
     response = self.client.patch(url, data)
     self.assertEqual(response.status_code, status.HTTP_200_OK)  
     #print "updated product: ", response.content
     self.assertEqual(response.content, '{"id": 2, "name": "tomato", "description": "test product", "vendor": 2, "photo": 1, "stock": "IS", "tags": ["one", "two"], "category": 1}')
     
     # upload new image 
     new_imgfile = StringIO.StringIO('GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;')
     new_imgfile.name = 'new_img_file.gif'
     data = {'image': new_imgfile} 
     url = reverse('vendor-products-photo-add')       
     new_photo_response = self.client.post(url, data, format='multipart')
     self.assertEqual(new_photo_response.status_code, status.HTTP_201_CREATED)
     self.assertEqual(new_photo_response.data['id'], 2)  
     
     # change image of the product
     url =  reverse('vendor-products-details', kwargs={'product_id': '2'})
     data = {'photo': new_photo_response.data['id']}
     response = self.client.patch(url, data)
     self.assertEqual(response.status_code, status.HTTP_200_OK)  
     #print "updated product: ", response.content
     self.assertEqual(response.content, '{"id": 2, "name": "tomato", "description": "test product", "vendor": 2, "photo": 2, "stock": "IS", "tags": ["one", "two"], "category": 1}')       
Пример #11
0
 def test_change_vendor_photo(self):
     # create dummy image and upload image      
     imgfile = StringIO.StringIO('GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;')
     imgfile.name = 'test_img_file.gif'
     data = {'image': imgfile} 
     url = reverse('vendor-photo-add')       
     photo_response = self.client.post(url, data, format='multipart')
     self.assertEqual(photo_response.status_code, status.HTTP_201_CREATED)
     self.assertEqual(photo_response.data['id'], 1)    
     
     # add image to product
     url =  reverse('vendor')
     data = {'id': 2, 'photo': photo_response.data['id']}
     response = self.client.patch(url, data)
     self.assertEqual(response.status_code, status.HTTP_200_OK)  
     print "updated vendor: ", response.content
     self.assertEqual(response.data['photo']['id'], 1)
     
     # upload new image 
     new_imgfile = StringIO.StringIO('GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;')
     new_imgfile.name = 'new_img_file.gif'
     data = {'image': new_imgfile} 
     url = reverse('vendor-photo-add')       
     new_photo_response = self.client.post(url, data, format='multipart')
     self.assertEqual(new_photo_response.status_code, status.HTTP_201_CREATED)
     self.assertEqual(new_photo_response.data['id'], 2)  
     
     # change image of the product
     url =  reverse('vendor')
     data = {'id': 2, 'photo': new_photo_response.data['id']}
     response = self.client.patch(url, data)
     self.assertEqual(response.status_code, status.HTTP_200_OK)  
     print "updated vendor: ", response.content
     self.assertEqual(response.data['photo']['id'], 2)   
Пример #12
0
	def get(self, request, *args, **kwargs):
		response = Response({
			'snippets': reverse('snippet-list', request=request),
			'tags': reverse('tag-list', request=request),
			'people': reverse('person-list', request=request)
			})
		return response
Пример #13
0
    def retrieve(self, request, project, jm, pk=None):
        """
        GET method implementation for detail view

        Return a single job with log_references and
        artifact names and links to the artifact blobs.
        """
        obj = jm.get_job(pk)
        if obj:
            job = obj[0]
            job["resource_uri"] = reverse("jobs-detail",
                kwargs={"project": jm.project, "pk": job["id"]})
            job["logs"] = jm.get_log_references(pk)

            # make artifact ids into uris
            artifact_refs = jm.get_job_artifact_references(pk)
            job["artifacts"] = []
            for art in artifact_refs:
                ref = reverse("artifact-detail",
                              kwargs={"project": jm.project, "pk": art["id"]})
                art["resource_uri"] = ref
                job["artifacts"].append(art)

            option_collections = jm.refdata_model.get_all_option_collections()
            job["platform_opt"] = option_collections[job["option_collection_hash"]]['opt']

            return Response(job)
        else:
            return Response("No job with id: {0}".format(pk), 404)
Пример #14
0
def reverses(request, format=None):
    return {
        'events':       reverse('recommender-events', request=request, format=format),
        'recommender':  reverse('recommender-recommender', request=request, format=format),
        'items':        reverse('recommender-items', request=request, format=format),
        'redirect':     reverse('recommender-redirect', request=request, format=format),
    }
Пример #15
0
 def to_representation(self, course_overview):
     course_id = unicode(course_overview.id)
     request = self.context.get("request")
     return {
         # identifiers
         "id": course_id,
         "name": course_overview.display_name,
         "number": course_overview.display_number_with_default,
         "org": course_overview.display_org_with_default,
         # dates
         "start": course_overview.start,
         "start_display": course_overview.start_display,
         "start_type": course_overview.start_type,
         "end": course_overview.end,
         # notification info
         "subscription_id": course_overview.clean_id(padding_char="_"),
         # access info
         "courseware_access": has_access(request.user, "load_mobile", course_overview).to_json(),
         # various URLs
         # course_image is sent in both new and old formats
         # (within media to be compatible with the new Course API)
         "media": {"course_image": {"uri": course_overview.course_image_url, "name": "Course Image"}},
         "course_image": course_overview.course_image_url,
         "course_about": reverse("about_course", kwargs={"course_id": course_id}, request=request),
         "course_updates": reverse("course-updates-list", kwargs={"course_id": course_id}, request=request),
         "course_handouts": reverse("course-handouts-list", kwargs={"course_id": course_id}, request=request),
         "discussion_url": reverse("discussion_course", kwargs={"course_id": course_id}, request=request)
         if course_overview.is_discussion_tab_enabled()
         else None,
         "video_outline": reverse("video-summary-list", kwargs={"course_id": course_id}, request=request),
     }
Пример #16
0
    def field_to_native(self, obj, field_name):
        request = self.context.get("request", None)
        format = self.format or self.context.get("format", None)
        view_name = self.view_name or self.parent.opts.view_name
        kwargs = {self.pk_url_kwarg: obj.pk}
        try:
            return reverse(view_name, kwargs=kwargs, request=request, format=format)
        except:
            pass

        slug = getattr(obj, self.slug_field, None)

        if not slug:
            raise ValidationError('Could not resolve URL for field using view name "%s"' % view_name)

        kwargs = {self.slug_url_kwarg: slug}
        try:
            return reverse(self.view_name, kwargs=kwargs, request=request, format=format)
        except:
            pass

        kwargs = {self.pk_url_kwarg: obj.pk, self.slug_url_kwarg: slug}
        try:
            return reverse(self.view_name, kwargs=kwargs, request=request, format=format)
        except:
            pass

        raise ValidationError('Could not resolve URL for field using view name "%s"', view_name)
Пример #17
0
    def get(self, request, format=None):
        api = OrderedDict((
            ('version', reverse('stackdio:version',
                                request=request,
                                format=format)),
            ('users', reverse('api:users:user-list',
                              request=request,
                              format=format)),
            ('groups', reverse('api:users:group-list',
                               request=request,
                               format=format)),
            ('current_user', reverse('api:users:currentuser-detail',
                                     request=request,
                                     format=format)),
            ('cloud', reverse('api:cloud:root',
                              request=request,
                              format=format)),
            ('blueprints', reverse('api:blueprints:blueprint-list',
                                   request=request,
                                   format=format)),
            ('formulas', reverse('api:formulas:formula-list',
                                 request=request,
                                 format=format)),
            ('stacks', reverse('api:stacks:stack-list',
                               request=request,
                               format=format)),
            ('volumes', reverse('api:volumes:volume-list',
                                request=request,
                                format=format)),
            ('search', reverse('api:search:search',
                               request=request,
                               format=format)),
        ))

        return Response(api)
Пример #18
0
 def get(self, request):
     result = {
         "Stories": reverse('story-view', request=request),
         "Chapters": reverse('chapter-view', request=request),
         "Contents": reverse('content-view', request=request)
     }
     return Response(result)
Пример #19
0
 def get__links(self, obj):
     links = {
         "phones": reverse('phone-list', kwargs=dict(contact_pk=obj.pk),
                           request=self.context.get('request')),
         "emails": reverse('email-list', kwargs=dict(contact_pk=obj.pk),
                           request=self.context.get('request'))}
     return links
Пример #20
0
def api_root(request, format=None):
    """
    Welcome to the XBee Wi-Fi Cloud Kit API Explorer
    ------------------------------------------------

    From here, you can browse and interact with API resources right in your
    browser, using the same calls made by the frontend. Unauthenticated users
    will have limited visibility into the system, users can log in via the
    login API or via the link in the header.

    From the API root, you will find links for the following resources:

    * `login/logout` - Used for establishing session based authentication
    * `user` - View the user resource associated with your account
    * `devices` - Explore device information for status, data, and
                        configuration
    * `dashboards` - Explore the dashboard resource rendered by the frontend

    """
    return Response({
        'login': reverse('api_login', request=request, format=format),
        'logout': reverse('api_logout', request=request, format=format),
        'user': reverse('deviceclouduser-list',
                        request=request, format=format),
        'dashboards': reverse('dashboard-list', request=request,
                              format=format),
        'devices': reverse('devices-list', request=request, format=format),
    })
Пример #21
0
def api_root(request, format=None):
	return Response({
		'users': reverse('user-list', request=request, format=format),
		'notices': reverse('notice-list', request=request, format=format),
		'students': reverse('student-list', request=request, format=format),
		'faculties': reverse('faculty-list', request=request, format=format),
	})
Пример #22
0
    def fetch_scheduled_on(self, act):
        scheduled_on = {}
        scheduled_activities = EighthScheduledActivity.objects.filter(activity=act).select_related("block")

        # user = self.context.get("user", self.context["request"].user)
        # favorited_activities = set(user.favorited_activity_set
        #                               .values_list("id", flat=True))
        # available_restricted_acts = EighthActivity.restricted_activities_available_to_user(user)

        for scheduled_activity in scheduled_activities:
            scheduled_on[scheduled_activity.block.id] = {
                "id": scheduled_activity.block.id,
                "date": scheduled_activity.block.date,
                "block_letter": scheduled_activity.block.block_letter,
                "url": reverse("api_eighth_block_detail",
                               args=[scheduled_activity.block.id],
                               request=self.context["request"]),
                "roster": {
                    "id": scheduled_activity.id,
                    "url": reverse("api_eighth_scheduled_activity_signup_list",
                                   args=[scheduled_activity.id],
                                   request=self.context["request"]),
                }
            }
        return scheduled_on
Пример #23
0
    def field_to_native(self, obj, field_name):
        request = self.context.get('request', None)
        format = self.format or self.context.get('format', None)
        view_namespace = self.view_namespace if self.view_namespace is not None else self.parent.opts.view_namespace
        view_name = self.view_name or self.parent.opts.view_name
        if view_namespace:
            view_name = "%(namespace)s:%(view)s" % {
                'view':view_name,
                'namespace':view_namespace
            }
        kwargs = {self.pk_url_kwarg: obj.pk}
        try:
            return reverse(view_name, kwargs=kwargs, request=request, format=format)
        except:
            pass

        slug = getattr(obj, self.slug_field, None)

        if not slug:
            raise ValidationError('Could not resolve URL for field using view name "%s"' % view_name)

        kwargs = {self.slug_url_kwarg: slug}
        try:
            return reverse(view_name, kwargs=kwargs, request=request, format=format)
        except:
            pass

        kwargs = {self.pk_url_kwarg: obj.pk, self.slug_url_kwarg: slug}
        try:
            return reverse(view_name, kwargs=kwargs, request=request, format=format)
        except:
            pass

        raise ValidationError('Could not resolve URL for field using view name "%s"', view_name)
Пример #24
0
    def get(self, request, format=None):
        return Response({
            'export-badges': reverse('api:export-badges', request=request,
                                     format=format),
            'export-instructors': reverse('api:export-instructors',
                                          request=request, format=format),
            'export-members': reverse('api:export-members', request=request,
                                      format=format),
            'events-published': reverse('api:events-published',
                                        request=request, format=format),
            'user-todos': reverse('api:user-todos',
                                  request=request, format=format),
            'reports-list': reverse('api:reports-list',
                                    request=request, format=format),

            # "new" API list-type endpoints below
            'airport-list': reverse('api:airport-list', request=request,
                                    format=format),
            'person-list': reverse('api:person-list', request=request,
                                   format=format),
            'event-list': reverse('api:event-list', request=request,
                                  format=format),
            'host-list': reverse('api:host-list', request=request,
                                 format=format),
        })
Пример #25
0
def Root(request):
    return Response({
        'test': reverse('blog_api:test', request=request),
        'categories': reverse('blog_api:category-list', request=request),
        'articles': reverse('blog_api:article-list', request=request),
        'popular-articles': reverse('blog_api:popular-article-list', request=request),
    })
Пример #26
0
def photos_upload_request(request, format=None):
    """
    Use the GET parameter `num_photos` to specify how many photos you would
    like to upload
    """
    num_photos = int(request.GET.get('num_photos', 1))

    response_data = []
    for i in xrange(num_photos):
        pending_photo = Photo.objects.upload_request(author=request.user)

        if settings.USING_LOCAL_PHOTOS:
            upload_url = reverse('photo-upload', [pending_photo.photo_id], request=request)
            fullres_upload_url = reverse('photo-upload', [pending_photo.photo_id], request=request)
        else:
            upload_url = settings.PHOTO_UPLOAD_SERVER_URL + '/photos/upload/' + pending_photo.photo_id + '/'
            fullres_upload_url = settings.PHOTO_UPLOAD_SERVER_URL + '/photos/upload/' + pending_photo.photo_id + '/original/'

        response_data.append({
            'photo_id': pending_photo.photo_id,
            'upload_url': upload_url,
            'fullres_upload_url': fullres_upload_url
            })

    return Response(response_data)
Пример #27
0
 def get(self, request, format=None):
     ret = {}
     for key, url_name in api_root_dict.items():
         ret[key] = reverse.reverse(url_name, request=request, format=format)
     for api_view_key in api_view_urls.keys():
         ret[api_view_key] = reverse.reverse(api_view_urls[api_view_key].name, request=request, format=format)
     return response.Response(ret)
Пример #28
0
    def to_native(self, obj):
        view_name = self.view_name
        request = self.context.get('request', None)
        format = self.format or self.context.get('format', None)
        pk = getattr(obj, 'pk', None)
        if pk is None:
            return
        kwargs = {self.pk_url_kwarg: pk}
        try:
            return reverse(view_name, kwargs=kwargs, request=request, format=format)
        except:
            pass

        slug = getattr(obj, self.slug_field, None)

        if not slug:
            raise ValidationError('Could not resolve URL for field using view name "%s"' % view_name)

        kwargs = {self.slug_url_kwarg: slug}
        try:
            return reverse(self.view_name, kwargs=kwargs, request=request, format=format)
        except:
            pass

        kwargs = {self.pk_url_kwarg: obj.pk, self.slug_url_kwarg: slug}
        try:
            return reverse(self.view_name, kwargs=kwargs, request=request, format=format)
        except:
            pass

        raise ValidationError('Could not resolve URL for field using view name "%s"' % view_name)
Пример #29
0
 def get(self, request, format=None):
     root_url = reverse('api-root', request=request, format=format)
     token_url = reverse('api-token-auth', request=request, format=format)
     links = [
         '<%s>; rel="%s"' % (root_url, 'api-root'),
         '<%s>; rel="%s"' % (token_url, 'api-get-auth-token'),
     ]
     if not request.user.is_anonymous():
         list_name = '{basename}-list'
         detail_name = '{basename}-detail'
         for prefix, viewset, basename in self.router.registry:
             singleton_pk = getattr(viewset, 'singleton_pk', False)
             if singleton_pk:
                 url_name = detail_name.format(basename=basename)
                 kwargs = { 'pk': singleton_pk(viewset(), request) }
             else:
                 url_name = list_name.format(basename=basename)
                 kwargs = {}
             url = reverse(url_name, request=request, format=format, kwargs=kwargs)
             links.append('<%s>; rel="%s"' % (url, url_name))
         # Add user link
         url_name = detail_name.format(basename='user')
         kwargs = { 'pk': request.user.pk }
         url = reverse(url_name, request=request, format=format, kwargs=kwargs)
         links.append('<%s>; rel="%s"' % (url, url_name))
     headers = { 'Link': ', '.join(links) }
     body = {
         name.lower(): getattr(settings, name, None) for name in self.names
     }
     return Response(body, headers=headers)
Пример #30
0
 def get(self, request, *args, **kwargs):
     response = Response(
         {"snippets": reverse("snippet-list", request=request),
          "tags": reverse("tag-list", request=request),
          "people": reverse("person-list", request=request)}
     )
     return response
Пример #31
0
 def get_list_url(cls):
     return 'http://testserver' + reverse('service-certification-list')
Пример #32
0
def api_root(request, format=None):
    return Response({
        'users': reverse('user-list', request=request, format=format),
        'profiles': reverse('profile-list', request=request, format=format),
        'socialnetworks': reverse('socialnetwork-list', request=request, format=format),
        'tshirts': reverse('tshirt-list', request=request, format=format),
        'snippets': reverse('snippet-list', request=request, format=format),
        'mediafiles': reverse('mediafile-list', request=request, format=format),
        'stocks': reverse('stock-list', request=request, format=format),
        'messages': reverse('message-list', request=request, format=format),
        'claps': reverse('clap-list', request=request, format=format),
        'followers': reverse('follower-list', request=request, format=format),
        'notifications': reverse('notification-list', request=request, format=format),
    })
Пример #33
0
 def test_unauthed(self):
     response = self.client.get(reverse('leaderboard-team'))
     self.assertEquals(response.status_code, HTTP_200_OK)
Пример #34
0
    def to_representation(self, block_key):
        """
        Return a serializable representation of the requested block
        """
        # create response data dict for basic fields

        block_structure = self.context['block_structure']
        authorization_denial_reason = block_structure.get_xblock_field(
            block_key, 'authorization_denial_reason')
        authorization_denial_message = block_structure.get_xblock_field(
            block_key, 'authorization_denial_message')

        data = {
            'id':
            six.text_type(block_key),
            'block_id':
            six.text_type(block_key.block_id),
            'lms_web_url':
            reverse(
                'jump_to',
                kwargs={
                    'course_id': six.text_type(block_key.course_key),
                    'location': six.text_type(block_key)
                },
                request=self.context['request'],
            ),
            'student_view_url':
            reverse(
                'render_xblock',
                kwargs={'usage_key_string': six.text_type(block_key)},
                request=self.context['request'],
            ),
        }

        if settings.FEATURES.get(
                "ENABLE_LTI_PROVIDER"
        ) and 'lti_url' in self.context['requested_fields']:
            data['lti_url'] = reverse(
                'lti_provider_launch',
                kwargs={
                    'course_id': six.text_type(block_key.course_key),
                    'usage_id': six.text_type(block_key)
                },
                request=self.context['request'],
            )

        # add additional requested fields that are supported by the various transformers
        for supported_field in SUPPORTED_FIELDS:
            if supported_field.requested_field_name in self.context[
                    'requested_fields']:
                field_value = self._get_field(
                    block_key,
                    supported_field.transformer,
                    supported_field.block_field_name,
                    supported_field.default_value,
                )
                if field_value is not None:
                    # only return fields that have data
                    data[supported_field.serializer_field_name] = field_value

        if 'children' in self.context['requested_fields']:
            children = block_structure.get_children(block_key)
            if children:
                data['children'] = [six.text_type(child) for child in children]

        if authorization_denial_reason and authorization_denial_message:
            data['authorization_denial_reason'] = authorization_denial_reason
            data['authorization_denial_message'] = authorization_denial_message
            for field in data.keys():  # pylint: disable=consider-iterating-dictionary
                if field not in FIELDS_ALLOWED_IN_AUTH_DENIED_CONTENT:
                    del data[field]

        return data
Пример #35
0
            new_filename_utf8 = new_filename.encode('utf-8')

            try:
                seafserv_threaded_rpc.move_file(src_repo_id, src_dir_utf8,
                                                filename_utf8, dst_repo_id,
                                                dst_dir_utf8, new_filename_utf8,
                                                request.user.username)
            except SearpcError, e:
                return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR,
                                 "SearpcError:" + e.msg)

            if request.GET.get('reloaddir', '').lower() == 'true':
                return reloaddir(request, dst_repo_id, dst_dir)
            else:
                resp = Response('success', status=status.HTTP_301_MOVED_PERMANENTLY)
                uri = reverse('FileView', args=[repo_id], request=request)
                resp['Location'] = uri + '?p=' + quote(dst_dir_utf8) + quote(new_filename_utf8)
                return resp
        elif operation.lower() == 'create':
            parent_dir = os.path.dirname(path)
            parent_dir_utf8 = parent_dir.encode('utf-8')
            new_file_name = os.path.basename(path)
            new_file_name = check_filename_with_rename(repo_id, parent_dir,
                                                       new_file_name)
            new_file_name_utf8 = new_file_name.encode('utf-8')
            
            try:
                seafserv_threaded_rpc.post_empty_file(repo_id, parent_dir,
                                                      new_file_name,
                                                      request.user.username)
            except SearpcError, e:
Пример #36
0
def hpc_api_root(request, format=None):
    return Response({
        {% for object in generator.rest_models %}'{{ object.plural }}': reverse('{{ object }}-list', request=request, format=format),
        {% endfor %}
    })
Пример #37
0
    def repository(self, request, **kwargs):
        obj = self.get_object()

        if isinstance(obj, Translation):
            project = obj.subproject.project
        elif isinstance(obj, SubProject):
            project = obj.project
        else:
            project = obj

        if request.method == 'POST':
            serializer = RepoRequestSerializer(data=request.data)
            serializer.is_valid(raise_exception=True)

            data = {
                'result':
                self.repository_operation(
                    request, obj, project,
                    serializer.validated_data['operation'])
            }

            storage = get_messages(request)
            if storage:
                data['detail'] = '\n'.join([m.message for m in storage])

            return Response(data)

        if not can_see_repository_status(request.user, project):
            raise PermissionDenied()

        data = {
            'needs_commit': obj.repo_needs_commit(),
            'needs_merge': obj.repo_needs_merge(),
            'needs_push': obj.repo_needs_push(),
        }

        if isinstance(obj, Project):
            data['url'] = reverse('api:project-repository',
                                  kwargs={'slug': obj.slug},
                                  request=request)
        else:
            data['remote_commit'] = obj.get_last_remote_commit()

            if isinstance(obj, Translation):
                subproject = obj.subproject
                data['url'] = reverse('api:translation-repository',
                                      kwargs={
                                          'subproject__project__slug':
                                          subproject.project.slug,
                                          'subproject__slug':
                                          subproject.slug,
                                          'language__code':
                                          obj.language.code,
                                      },
                                      request=request)
                data['status'] = obj.subproject.repository.status()
                changes = Change.objects.filter(
                    action__in=Change.ACTIONS_REPOSITORY,
                    subproject=obj.subproject,
                )
            else:
                data['url'] = reverse('api:component-repository',
                                      kwargs={
                                          'project__slug': obj.project.slug,
                                          'slug': obj.slug,
                                      },
                                      request=request)
                data['status'] = obj.repository.status()
                changes = Change.objects.filter(
                    action__in=Change.ACTIONS_REPOSITORY,
                    subproject=obj,
                )

            if changes.exists() and changes[0].is_merge_failure():
                data['merge_failure'] = changes[0].target
            else:
                data['merge_failure'] = None

        return Response(data)
Пример #38
0
 def setUp(self):
     self.base_url = reverse("user-resend-activation")
Пример #39
0
    def test_try_to_get_invoice_entries(self):
        url = reverse('invoice-entry-create', kwargs={'document_pk': 1})

        response = self.client.get(url)
        assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED
        assert response.data == {"detail": 'Method "GET" not allowed.'}
Пример #40
0
def api_root(request, format=None):
    return Response({
        'users': reverse('user-list', request=request, format=format),
        'snippets': reverse('snippet-list', request=request, format=format)
    })
Пример #41
0
def test_products_list(client, product_factory):
    """ Тест на получение списка продуктов пользователем """
    product_factory(_quantity=3)
    url = reverse("products-list")
    resp = client.get(url)
    assert resp.status_code == HTTP_200_OK
Пример #42
0
    def test_delete_invoice(self):
        url = reverse('invoice-detail', kwargs={'pk': 1})

        response = self.client.delete(url)
        assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED
        assert response.data == {"detail": 'Method "DELETE" not allowed.'}
Пример #43
0
 def get_url(cls, customer=None, action=None):
     if customer is None:
         customer = CustomerFactory()
     url = 'http://testserver' + reverse('customer-detail', kwargs={'uuid': customer.uuid})
     return url if action is None else url + action + '/'
Пример #44
0
 def get_list_url(cls):
     return 'http://testserver' + reverse('customer-list')
Пример #45
0
 def get_url(cls, key):
     if key is None:
         key = SshPublicKeyFactory()
     return 'http://testserver' + reverse('sshpublickey-detail', kwargs={'uuid': str(key.uuid)})
Пример #46
0
 def get_list_url(cls):
     return 'http://testserver' + reverse('sshpublickey-list')
Пример #47
0
    def get(self, request,format=None):
        return Response({
            'Queue': {'Tasks': reverse('queue-main', request=request),
                      'Tasks History': reverse('queue-user-tasks',request=request)},
                      'Data Store': {'ETAG Postgresql':{'Readers':reverse('readers-list',request=request),
                      'Animals':reverse('animals-list',request=request),
                      'Locations':reverse('locations-list',request=request),
                      'Reader Location':reverse('readerlocation-list',request=request),
                      'Tags':reverse('tags-list',request=request),
                      'Tag Owners':reverse('tagowner-list',request=request),
                      'Tag Read':reverse('tagreads-list',request=request),
                      'Tag Animal':reverse('taggedanimal-list',request=request),
                      'Animal Hit Reader':reverse('animalhitreader-list',request=request),
                      'Upload Location':reverse('uploadlocation-list',request=request),
                      },
            'Mongo':reverse('data-list',request=request)
                         },
            'Catalog': {'Data Source':reverse('catalog-list',request=request)},

            'User Profile': {'User':reverse('user-list',request=request)}

        })
Пример #48
0
 def get_password_url(self, user):
     return 'http://testserver' + reverse('user-detail', kwargs={'uuid': user.uuid}) + 'password/'
Пример #49
0
 def get_url(cls, project=None, action=None):
     if project is None:
         project = ProjectFactory()
     url = 'http://testserver' + reverse('project-detail', kwargs={'uuid': project.uuid})
     return url if action is None else url + action + '/'
Пример #50
0
 def get_list_url(cls):
     return 'http://testserver' + reverse('test-new-instances-list')
Пример #51
0
 def get_list_url(cls):
     return 'http://testserver' + reverse('test-spl-list')
Пример #52
0
 def get_url(cls, instance=None, action=None):
     if instance is None:
         instance = ServiceCertificationFactory()
     url = 'http://testserver' + reverse('service-certification-detail', kwargs={'uuid': instance.uuid})
     return url if action is None else url + action + '/'
Пример #53
0
 def get_url(cls, service=None, action=None):
     if service is None:
         service = TestServiceFactory()
     url = 'http://testserver' + reverse('test-detail', kwargs={'uuid': service.uuid})
     return url if action is None else url + action + '/'
Пример #54
0
 def get_url(cls, instance=None, action=None):
     if instance is None:
         instance = TestNewInstanceFactory()
     url = 'http://testserver' + reverse('test-new-instances-detail', kwargs={'uuid': instance.uuid})
     return url if action is None else url + action + '/'
Пример #55
0
 def get_url(cls, settings=None, action=None):
     if settings is None:
         settings = ServiceSettingsFactory()
     url = 'http://testserver' + reverse('servicesettings-detail', kwargs={'uuid': settings.uuid})
     return url if action is None else url + action + '/'
Пример #56
0
 def get_url(cls, spl=None, action=None):
     if spl is None:
         spl = TestServiceProjectLinkFactory()
     url = 'http://testserver' + reverse('test-spl-detail', kwargs={'pk': spl.pk})
     return url if action is None else url + action + '/'
Пример #57
0
 def get_list_url(cls):
     return 'http://testserver' + reverse('project_permission-list')
Пример #58
0
 def get_list_url(cls):
     return 'http://testserver' + reverse('servicesettings-list')
Пример #59
0
 def get_owner_url(self, obj):
     return reverse('loyal:customer:customer-detail',
                    args=[obj.owned_by.pk],
                    request=self.context['request'])
Пример #60
0
 def get_url(cls, permission=None, action=None):
     if permission is None:
         permission = CustomerPermissionFactory()
     url = 'http://testserver' + reverse('customer_permission-detail', kwargs={'pk': permission.pk})
     return url if action is None else url + action + '/'