我们从Python开源项目中,提取了以下30个代码示例,用于说明如何使用rest_framework.reverse.reverse()。
def get_url(self, obj, view_name, request, format): """ Given an object, return the URL that hyperlinks to the object. May raise a `NoReverseMatch` if the `view_name` and `lookup_field` attributes are not configured to correctly match the URL conf. """ # Unsaved objects will not yet have a valid URL. if hasattr(obj, 'pk') and obj.pk in (None, ''): return None # override lookup_url_kwarg router = SwaggerRouter() self.lookup_url_kwarg = router.get_view_key(view_name) or self.lookup_field lookup_value = getattr(obj, self.lookup_field) kwargs = {self.lookup_url_kwarg: lookup_value} return self.reverse(view_name, kwargs=kwargs, request=request, format=format)
def api_root(request, format=None): """ Defines the clickable links displayed on the server endpoint. All the reachable endpoints don't appear here """ return Response({ 'associations': reverse('association-list', request=request, format=format), 'sales': reverse('sale-list', request=request, format=format), 'items': reverse('item-list', request=request, format=format), 'itemSpecifications': reverse('itemSpecification-list', request=request, format=format), 'woollyusertypes': reverse('usertype-list', request=request, format=format), 'orders': reverse('order-list', request=request, format=format), 'orderlines': reverse('orderline-list', request=request, format=format), 'paymentmethods': reverse('paymentmethod-list', request=request, format=format), 'associationmembers': reverse('associationmember-list', request=request, format=format), })
def test_get_repos_when_multiple_repos_saved(self): """ Ensure get repos returns multiple repos if there is more than one saved """ repos = [ create_repo(title="Repo 1"), create_repo(title="Repo 2"), create_repo(title="Repo 3"), ] url = reverse('repos') response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(repos), len(response.data)) for app_response in response.data: RepoAssertorNested.assertAllFields(self, app_response)
def test_get_apps_when_multiple_app_saved(self): """ Ensure get apps returns multiple apps if there is more than one saved """ apps = [ create_app(title="App 1"), create_app(title="App 2"), create_app(title="App 3") ] url = reverse('apps') response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(apps), len(response.data)) for app_response in response.data: AppAssertorNested.assertAllFields(self, app_response)
def test_get_article_when_multiple_articles_saved(self): """ Ensure get articles returns multiple articles if there are more than one saved """ articles = [ create_article(title="Article 1"), create_article(title="Article 2"), create_article(title="Article 3") ] url = reverse('articles') response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(articles), len(response.data)) for article_response in response.data: ArticleAssertorNested.assertAllFields(self, article_response)
def unlock(request, email): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = UnlockForm(request.POST) # check whether it's valid: if form.is_valid(): try: user = User.objects.get(email=email) user.unlock() if not user.dyn: context = {'token': user.get_token()} send_token_email(context, user) except User.DoesNotExist: pass # fail silently, otherwise people can find out if email addresses are registered with us return HttpResponseRedirect(reverse('unlock/done')) # if a GET (or any other method) we'll create a blank form else: form = UnlockForm() return render(request, 'unlock.html', {'form': form})
def get(self, request, *args, **kwargs): # Return a plain {"name": "hyperlink"} response. ret = OrderedDict() namespace = request.resolver_match.namespace for key, url_name in self.api_root_dict.items(): if namespace: url_name = namespace + ':' + url_name try: ret[key] = reverse( url_name, args=args, kwargs=kwargs, request=request, format=kwargs.get('format', None) ) except NoReverseMatch: # Don't bail out if eg. no list routes exist, only detail routes. continue return Response(ret)
def test_can_join_if_invited(self): """ Test it's possible to join organization if invited """ self.test_can_invite_user() self.assertTrue(self.user2 not in self.organization.members.all()) mail.outbox = [] self.assertTrue(len(mail.outbox) == 0) client = APIClient() client.force_authenticate(self.user2) response = client.post(reverse("organization-join", ["test-organization"]), {}, format="json") self.assertTrue(response.status_code == 200) self.assertTrue(response.data["detail"] == "Joined organization.") self.assertTrue(self.user2 in self.organization.members.all()) subjects = [x.subject for x in mail.outbox] if is_email_enabled("default", "userJoined-toUser"): # pragma: no cover self.assertTrue(get_email_subject("default", "userJoined-toUser", "You have joined an organization")) if is_email_enabled("default", "userJoined-toOwner"): # pragma: no cover self.assertTrue(get_email_subject("default", "userJoined-toOwner", "An user has joined an organization you own"))
def test_creating_project_creates_objects_on_correct_channel(self): """ Assert creating a project creates the object on the correct channel """ client = APIClient() client.login(email=self.email, password=self.password, channel="test-channel") # Create data = copy.copy(base_project) response = client.post(reverse("project-list"), data, format="json", HTTP_X_OVP_CHANNEL="test-channel") self.assertTrue(response.status_code == 201) self.assertTrue(Project.objects.last().channel.slug == "test-channel") self.assertTrue(Work.objects.last().channel.slug == "test-channel") # Modify updated_project = {"disponibility": {"type": "job", "job": {"dates": [{"name": "update", "start_date": "2013-01-29T12:34:56.123Z", "end_date": "2013-01-29T13:34:56.123Z"}, {"name": "test1", "start_date": "2013-02-01T12:34:56.123Z", "end_date": "2013-02-01T13:34:56.123Z"}]}}} response = client.patch(reverse("project-detail", ["test-project"]), updated_project, format="json", HTTP_X_OVP_CHANNEL="test-channel") self.assertTrue(Job.objects.last().channel.slug == "test-channel") self.assertTrue(JobDate.objects.last().channel.slug == "test-channel")
def test_empty_job_or_work(self): """Test empty job or work returns error""" self.data["disponibility"] = {"type": "job"} response = self.client.post(reverse("project-list"), self.data, format="json") self.assertTrue(response.data["disponibility"]["job"] == ["This field is required if type=\"job\"."]) self.assertTrue(response.status_code == 400) self.data["disponibility"] = {"type": "work"} response = self.client.post(reverse("project-list"), self.data, format="json") self.assertTrue(response.data["disponibility"]["work"] == ["This field is required if type=\"work\"."]) self.assertTrue(response.status_code == 400) # def test_work_description_required(self): # """Test work description is required""" # self.data["disponibility"] = {"type": "work", "work": {}} # response = self.client.post(reverse("project-list"), self.data, format="json") # self.assertTrue(response.data["disponibility"]["work"]["description"] == ["This field is required."]) # self.assertTrue(response.status_code == 400)
def _test_can_update(self): data = { 'profile': { 'full_name': 'New name', 'about': 'New about', 'causes': [{'id': 3}, {'id': 4}], 'skills': [{'id': 3}, {'id': 4}], 'gender': 'female' } } response = self.client.patch(reverse('user-current-user'), data, format="json") self.assertTrue(response.data['profile']['full_name'] == data['profile']['full_name']) self.assertTrue(response.data['profile']['about'] == data['profile']['about']) self.assertTrue(response.data['profile']['gender'] == 'female') self.assertTrue(response.data['profile']['skills'][0]['id'] == 3) self.assertTrue(response.data['profile']['skills'][1]['id'] == 4) self.assertTrue(response.data['profile']['causes'][0]['id'] == 3) self.assertTrue(response.data['profile']['causes'][1]['id'] == 4)
def test_address_filter(self): """ Test searching with address filter returns only results filtered by address """ # Filter by city response = self.client.get(reverse("search-projects-list") + '?address={"address_components":[{"types":["locality", "administrative_area_level_2"], "long_name":"São Paulo"}]}', format="json") self.assertEqual(len(response.data["results"]), 1) # Filter by state response = self.client.get(reverse("search-projects-list") + '?address={"address_components":[{"types":["administrative_area_level_1"], "long_name":"State of São Paulo"}]}', format="json") self.assertEqual(len(response.data["results"]), 2) # Filter by country response = self.client.get(reverse("search-projects-list") + '?address={"address_components":[{"types":["country"], "long_name":"United States"}]}', format="json") self.assertEqual(len(response.data["results"]), 1) # Filter remote jobs response = self.client.get(reverse("search-projects-list") + '?address={"address_components":[]}', format="json") self.assertEqual(len(response.data["results"]), 2)
def test_causes_filter(self): """ Test searching with causes filter returns only results filtered by cause """ cause_id1 = Cause.objects.all().order_by('pk')[0].pk cause_id2 = Cause.objects.all().order_by('pk')[1].pk response = self.client.get(reverse("search-projects-list") + "?cause=" + str(cause_id1), format="json") self.assertEqual(len(response.data["results"]), 1) self.assertEqual(str(response.data["results"][0]["name"]), "test project") response = self.client.get(reverse("search-projects-list") + "?cause=" + str(cause_id2), format="json") self.assertEqual(len(response.data["results"]), 1) self.assertEqual(str(response.data["results"][0]["name"]), "test project2") response = self.client.get(reverse("search-projects-list") + "?cause={},{}".format(cause_id1, cause_id2), format="json") self.assertEqual(len(response.data["results"]), 2)
def test_categories_filter(self): """ Test searching with categories filter returns only results filtered by category """ category_id1 = Category.objects.all().order_by('pk')[0].pk category_id2 = Category.objects.all().order_by('pk')[1].pk response = self.client.get(reverse("search-projects-list") + "?category=" + str(category_id1), format="json") self.assertEqual(len(response.data["results"]), 1) self.assertEqual(str(response.data["results"][0]["name"]), "test project") response = self.client.get(reverse("search-projects-list") + "?category=" + str(category_id2), format="json") self.assertEqual(len(response.data["results"]), 1) self.assertEqual(str(response.data["results"][0]["name"]), "test project2") response = self.client.get(reverse("search-projects-list") + "?category={},{}".format(category_id1, category_id2), format="json") self.assertEqual(len(response.data["results"]), 2)
def test_skills_filter(self): """ Test searching with skill filter returns only results filtered by skill """ skill_id1 = Skill.objects.all().order_by('pk')[0].pk skill_id2 = Skill.objects.all().order_by('pk')[1].pk response = self.client.get(reverse("search-projects-list") + "?skill=" + str(skill_id1), format="json") self.assertEqual(len(response.data["results"]), 1) self.assertEqual(str(response.data["results"][0]["name"]), "test project") response = self.client.get(reverse("search-projects-list") + "?skill=" + str(skill_id2), format="json") self.assertEqual(len(response.data["results"]), 1) self.assertEqual(str(response.data["results"][0]["name"]), "test project3") response = self.client.get(reverse("search-projects-list") + "?skill={},{}".format(skill_id1, skill_id2), format="json") self.assertEqual(len(response.data["results"]), 2)
def test_name_filter(self): """ Test searching with name filter returns organizations filtered by name(ngram) """ response = self.client.get(reverse("search-users-list") + "?name=user", format="json") self.assertEqual(len(response.data["results"]), 3) response = self.client.get(reverse("search-users-list") + "?name=one", format="json") self.assertEqual(len(response.data["results"]), 1) self.assertEqual(response.data["results"][0]["name"], "user one") response = self.client.get(reverse("search-users-list") + "?name=two", format="json") self.assertEqual(len(response.data["results"]), 1) self.assertEqual(response.data["results"][0]["name"], "user two") response = self.client.get(reverse("search-users-list") + "?name=three", format="json") self.assertEqual(len(response.data["results"]), 1) self.assertEqual(response.data["results"][0]["name"], "user three")
def test_available_country_cities(self): client = APIClient() response = client.get(reverse("available-country-cities", ["Brazil"]), format="json") self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data["projects"]), 1) self.assertEqual(len(response.data["organizations"]), 1) self.assertEqual(len(response.data["common"]), 1) self.assertIn("Campinas", response.data["projects"]) self.assertIn("Santo André", response.data["organizations"]) self.assertIn("São Paulo", response.data["common"]) response = client.get(reverse("available-country-cities", ["United States"]), format="json") self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data["projects"]), 0) self.assertEqual(len(response.data["organizations"]), 0) self.assertEqual(len(response.data["common"]), 1) self.assertIn("New York", response.data["common"])
def get_root_apiview(self): handlers = sorted(self.handlers.items(), key = lambda x : x[1]['display']) def list_handlers(self, request, *args, **kwargs): resp = OrderedDict() # get all names for regex, data in handlers: name = data['name'] alias = data['display'] if alias != APIROOT_NAME: try: resp[alias] = reverse(name, args = args, kwargs = kwargs, request = request, format = kwargs.get('format', None)) except NoReverseMatch: # here we've got a path with defined params which are not specified in request continue return Response(resp, status = status.HTTP_200_OK) # get available info from schema info = self.schema.get('info', None) name = info.get('title', APIROOT_NAME).strip(' ').replace(' ', '_') vers = info.get('version', 'unknown') desc = info.get('description', 'Enumerates all available endpoints for current schema') # construct class apiroot = LazyClass(name, SwaggerViewClass) apiroot.set_attr('get', list_handlers) apiroot.set_attr('__doc__', 'v.' + vers + '\n\n' + desc) return apiroot().as_view() #: main schema processing function
def test_no_vote_count(self): connection = ConnectionFactory() url = reverse('connection-detail', kwargs={"pk":connection.id}) response = self.client.get(url).json() self.assertEqual(response['vote_count'], 0)
def test_vote_count(self): connection = ConnectionFactory() url = reverse('connection-detail', kwargs={"pk":connection.id}) # Cast 5 votes VoteFactory.create_batch(size=5, connection=connection) response = self.client.get(url).json() self.assertEqual(response['vote_count'], 5)
def test_no_vote_created(self): connection = ConnectionFactory() url = reverse('add-vote', kwargs={'connection_id': connection.id}) response = self.client.get(url) self.assertEqual(response.status_code, 404)
def test_casting_vote(self): connection = ConnectionFactory() url = reverse('add-vote', kwargs={'connection_id': connection.id}) response = self.client.post(url) self.assertEqual(response.status_code, 201) self.assertEqual(connection.votes.count(), 1)
def test_deleting_vote(self): connection = ConnectionFactory() url = reverse('add-vote', kwargs={'connection_id': connection.id}) vote = VoteFactory(connection=connection) response = self.client.delete(url, REMOTE_ADDR=vote.ip) self.assertEqual(response.status_code, 200) self.assertEqual(connection.votes.count(), 0) response = self.client.delete(url, REMOTE_ADDR=vote.ip) self.assertEqual(response.status_code, 404)
def root_route(request, format=None): return Response({ 'bucketlists': reverse( 'bucketlist-list', request=request, format=format ), })
def get_records_url(self, obj): request = self.context.get('request') return reverse('record-create', request=request, kwargs={ 'zone_id': obj.pk })
def api_root(request, format=None): return Response({ 'chairmans': reverse('chairman-list', request=request, format=format), })
def test_server_error(self): response = self.client.get(reverse('server-error')) self.assertEqual(response.status_code, 500) self.assertEqual(response.data['message'], 'APIException') self.assertEqual(response.data['status_code'], 500) self.assertEqual(response.data['code'], settings.FRIENDLY_EXCEPTION_DICT.get('APIException'))
def test_handler_do_not_touch_pretty_errors(self): self.data_set['language'] = 'node.js' request = self.factory.post(reverse('snippet-list'), data=self.data_set) response = SnippetList.as_view()(request) self.assertNotIn('status_code', response.data)
def test_not_found(self): response = self.client.get(reverse('not-found')) self.assertEqual(response.status_code, 404) self.assertEqual(response.data['status_code'], 404) self.assertEqual(response.data['code'], settings.FRIENDLY_EXCEPTION_DICT.get('NotFound'))
def test_method_not_allowed(self): response = self.client.get(reverse('not-allowed')) self.assertEqual(response.status_code, 405) self.assertEqual(response.data['status_code'], 405) self.assertEqual( response.data['code'], settings.FRIENDLY_EXCEPTION_DICT.get('MethodNotAllowed') )