我们从Python开源项目中,提取了以下46个代码示例,用于说明如何使用django.core.urlresolvers.reverse()。
def test_webfinger_responds_404_on_unknown_user(self, client): response = client.get("{url}?q=foobar%40socialhome.local".format(url=reverse("federate:webfinger"))) assert response.status_code == 404
def createconfig(request): print('Hello Config') query_string = request.META['QUERY_STRING'] new_query_string = [] for item in query_string.split('&'): if not item.startswith('individuals'): new_query_string.append(item) query_string = "&".join(new_query_string) filterstring = query_string if request.method == 'POST': form = Filter(request.POST) if form.is_valid(): #use id for unique names filterconfig = FilterConfig.objects.create(user=request.user) filterconfig.name = request.POST['name'] filterconfig.filterstring = form.cleaned_data['filterstring'] filterconfig.save() #return HttpResponseRedirect('/filter_analysis/?%s' % (filterconfig.filterstring)) return redirect(reverse('filter_analysis')+'?'+filterconfig.filterstring) else: form = Filter(initial={'filterstring': filterstring}) return render(request, 'filter_analysis/createfilter.html', {'form': form})
def sign_out(request, context): tenant = context.tenant cfg_url = '%s?signed_request=%s' % (reverse('sentry-hipchat-ac-config'), context.signed_request) if 'no' in request.POST: return HttpResponseRedirect(cfg_url) elif request.method == 'POST': if tenant.auth_user: tenant.clear() notify_tenant_removal(tenant) url = "%s?next=%s" % (reverse('sentry-logout'), cfg_url) return HttpResponseRedirect(url) return render( request, 'sentry_hipchat_ac/sign_out.html', { 'context': context, 'tenant': tenant, } )
def get_saml_settings(): base_url = '{scheme}://{domain}'.format( scheme=settings.SITES['front']['scheme'], domain=settings.SITES['front']['domain'], ) debug = settings.DEBUG saml_settings = dict(settings.SAML_AUTH) saml_settings['strict'] = settings.SAML_AUTH.get('strict', not debug) saml_settings['debug'] = settings.SAML_AUTH.get('debug', debug) del(saml_settings['mapping']) saml_settings['sp'].update({ 'entityId': base_url + reverse('taiga_contrib_saml_auth:metadata'), 'assertionConsumerService': { 'url': base_url + reverse('taiga_contrib_saml_auth:login_complete'), }, 'singleLogoutService': { 'url': base_url + reverse('taiga_contrib_saml_auth:logout_complete'), }, }) return saml_settings
def test_form_submission(self): """ Test that a (normal, non-Crispy) form submission results in an additional Sample instance. """ # First get the number Sample-instances current_samples = Sample.objects.count() sample_name = self.get_random_string(10) sample_msg = self.get_random_string(100) action_url = reverse( 'cmsplugin_form_handler:process_form', args=(self.form_plugin.pk, ) ) response = self.client.post(action_url, { 'name': sample_name, 'message': sample_msg, 'cmsplugin_form_source_url': '/en/', }, follow=True) self.assertEqual(response.status_code, 200) assert Sample.objects.count() > current_samples
def test_form_submission(self): """ Test that a Crispy form submission results in an additional Sample instance. """ # First get the number Sample-instances current_samples = Sample.objects.count() sample_name = self.get_random_string(10) sample_msg = self.get_random_string(100) action_url = reverse( 'cmsplugin_form_handler:process_form', args=(self.crispy_model_form_plugin.pk, ) ) response = self.client.post(action_url, { 'name': sample_name, 'message': sample_msg, 'cmsplugin_form_source_url': '/en/', }, follow=True) self.assertEqual(response.status_code, 200) assert Sample.objects.count() > current_samples
def test_invalid_form_submission(self): """ Test that the desired response occurs when the form is not valid. """ # First get the number Sample-instances current_samples = Sample.objects.count() sample_name = '' sample_msg = self.get_random_string(100) action_url = reverse( 'cmsplugin_form_handler:process_form', args=(self.model_form_plugin.pk, ) ) response = self.client.post(action_url, { 'name': sample_name, 'message': sample_msg, 'cmsplugin_form_source_url': '/en/', }, follow=True) self.assertEqual(response.status_code, 200) assert Sample.objects.count() == current_samples
def test_invalid_form_submission_no_session(self): """ Test that the desired response occurs when the form is not valid, when there is no session. """ # First get the number Sample-instances current_samples = Sample.objects.count() sample_name = '' sample_msg = self.get_random_string(100) action_url = reverse( 'cmsplugin_form_handler:process_form', args=(self.model_form_plugin.pk, ) ) response = self.client.post(action_url, { 'name': sample_name, 'message': sample_msg, 'cmsplugin_form_source_url': '/en/', }, follow=True) self.assertEqual(response.status_code, 200) # Ensure we didn't add any new samples assert Sample.objects.count() == current_samples
def test_non_existent_plugin_submission(self): """ Test that a submitting a form for a non-existent plugin meets defined behavior. """ sample_name = self.get_random_string(10) sample_msg = self.get_random_string(100) # Get non-existent plugin ID: bad_id = CMSPlugin.objects.aggregate(max=Max('id'))['max'] + 1 assert bad_id action_url = reverse( 'cmsplugin_form_handler:process_form', args=(bad_id + 1, ) ) with self.assertRaises(ImproperlyConfigured): self.client.post(action_url, { 'name': sample_name, 'message': sample_msg, 'cmsplugin_form_source_url': '/en/', }, follow=True)
def test_sitemap_defaults(self): page = Page.objects.create( url='/test/', ) url = reverse('sitemap') response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertEqual( parse_sitemap(response.content), [ { 'loc': 'http://testserver{0}'.format(page.url), 'lastmod': page.changed_at.strftime('%Y-%m-%d') } ] )
def test_sitemap_lastmod_per_page(self): page = Page.objects.create( url='/test/', page_processor_config={ 'sitemap': { 'lastmod': "2012-12-30", } } ) url = reverse('sitemap') response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertEqual( parse_sitemap(response.content), [ { 'loc': 'http://testserver{0}'.format(page.url), 'lastmod': "2012-12-30", } ] )
def test_sitemap_changefreq_default(self): page = Page.objects.create( url='/test/', ) url = reverse('sitemap') response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertEqual( parse_sitemap(response.content), [ { 'loc': 'http://testserver{0}'.format(page.url), 'lastmod': page.changed_at.strftime('%Y-%m-%d'), 'changefreq': "daily" } ] )
def test_sitemap_changefreq_per_page_with_default(self): page = Page.objects.create( url='/test/', page_processor_config={ 'sitemap': { 'changefreq': "monthly", } } ) url = reverse('sitemap') response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertEqual( parse_sitemap(response.content), [ { 'loc': 'http://testserver{0}'.format(page.url), 'lastmod': page.changed_at.strftime('%Y-%m-%d'), 'changefreq': "monthly" # page config has higher priority } ] )
def test_sitemap_priority_per_page(self): page = Page.objects.create( url='/test/', page_processor_config={ 'sitemap': { 'priority': 0.5, } } ) url = reverse('sitemap') response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertEqual( parse_sitemap(response.content), [ { 'loc': 'http://testserver{0}'.format(page.url), 'lastmod': page.changed_at.strftime('%Y-%m-%d'), 'priority': "0.5" } ] )
def test_sitemap_priority_default(self): page = Page.objects.create( url='/test/', ) url = reverse('sitemap') response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertEqual( parse_sitemap(response.content), [ { 'loc': 'http://testserver{0}'.format(page.url), 'lastmod': page.changed_at.strftime('%Y-%m-%d'), 'priority': "0.8" } ] )
def test_sitemap_priority_per_page_with_default(self): page = Page.objects.create( url='/test/', page_processor_config={ 'sitemap': { 'priority': 0.5, } } ) url = reverse('sitemap') response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertEqual( parse_sitemap(response.content), [ { 'loc': 'http://testserver{0}'.format(page.url), 'lastmod': page.changed_at.strftime('%Y-%m-%d'), 'priority': "0.5", # page config has higher priority } ] )
def current_page_info(context, stylesheet=True, url_namespace=None): request = context.get('request') try: if url_namespace: switch_edit_mode_url = reverse( '{0}:switch_edit_mode'.format(url_namespace) ) else: switch_edit_mode_url = reverse('switch_edit_mode') except NoReverseMatch: switch_edit_mode_url = reverse('powerpages:switch_edit_mode') return { 'show_info': bool( request and request.session.get('WEBSITE_EDIT_MODE') ), 'page': context.get('website_page'), 'stylesheet': stylesheet, 'switch_edit_mode_url': switch_edit_mode_url, }
def test_upload_no_permission(self): from filer import settings settings.FILER_ENABLE_PERMISSIONS = True image = self.create_django_image_object() self.assertEqual(Image.objects.count(), 0) folder = Folder.objects.create(name='foo') with self.login_user_context(self.user_normal): url = reverse('admin:filer-ajax_upload', kwargs={'folder_id': folder.pk}) post_data = { 'Filename': image.name, 'Filedata': image, 'jsessionid': self.client.session.session_key } response = self.client.post(url, post_data) self.assertContains(response, 'Permission Denied') settings.FILER_ENABLE_PERMISSIONS = False
def get(self, request, *args, **kwargs): """Process checkout when view triggered by GET request.""" logger = logging.getLogger('django') try: self.item = Lendable(type=self.kwargs.get('item_subtype', None), user=self.request.user) self.item.checkout() self.item.save() except Exception as e: messages.error(request, e) logger.exception('%s: %s' % (type(e).__name__, e)) return redirect(reverse('library:index')) else: messages.success( request, "'%s' is checked out to you until %s." % (self.item.name, formatting_filters.format_date(self.item.due_on)) ) return super(CheckoutView, self).get(request, *args, **kwargs)
def test_checkout_exception(self): self.c.login(username=self.user.username, password='str0ngpa$$w0rd') # Test check out lendable raises exception with patch.object(Lendable, 'checkout', side_effect=Exception('Checkout Failed!')): response = self.c.get(reverse('library:checkout', args=['lendable']), follow=True) # Confirm error message displayed message = list(response.context['messages'])[0].message self.assertEqual(message, 'Checkout Failed!') # Confirm lendable not created self.assertEqual(Lendable.all_types.count(), 0)
def test_checkout_group_exception(self): mocker = AWSMock() self.c.login(username=self.user.username, password='str0ngpa$$w0rd') # Test create IAM account group not found exception handled with patch('botocore.client.BaseClient._make_api_call', new=mocker.mock_make_api_call): with self.settings(AWS_IAM_GROUP='Admins', AWS_ACCOUNT_ID_ALIAS=None): response = self.c.get(reverse('library:checkout', args=['amazondemoaccount']), follow=True) # Confirm error message displayed message = list(response.context['messages'])[0].message self.assertEqual(message, "An error occurred (Not Found) when calling the " "AddUserToGroup operation: Group Admins not found") # Confirm lendable not created self.assertEqual(Lendable.all_types.count(), 0)
def _make_flow(request, scopes, return_url=None): """Creates a Web Server Flow""" # Generate a CSRF token to prevent malicious requests. csrf_token = hashlib.sha256(os.urandom(1024)).hexdigest() request.session[_CSRF_KEY] = csrf_token state = json.dumps({ 'csrf_token': csrf_token, 'return_url': return_url, }) flow = client.OAuth2WebServerFlow( client_id=django_util.oauth2_settings.client_id, client_secret=django_util.oauth2_settings.client_secret, scope=scopes, state=state, redirect_uri=request.build_absolute_uri( urlresolvers.reverse("google_oauth:callback"))) flow_key = _FLOW_KEY.format(csrf_token) request.session[flow_key] = pickle.dumps(flow) return flow
def login(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): code = LoginCode.objects.filter(**{ 'user__email': request.POST.get('username') })[0] code.next = reverse('webtzite_register') code.save() code.send_login_code( secure=request.is_secure(), host=request.get_host(), ) return render(request, 'registration/sent_mail.html') jpy_user = os.environ.get('JPY_USER') if jpy_user: from django.contrib.auth import authenticate code = authenticate(code=None, username=jpy_user+'@users.noreply.github.com') user = authenticate(code=code.code, username=code.user.username) auth_login(request, user) return redirect(reverse('webtzite_register')) return django_login(request, authentication_form=AuthenticationForm)
def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice." }) else: # See Avoiding race conditions using F() # https://docs.djangoproject.com/en/1.9/ref/models/expressions/#avoiding-race-conditions-using-f selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=( question.id, )))
def test_resolve_cart_for_logged_in_user(self): session = self.client.session session['user_cart'] = 'testing_session' request = self.client.get(reverse('cart:index')) request.user = self._create_testing_user() request.session = session testing_cart = self._create_testing_cart() testing_cart.session_key = request.session['user_cart'] testing_cart.user = request.user testing_cart.save() cart = get_cart(request) self.assertEqual(request.status_code, 200) self.assertEqual(cart, testing_cart)
def test_updating_cart_item(self): session = self.client.session cart = self._create_testing_cart() cart.session_key = session.session_key cart.save() cart_item = self._create_testing_cart_item(cart_instance=cart, product_instance=self.test_product) response = self.client.post(reverse('cart:update', kwargs={'pk': cart_item.pk}), data={'cart_item_quantity': '2'}, follow=True ) messages = [msg for msg in get_messages(response.wsgi_request)] updated_quantity = response.context['cart'].items.first().quantity cart_item.quantity = updated_quantity cart_item.save() self.assertEqual(response.status_code, 200) self.assertEqual(cart_item.quantity, 2) self.assertEqual(cart_item.total_price, Decimal(cart_item.quantity * cart_item.product.price)) self.assertEqual(messages[0].tags, 'success', 'Message type should return success type') self.assertEqual(messages[0].message, 'Product quantity has been updated.')
def test_adding_item_to_cart_as_logged_user(self): session = self.client.session session['user_cart'] = 'cart_session' test_user = self._create_testing_user() response = self.client.post( reverse('cart:add', kwargs={'product_id': self.test_product.id}), data={'quantity': 3}, follow=True) response.session = session response.user = test_user cart, created = Cart.objects.get_or_create( session_key=response.session['user_cart'], user=response.user) cart.save() self.assertRedirects(response, '/cart/', 302) self.assertEqual(response.context['cart'].items.count(), 1) self.assertEqual(response.context['cart'].items.first().quantity, 3)
def post(self, request, *args, **kwargs): #get list of diseases diseases_ids = request.POST.getlist('diseases') diseases = Disease.objects.filter(id__in=diseases_ids) #create list of genes gene_list = [] for disease in diseases: genes = disease.gene_names.split(',') for gene in genes: parsed_gene = gene.strip() if parsed_gene not in gene_list: gene_list.append(parsed_gene) #redirect to filter analysis page gene_list_url = '?gene_list=%s' % ("%2C".join(gene_list)) #return redirect('/filter_analysis/?gene_list=%s' % ("%2C".join(gene_list))) # return redirect(reverse('filter_analysis', args=['some_value'])) return redirect(reverse('filter_analysis')+gene_list_url) # return redirect('filter_analysis', gene_list='%s' % ("%2C".join(gene_list)))
def post(self, request, *args, **kwargs): #get list of diseases diseases_ids = request.POST.getlist('diseases') diseases = Disease.objects.filter(id__in=diseases_ids) #create list of genes gene_list = [] for disease in diseases: genes = disease.gene_names.split(',') for gene in genes: gene_list.append(gene.strip()) #redirect to filter analysis page gene_list_url = '?gene_list=%s' % ("%2C".join(gene_list)) #return redirect('/filter_analysis/?gene_list=%s' % ("%2C".join(gene_list))) # return redirect(reverse('filter_analysis', args=['some_value'])) return redirect(reverse('filter_analysis')+gene_list_url) # return redirect('filter_analysis', gene_list='%s' % ("%2C".join(gene_list)))
def oneclick(request): form = FilterAnalysisForm(request.user) if request.method == 'GET': # print request.META query_string = request.META['QUERY_STRING'] # print(query_string) if query_string != '': new_query_string = [] query_string = query_string.split('&') for item in query_string: if not (item.startswith('csrfmiddlewaretoken') or item.startswith('hash') or item.startswith('wizard')): #get here only the ones need to be cleaned Ex. 1-chr #item = "-".join(item.split('-', 2)[1:]) new_query_string.append(item) #create new query filterstring = "&".join(new_query_string) return redirect(reverse('filter_analysis')+'?'+filterstring) return render(request, 'filter_analysis/oneclick.html', {'form':form});
def create(request): print('Hello') filterstring = request.META['QUERY_STRING'] print(filterstring) if request.method == 'POST': form = Filter(request.POST) if form.is_valid(): #use id for unique names filter = FilterAnalysis.objects.create(user=request.user) filter.name = request.POST['name'] filter.filterstring = form.cleaned_data['filterstring'] filter.save() #return HttpResponseRedirect('/filter_analysis/?%s' % (filter.filterstring)) return redirect(reverse('filter_analysis')+'?'+filter.filterstring) else: form = Filter(initial={'filterstring': filterstring}) return render(request, 'filter_analysis/createfilter.html', {'form': form})
def oneclick(request): form = FilterAnalysisForm() if request.method == 'GET': print('Entrando no GET') # print request.META query_string = request.META['QUERY_STRING'] print(query_string) if query_string != '': print("LIMPANDO") new_query_string = [] query_string = query_string.split('&') for item in query_string: if not (item.startswith('csrfmiddlewaretoken') or item.startswith('hash') or item.startswith('wizard')): #get here only the ones need to be cleaned Ex. 1-chr #item = "-".join(item.split('-', 2)[1:]) new_query_string.append(item) #create new query filterstring = "&".join(new_query_string) # return HttpResponseRedirect('/filter_analysis/?%s' % (filterstring)) return redirect(reverse('filter_analysis')+'?'+filterstring) return render(request, 'filter_analysis/oneclick.html', {'form':form})
def wizard(request): form = FilterWizard([FilterWiZardForm1, FilterWiZardForm2, FilterWiZardForm3]) if request.method == 'GET': print('CHECK HERE') query_string = request.META['QUERY_STRING'] if query_string != '': print("LIMPANDO") new_query_string = [] query_string = query_string.split('&') for item in query_string: if not (item.startswith('csrfmiddlewaretoken') or item.startswith('hash') or item.startswith('wizard')): #get here only the ones need to be cleaned Ex. 1-chr item = "-".join(item.split('-', 2)[1:]) new_query_string.append(item) #create new query filterstring = "&".join(new_query_string) # return HttpResponseRedirect('/filter_analysis/?%s' % (filterstring)) return redirect(reverse('filter_analysis')+'?'+filterstring) return form(context=RequestContext(request), request=request)
def family_analysis_create_filter(request): print('Hello') filterstring = request.META['QUERY_STRING'] print(filterstring) if request.method == 'POST': form = FamilyFilter(request.POST) if form.is_valid(): #use id for unique names filter = FamilyFilterAnalysis.objects.create(user=request.user) filter.name = request.POST['name'] filter.filterstring = form.cleaned_data['filterstring'] filter.save() #return HttpResponseRedirect('/filter_analysis/family_analysis/?%s' % (filter.filterstring)) return redirect(reverse('family_analysis')+'?'+filter.filterstring) # return redirect('mendelmd/%s' % (reverse('family_analysis')+'?'+filter.filterstring)) else: form = FamilyFilter(initial={'filterstring': filterstring}) return render(request, 'filter_analysis/createfilter.html', {'form': form})
def _search_by_field(self, field_name, search_term): """Search by field.""" self.authenticate() url = reverse('bookdocument-list', kwargs={}) data = {} # Should contain 20 results response = self.client.get(url, data) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data['results']), self.all_count) # Should contain only 10 results filtered_response = self.client.get( url + '?search={}'.format(search_term), data ) self.assertEqual(filtered_response.status_code, status.HTTP_200_OK) self.assertEqual( len(filtered_response.data['results']), self.special_count )
def _search_by_nested_field(self, search_term): """Search by field.""" self.authenticate() url = reverse('citydocument-list', kwargs={}) data = {} # Should contain 20 results response = self.client.get(url, data) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data['results']), self.all_cities_count) # Should contain only 10 results filtered_response = self.client.get( url + '?search={}'.format(search_term), data ) self.assertEqual(filtered_response.status_code, status.HTTP_200_OK) self.assertEqual( len(filtered_response.data['results']), self.switz_cities_count )
def setUpClass(cls): """Set up.""" cls.geo_origin = factories.PublisherFactory.create( **{ 'latitude': 48.8549, 'longitude': 2.3000, } ) cls.geo_in_count = 5 cls.unit = 'km' cls.algo = 'plane' cls.geo_in = [] for index in range(cls.geo_in_count): __publisher = factories.PublisherFactory.create( **{ 'latitude': 48.8570 + index, 'longitude': 2.3005, } ) cls.geo_in.append(__publisher) cls.base_publisher_url = reverse('publisherdocument-list', kwargs={}) call_command('search_index', '--rebuild', '-f')
def test_host_meta_responds(self, client): response = client.get(reverse("federate:host-meta")) assert response.status_code == 200
def test_hcard_responds_on_404_on_unknown_user(self, client): response = client.get(reverse("federate:hcard", kwargs={"guid": "fehwuyfehiufhewiuhfiuhuiewfew"})) assert response.status_code == 404 with patch("socialhome.federate.views.get_object_or_404") as mock_get: # Test also ValueError raising ending up as 404 Profile.objects.filter(user__username="foobar").update(rsa_public_key="fooobar") mock_get.side_effect = ValueError() response = client.get(reverse("federate:hcard", kwargs={"guid": "foobar"})) assert response.status_code == 404
def test_hcard_responds_on_200_on_known_user(self, client): user = UserFactory(username="foobar") Profile.objects.filter(user__username="foobar").update(rsa_public_key="fooobar") response = client.get(reverse("federate:hcard", kwargs={"guid": user.profile.guid})) assert response.status_code == 200
def test_nodeinfo_responds(self, client): response = client.get(reverse("federate:nodeinfo")) assert response.status_code == 200
def test_social_relay_responds(self, client): response = client.get(reverse("federate:social-relay")) assert response.status_code == 200
def test_receive_public_responds(self, client): response = client.post(reverse("federate:receive-public"), {"xml": "foo"}) assert response.status_code == 202
def test_receive_user_responds_for_xml_payload(self, client): response = client.post(reverse("federate:receive-user", kwargs={"guid": "1234"}), {"xml": "foo"}) assert response.status_code == 202