def entry(request, blog_title, entry_title): """ Displays a single blog entry. If the current user can edit they are presented with additional controls. """ blog_title = urlunquote(blog_title) entry_title = urlunquote(entry_title) blog = Blog.get_one(blog_title) if blog is None: raise Http404 entry = Entry.get_one(blog.key, entry_title) if entry is None: raise Http404 user = users.get_current_user() url = entry.get_absolute_url() logout_url = users.create_logout_url(url) login_url = users.create_login_url(url) edit = user in blog.editors return render(request, 'entry.html', { 'edit': edit, 'user': user, 'logout_url': logout_url, 'login_url': login_url, 'blog': blog, 'entry': entry })
def test_subscription(self): self.client.get('/newsletter/') pass response = self.client.post('/newsletter/', { 'email': '*****@*****.**', 'action': 'subscribe', }) self.assertRedirects(response, '/newsletter/') self.assertEqual(len(mail.outbox), 1) body = mail.outbox[0].body subscribe_url = urlunquote([ line for line in body.splitlines() if 'testserver' in line][0]) self.assertEqual(Subscription.objects.count(), 0) response = self.client.get(subscribe_url) self.assertEqual( Subscription.objects.filter(is_active=True).count(), 1) self.assertContains(response, 'id="id_full_name"') response = self.client.post(subscribe_url, { 'full_name': 'Hans Muster', }) self.assertRedirects(response, subscribe_url) subscription = Subscription.objects.get() self.assertTrue(subscription.is_active) self.assertEqual(subscription.email, '*****@*****.**') self.assertEqual(subscription.full_name, 'Hans Muster') self.assertContains(self.client.post('/newsletter/', { 'email': '*****@*****.**', 'action': 'subscribe', }), 'This address is already subscribed to our newsletter.') self.assertContains(self.client.post('/newsletter/', { 'email': '*****@*****.**', 'action': 'unsubscribe', }, follow=True), 'You have been unsubscribed.') self.assertEqual( Subscription.objects.filter(is_active=True).count(), 0) self.assertEqual(len(mail.outbox), 2) body = mail.outbox[1].body resubscribe_url = urlunquote([ line for line in body.splitlines() if 'testserver' in line][0]) self.assertContains( self.client.get(resubscribe_url, follow=True), 'Your subscription has been activated.') self.assertEqual( Subscription.objects.filter(is_active=True).count(), 1) self.assertContains( self.client.get(resubscribe_url, follow=True), 'Your subscription is already active.')
def test_urlquote(self): self.assertEqual(http.urlquote('Paris & Orl\xe9ans'), 'Paris%20%26%20Orl%C3%A9ans') self.assertEqual(http.urlquote('Paris & Orl\xe9ans', safe="&"), 'Paris%20&%20Orl%C3%A9ans') self.assertEqual(http.urlunquote('Paris%20%26%20Orl%C3%A9ans'), 'Paris & Orl\xe9ans') self.assertEqual(http.urlunquote('Paris%20&%20Orl%C3%A9ans'), 'Paris & Orl\xe9ans') self.assertEqual(http.urlquote_plus('Paris & Orl\xe9ans'), 'Paris+%26+Orl%C3%A9ans') self.assertEqual(http.urlquote_plus('Paris & Orl\xe9ans', safe="&"), 'Paris+&+Orl%C3%A9ans') self.assertEqual(http.urlunquote_plus('Paris+%26+Orl%C3%A9ans'), 'Paris & Orl\xe9ans') self.assertEqual(http.urlunquote_plus('Paris+&+Orl%C3%A9ans'), 'Paris & Orl\xe9ans')
def assertRedirectsNoFollow(self, response, expected_url): """Check for redirect. Asserts that the given response issued a 302 redirect without processing the view which is redirected to. """ loc = six.text_type(response._headers.get('location', None)[1]) loc = http.urlunquote(loc) expected_url = http.urlunquote(expected_url) self.assertEqual(loc, expected_url) self.assertEqual(response.status_code, 302)
def assertRedirectsNoFollow(self, response, expected_url): """Check for redirect. Asserts that the given response issued a 302 redirect without processing the view which is redirected to. """ if django.VERSION >= (1, 9): loc = six.text_type(response._headers.get('location', None)[1]) loc = http.urlunquote(loc) expected_url = http.urlunquote(expected_url) self.assertEqual(loc, expected_url) else: self.assertEqual(response._headers.get('location', None), ('Location', settings.TESTSERVER + expected_url)) self.assertEqual(response.status_code, 302)
def test_subnet_create_button_disabled_when_quota_exceeded_detail(self): network_id = self.networks.first().id quota_data = self.neutron_quota_usages.first() quota_data['subnets']['available'] = 0 api.neutron.network_get( IsA(http.HttpRequest), network_id)\ .MultipleTimes().AndReturn(self.networks.first()) api.neutron.subnet_list( IsA(http.HttpRequest), network_id=network_id)\ .AndReturn(self.subnets.list()) api.neutron.is_extension_supported( IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(False) quotas.tenant_quota_usages( IsA(http.HttpRequest)) \ .MultipleTimes().AndReturn(quota_data) self.mox.ReplayAll() url = urlunquote(reverse('horizon:project:networks:subnets_tab', args=[network_id])) res = self.client.get(url) self.assertTemplateUsed(res, 'horizon/common/_detail.html') subnets = res.context['subnets_table'].data self.assertItemsEqual(subnets, self.subnets.list()) create_action = self.getAndAssertTableAction(res, 'subnets', 'create') self.assertIn('disabled', create_action.classes, 'The create button should be disabled')
def _test_network_detail_subnets_tab_network_exception(self, mac_learning=False): network_id = self.networks.first().id ip_availability = self.ip_availability.get() api.neutron.show_network_ip_availability(IsA(http.HttpRequest), network_id).\ MultipleTimes().AndReturn(ip_availability) api.neutron.network_get(IsA(http.HttpRequest), network_id)\ .AndRaise(self.exceptions.neutron) api.neutron.subnet_list(IsA(http.HttpRequest), network_id=network_id)\ .AndReturn([self.subnets.first()]) api.neutron.is_extension_supported( IsA(http.HttpRequest), 'network-ip-availability').AndReturn(True) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(mac_learning) api.neutron.is_extension_supported( IsA(http.HttpRequest), 'network-ip-availability').AndReturn(True) self.mox.ReplayAll() url = urlunquote(reverse('horizon:admin:networks:subnets_tab', args=[network_id])) res = self.client.get(url) redir_url = INDEX_URL self.assertRedirectsNoFollow(res, redir_url)
def _test_index_paginated(self, marker, sort_dir, volumes, url, has_more, has_prev): vol_snaps = self.cinder_volume_snapshots.list() self.mock_volume_list_paged.return_value = \ [volumes, has_more, has_prev] self.mock_volume_snapshot_list.return_value = vol_snaps self.mock_server_list.return_value = [self.servers.list(), False] self.mock_tenant_list.return_value = [self.tenants.list(), False] res = self.client.get(urlunquote(url)) self.mock_server_list.assert_called_once_with( test.IsHttpRequest(), search_opts={'all_tenants': True}) self.mock_volume_list_paged.assert_called_once_with( test.IsHttpRequest(), sort_dir=sort_dir, marker=marker, paginate=True, search_opts={ 'all_tenants': True}) self.mock_volume_snapshot_list.assert_called_once_with( test.IsHttpRequest(), search_opts={'all_tenants': True}) self.mock_tenant_list.assert_called_once() self.assertTemplateUsed(res, 'horizon/common/_data_table_view.html') self.assertEqual(res.status_code, 200) return res
def maskurl(given_url, *args, **kwargs): """ Probable usage: - {% url 'main' %} -> {% maskurl 'main' %} - {% url 'list' 4 %} -> {% maskurl 'main' 4 %} - {% url 'list' 'blah' %} -> {% maskurl 'main' 'blah' %} - {% url 'list' object.id %} -> {% maskurl 'main' object.id %} - {% url 'list' obj1.id obj2.id %} -> {% maskurl 'main' obj1.id obj2.id %} - {% url 'list' obj1.name|title obj2.id|lower %} -> {% maskurl 'main' obj1.id|title obj2.id|lower %} - {{ reversed_url }} -> {% maskurl reversed_url %} After Django 1.7.0 version url built in templatetag returns quoted paths """ maskedurl = "" match = given_url.find("/") == -1 if match: reversed_url = url_reverse(given_url, args=args, kwargs=kwargs) resolved_url = urlunquote(reversed_url) maskedurl = dumps(resolved_url.lstrip('/')) else: maskedurl = dumps(given_url.lstrip('/')) if DJANGO_VERSION >= 170: maskedurl = urlquote(maskedurl) return '/%s' % maskedurl
def test_volume_types_tab(self): encryption_list = (self.cinder_volume_encryption_types.list()[0], self.cinder_volume_encryption_types.list()[1]) cinder.volume_type_list_with_qos_associations( IsA(http.HttpRequest)).\ AndReturn(self.cinder_volume_types.list()) cinder.qos_spec_list(IsA(http.HttpRequest)).\ AndReturn(self.cinder_qos_specs.list()) cinder.volume_encryption_type_list(IsA(http.HttpRequest))\ .AndReturn(encryption_list) cinder.extension_supported(IsA(http.HttpRequest), 'VolumeTypeEncryption').MultipleTimes()\ .AndReturn(True) self.mox.ReplayAll() url = reverse('horizon:admin:volumes:volume_types_tab') res = self.client.get(urlunquote(url)) self.assertEqual(res.status_code, 200) self.assertTemplateUsed( res, 'admin/volumes/volume_types/volume_types_tables.html') volume_types = res.context['volume_types_table'].data self.assertItemsEqual(volume_types, self.cinder_volume_types.list()) qos_specs = res.context['qos_specs_table'].data self.assertItemsEqual(qos_specs, self.cinder_qos_specs.list())
def test_anonymous_redirect(self): url = reverse('banktransactions:list', kwargs={ 'bankaccount_pk': self.bankaccount.pk, }) login_url = resolve_url(settings.LOGIN_URL) admin_base_url = get_script_prefix() + settings.MYMONEY['ADMIN_BASE_URL'] # Anonymous should be redirect to login url. response = self.client.get(url, follow=True) self.assertEqual(response.request['PATH_INFO'], login_url) self.assertEqual( urlunquote(response.request['QUERY_STRING']), 'next=' + url ) # Check explicit infinite loop with anonymous. response = self.client.get(login_url, follow=True) self.assertEqual(response.request['PATH_INFO'], login_url) # However, check that anonymous could access back-office response = self.client.get(admin_base_url, follow=True) self.assertEqual(response.request['PATH_INFO'], admin_base_url + '/login/') # Authentificated user are not redirected. self.client.force_login(self.owner) response = self.client.get(url, follow=True) self.assertEqual(response.request['PATH_INFO'], url) # Check explicit infinite loop after log out. logout_url = resolve_url(settings.LOGOUT_URL) response = self.client.get(logout_url, follow=True) self.assertEqual(response.request['PATH_INFO'], login_url)
def _test_subnet_create_button(self, quota_data): network_id = self.networks.first().id api.neutron.network_get( IsA(http.HttpRequest), network_id)\ .MultipleTimes().AndReturn(self.networks.first()) api.neutron.subnet_list( IsA(http.HttpRequest), network_id=network_id)\ .AndReturn(self.subnets.list()) api.neutron.is_extension_supported( IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(False) quotas.tenant_quota_usages( IsA(http.HttpRequest), targets=['subnets']) \ .MultipleTimes().AndReturn(quota_data) self.mox.ReplayAll() url = urlunquote(reverse('horizon:project:networks:subnets_tab', args=[network_id])) res = self.client.get(url) self.assertTemplateUsed(res, 'horizon/common/_detail.html') subnets = res.context['subnets_table'].data self.assertItemsEqual(subnets, self.subnets.list()) return self.getAndAssertTableAction(res, 'subnets', 'create')
def _test_index_paginated(self, marker, sort_dir, volumes, url, has_more, has_prev): vol_snaps = self.cinder_volume_snapshots.list() server = self.servers.first() cinder.volume_list_paged(IsA(http.HttpRequest), sort_dir=sort_dir, marker=marker, paginate=True, search_opts={'all_tenants': True}) \ .AndReturn([volumes, has_more, has_prev]) api.cinder.volume_snapshot_list( IsA(http.HttpRequest), search_opts=None).AndReturn(vol_snaps) api.nova.server_list(IsA(http.HttpRequest), search_opts={ 'all_tenants': True}, detailed=False) \ .AndReturn([self.servers.list(), False]) api.nova.server_get(IsA(http.HttpRequest), server.id).AndReturn(server) keystone.tenant_list(IsA(http.HttpRequest)) \ .AndReturn([self.tenants.list(), False]) self.mox.ReplayAll() res = self.client.get(urlunquote(url)) self.assertTemplateUsed(res, 'horizon/common/_data_table_view.html') self.assertEqual(res.status_code, 200) self.mox.UnsetStubs() return res
def get(self, *args, **kwargs): lang = kwargs.pop('lang') next_url = self.request.GET.get('next') if (next_url or not self.request.is_ajax()) and not is_safe_url(url=next_url, host=self.request.get_host()): next_url = self.request.META.get('HTTP_REFERER') if next_url: next_url = urlunquote(next_url) # HTTP_REFERER may be encoded. if not is_safe_url(url=next_url, host=self.request.get_host()): next_url = '/' response = HttpResponseRedirect(next_url) if next_url else HttpResponse(status=204) if lang and check_for_language(lang): if next_url: if lang == 'ru': next_trans = re.sub("/en/", "/", next_url) else: next_trans = translate_url(next_url, lang) if next_trans != next_url: response = HttpResponseRedirect(next_trans) translation.activate(lang) if hasattr(self.request, 'session'): self.request.session[translation.LANGUAGE_SESSION_KEY] = lang else: response.set_cookie( settings.LANGUAGE_COOKIE_NAME, lang, max_age=settings.LANGUAGE_COOKIE_AGE, path=settings.LANGUAGE_COOKIE_PATH, domain=settings.LANGUAGE_COOKIE_DOMAIN, ) return response
def test_ajax_subscription(self): for email in ['', 'mnwr@@ewrwer.com', '@']: response = self.client.post('/newsletter/ajax_subscribe/', { 'subscription_email': email }) self.assertContains(response, 'Invalid email') response = self.client.post('/newsletter/ajax_subscribe/', { 'subscription_email': '*****@*****.**' }) self.assertContains(response, 'You should receive a confirmation email shortly') self.assertEqual(len(mail.outbox), 1) body = mail.outbox[0].body subscribe_url = urlunquote([ line for line in body.splitlines() if 'testserver' in line][0]) self.assertEqual(Subscription.objects.count(), 0) response = self.client.get(subscribe_url) self.assertEqual( Subscription.objects.filter(is_active=True).count(), 1) response = self.client.post('/newsletter/ajax_subscribe/', { 'subscription_email': '*****@*****.**' }) self.assertContains(response, 'already subscribed')
def _test_network_detail_subnets_tab_network_exception(self, mac_learning=False): network_id = self.networks.first().id ip_availability = self.ip_availability.get() self.mock_show_network_ip_availability.return_value = ip_availability self.mock_network_get.side_effect = self.exceptions.neutron self.mock_subnet_list.return_value = [self.subnets.first()] self._stub_is_extension_supported( {'network-ip-availability': True, 'mac-learning': mac_learning}) url = urlunquote(reverse('horizon:admin:networks:subnets_tab', args=[network_id])) res = self.client.get(url) redir_url = INDEX_URL self.assertRedirectsNoFollow(res, redir_url) self.mock_show_network_ip_availability.assert_called_once_with( test.IsHttpRequest(), network_id) self.mock_network_get.assert_called_once_with(test.IsHttpRequest(), network_id) self.mock_subnet_list.assert_called_once_with(test.IsHttpRequest(), network_id=network_id) self._check_is_extension_supported( {'network-ip-availability': 2, 'mac-learning': 1})
def test_network_detail_agents_tab(self, mac_learning=False): network = self.networks.first() quota_data = self.quota_usages.first() self._stub_is_extension_supported( {'network-ip-availability': True, 'mac-learning': mac_learning, 'network_availability_zone': True, 'dhcp_agent_scheduler': True}) self.mock_list_dhcp_agent_hosting_networks.return_value = \ self.agents.list() self.mock_network_get.return_value = network self.mock_tenant_quota_usages.return_value = quota_data url = reverse('horizon:admin:networks:agents_tab', args=[network.id]) res = self.client.get(urlunquote(url)) self.assertTemplateUsed(res, 'horizon/common/_detail.html') result_agents = res.context['agents_table'].data expected_agents = self.agents.list() self.assertItemsEqual(result_agents, expected_agents) self._check_is_extension_supported( {'network-ip-availability': 1, 'mac-learning': 1, 'network_availability_zone': 1, 'dhcp_agent_scheduler': 2}) self.mock_list_dhcp_agent_hosting_networks.assert_called_once_with( test.IsHttpRequest(), network.id) self.mock_network_get.assert_called_once_with( test.IsHttpRequest(), network.id) self.mock_tenant_quota_usages.assert_called_once_with( test.IsHttpRequest(), tenant_id=network.tenant_id, targets=('subnet',))
def get(self, request, container): """Get object information. :param request: :param container: :return: """ path = request.GET.get('path') if path is not None: path = urlunquote(path) objects = api.swift.swift_get_objects( request, container, prefix=path ) # filter out the folder from the listing if we're filtering for # contents of a (pseudo) folder contents = [{ 'path': o.subdir if isinstance(o, swift.PseudoFolder) else o.name, 'name': o.name.split('/')[-1], 'bytes': o.bytes, 'is_subdir': isinstance(o, swift.PseudoFolder), 'is_object': not isinstance(o, swift.PseudoFolder), 'content_type': getattr(o, 'content_type', None) } for o in objects[0] if o.name != path] return {'items': contents}
def _test_snapshots_index_paginated(self, marker, sort_dir, snapshots, url, has_more, has_prev, with_groups=False): self.mock_is_service_enabled.return_value = True self.mock_volume_snapshot_list_paged.return_value = [snapshots, has_more, has_prev] self.mock_volume_list.return_value = self.cinder_volumes.list() self.mock_group_snapshot_list.return_value = \ self.cinder_volume_snapshots_with_groups.list() res = self.client.get(urlunquote(url)) self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, 'horizon/common/_data_table_view.html') self.assert_mock_multiple_calls_with_same_arguments( self.mock_is_service_enabled, 2, mock.call(test.IsHttpRequest(), 'volumev3')) self.mock_volume_snapshot_list_paged.assert_called_once_with( test.IsHttpRequest(), marker=marker, sort_dir=sort_dir, paginate=True) self.mock_volume_list.assert_called_once_with(test.IsHttpRequest()) if with_groups: self.mock_group_snapshot_list.assert_called_once_with( test.IsHttpRequest()) return res
def test_network_detail_new(self, mac_learning=False): network = self.networks.first() quota_data = self.quota_usages.first() api.neutron.network_get(IsA(http.HttpRequest), network.id) \ .MultipleTimes().AndReturn(self.networks.first()) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'network-ip-availability') \ .AndReturn(True) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning') \ .AndReturn(mac_learning) api.neutron.is_extension_supported( IsA(http.HttpRequest), 'network_availability_zone').AndReturn(True) api.neutron.is_extension_supported( IsA(http.HttpRequest), 'dhcp_agent_scheduler').AndReturn(True) usage.quotas.tenant_quota_usages( IsA(http.HttpRequest), tenant_id=network.tenant_id, targets=('subnet',)).MultipleTimes().AndReturn(quota_data) self.mox.ReplayAll() url = urlunquote(reverse('horizon:admin:networks:detail', args=[network.id])) res = self.client.get(url) network = res.context['network'] self.assertEqual(self.networks.first().name_or_id, network.name_or_id) self.assertEqual(self.networks.first().status_label, network.status_label) self.assertTemplateUsed(res, 'horizon/common/_detail.html')
def _test_network_detail_subnets_tab_subnet_exception(self, mac_learning=False): network = self.networks.first() quota_data = self.quota_usages.first() api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .MultipleTimes().AndReturn(self.networks.first()) api.neutron.subnet_list(IsA(http.HttpRequest), network_id=network.id).\ AndRaise(self.exceptions.neutron) api.neutron.is_extension_supported( IsA(http.HttpRequest), 'network-ip-availability').AndReturn(True) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(mac_learning) api.neutron.is_extension_supported( IsA(http.HttpRequest), 'dhcp_agent_scheduler').AndReturn(True) api.neutron.is_extension_supported( IsA(http.HttpRequest), 'network_availability_zone').AndReturn(True) api.neutron.is_extension_supported( IsA(http.HttpRequest), 'dhcp_agent_scheduler').AndReturn(True) usage.quotas.tenant_quota_usages( IsA(http.HttpRequest), tenant_id=network.tenant_id, targets=('subnet',)).MultipleTimes().AndReturn(quota_data) self.mox.ReplayAll() url = urlunquote(reverse('horizon:admin:networks:subnets_tab', args=[network.id])) res = self.client.get(url) self.assertTemplateUsed(res, 'horizon/common/_detail.html') subnets = res.context['subnets_table'].data self.assertEqual(len(subnets), 0)
def custom_get_object_from_queryset(self, queryset): lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field lookup_url = self.kwargs[lookup_url_kwarg] decoded_lookup_url = urlunquote(lookup_url) filter_kwargs = {self.lookup_field: decoded_lookup_url} return get_object_or_404(queryset, **filter_kwargs)
def do_show_facet(context, facet_name): html = "" facets = context['facets']['fields'][facet_name] selected_facets = context['selected_facets'] path = context['request'].get_full_path() for f in facets: long_facet_name = "__".join([facet_name, urlquote(f[0])]) if urlunquote(long_facet_name) in selected_facets: html += "<dd><a href='%s'><input onclick='window.location=\"%s\"; return true;'type='checkbox' checked='checked'/> %s</a> (%s)</dd>" % (path.replace( "&selected_facets=" + long_facet_name, "").replace( "?selected_facets=" + long_facet_name, "?"), path.replace( "&selected_facets=" + long_facet_name, "").replace( "?selected_facets=" + long_facet_name, "?"), smart_text( f[0]), f[1]) else: if path.endswith('/'): html += "<dd><a href='%s?selected_facets=%s'><input onclick='window.location=\"%s?selected_facets=%s\"; return true;'type='checkbox' />%s</a> (%s)</dd>" % ( path, long_facet_name, path, long_facet_name, smart_text(f[0]), f[1]) else: html += "<dd><a href='%s&selected_facets=%s'><input onclick='window.location=\"%s&selected_facets=%s\"; return true;'type='checkbox' /> %s</a> (%s)</dd>" % ( path, long_facet_name, path, long_facet_name, smart_text(f[0]), f[1]) return html
def test_network_detail_new(self, mac_learning=False): network = self.networks.first() quota_data = self.quota_usages.first() self.mock_network_get.return_value = network self.mock_tenant_quota_usages.return_value = quota_data self._stub_is_extension_supported( {'network-ip-availability': True, 'network_availability_zone': True, 'mac-learning': mac_learning, 'dhcp_agent_scheduler': True}) url = urlunquote(reverse('horizon:admin:networks:detail', args=[network.id])) res = self.client.get(url) network = res.context['network'] self.assertEqual(self.networks.first().name_or_id, network.name_or_id) self.assertEqual(self.networks.first().status_label, network.status_label) self.assertTemplateUsed(res, 'horizon/common/_detail.html') self.assert_mock_multiple_calls_with_same_arguments( self.mock_network_get, 2, mock.call(test.IsHttpRequest(), network.id)) self.mock_tenant_quota_usages.assert_called_once_with( test.IsHttpRequest(), tenant_id=network.tenant_id, targets=('subnet',)) self._check_is_extension_supported( {'network-ip-availability': 1, 'network_availability_zone': 1, 'mac-learning': 1, 'dhcp_agent_scheduler': 1})
def _test_index_paginated(self, marker, sort_dir, volumes, url, has_more, has_prev): backup_supported = True vol_snaps = self.cinder_volume_snapshots.list() api.cinder.volume_backup_supported(IsA(http.HttpRequest)).\ MultipleTimes().AndReturn(backup_supported) api.cinder.volume_list_paged(IsA(http.HttpRequest), marker=marker, sort_dir=sort_dir, search_opts=None, paginate=True).\ AndReturn([volumes, has_more, has_prev]) api.cinder.volume_snapshot_list( IsA(http.HttpRequest), search_opts=None).AndReturn(vol_snaps) api.nova.server_list(IsA(http.HttpRequest), search_opts=None).\ AndReturn([self.servers.list(), False]) api.cinder.tenant_absolute_limits(IsA(http.HttpRequest)).MultipleTimes().\ AndReturn(self.cinder_limits['absolute']) self.mox.ReplayAll() res = self.client.get(urlunquote(url)) self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, 'virtual/volumes/index.html') self.mox.UnsetStubs() return res
def _test_subnets_tab_subnet_exception(self, mac_learning=False): network_id = self.networks.first().id quota_data = self.neutron_quota_usages.first() quota_data['networks']['available'] = 5 quota_data['subnets']['available'] = 5 api.neutron.network_get(IsA(http.HttpRequest), network_id).\ MultipleTimes().AndReturn(self.networks.first()) api.neutron.subnet_list(IsA(http.HttpRequest), network_id=network_id).\ AndRaise(self.exceptions.neutron) # Called from SubnetTable api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(mac_learning) quotas.tenant_quota_usages( IsA(http.HttpRequest), targets=['subnets']) \ .MultipleTimes().AndReturn(quota_data) self.mox.ReplayAll() url = urlunquote(reverse('horizon:project:networks:subnets_tab', args=[network_id])) res = self.client.get(url) self.assertTemplateUsed(res, 'horizon/common/_detail.html') subnets = res.context['subnets_table'].data self.assertEqual(len(subnets), 0)
def test_network_detail_agents_tab(self, mac_learning=False): network_id = self.networks.first().id api.neutron.is_extension_supported(IsA(http.HttpRequest), 'network-ip-availability') \ .AndReturn(True) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(mac_learning) api.neutron.list_dhcp_agent_hosting_networks(IsA(http.HttpRequest), network_id)\ .AndReturn(self.agents.list()) api.neutron.network_get(IsA(http.HttpRequest), network_id)\ .AndReturn(self.networks.first()) api.neutron.is_extension_supported( IsA(http.HttpRequest), 'dhcp_agent_scheduler').AndReturn(True) api.neutron.is_extension_supported( IsA(http.HttpRequest), 'dhcp_agent_scheduler').AndReturn(True) self.mox.ReplayAll() url = reverse('horizon:admin:networks:agents_tab', args=[network_id]) res = self.client.get(urlunquote(url)) self.assertTemplateUsed(res, 'horizon/common/_detail.html') result_agents = res.context['agents_table'].data expected_agents = self.agents.list() self.assertItemsEqual(result_agents, expected_agents)
def _test_network_detail_ip_availability_exception(self, mac_learning=False): network_id = self.networks.first().id api.neutron.is_extension_supported( IsA(http.HttpRequest), 'network-ip-availability').AndReturn(True) api.neutron.show_network_ip_availability(IsA(http.HttpRequest), network_id).\ MultipleTimes().AndRaise(self.exceptions.neutron) api.neutron.network_get(IsA(http.HttpRequest), network_id).\ AndReturn(self.networks.first()) api.neutron.subnet_list(IsA(http.HttpRequest), network_id=network_id).\ AndReturn([self.subnets.first()]) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning') \ .AndReturn(mac_learning) api.neutron.is_extension_supported( IsA(http.HttpRequest), 'network-ip-availability').AndReturn(True) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'dhcp_agent_scheduler')\ .MultipleTimes().AndReturn(True) self.mox.ReplayAll() from django.utils.http import urlunquote url = urlunquote(reverse('horizon:admin:networks:subnets_tab', args=[network_id])) res = self.client.get(url) self.assertTemplateUsed(res, 'horizon/common/_detail.html') subnets = res.context['subnets_table'].data self.assertItemsEqual(subnets, [self.subnets.first()])
def decode_uri(self, uri): decoded = urlunquote(uri) # If uri got decoded then recursive try more times until nothing more can be decoded if decoded != uri: decoded = self.decode_uri(decoded) return decoded
def get_referer_url(request): url = request.META.get('HTTP_REFERER') if url: url = urlunquote(url) if not is_safe_url(url = url, host = request.get_host()): url = '/' return urlparse(url).path
def generate_solr_params(params, assay_uuids, facets_from_config=False, exclude_facets=[]): """ Either returns a solr url parameter string, or None if assay_uuids is empty. """ is_annotation = params.get('is_annotation', 'false') facet_count = params.get('include_facet_count', 'true') start = params.get('offset', '0') # row number suggested by solr docs, since there's no unlimited option row = params.get('limit', str(constants.REFINERY_SOLR_DOC_LIMIT)) field_limit = params.get('attributes') facet_field = params.get('facets') facet_pivot = params.get('pivots') sort = params.get('sort') facet_filter = params.get('filter_attribute') fixed_solr_params = \ '&'.join(['fq=is_annotation:%s' % is_annotation, 'start=%s' % start, 'rows=%s' % row, 'q=django_ct:data_set_manager.node&wt=json', 'facet=%s' % facet_count, 'facet.limit=-1' ]) if len(assay_uuids) == 0: return None solr_params = 'fq=assay_uuid:({})'.format(' OR '.join(assay_uuids)) fq = params.get('fq') if fq is not None: solr_params += '&fq=' + fq if facets_from_config: # Twice as many facets as necessary, but easier than the alternative. facet_template = '{0}_Characteristics{1},{0}_Factor_Value{1}' facet_field = ','.join([ facet_template.format(s, NodeIndex.GENERIC_SUFFIX) for s in settings.USER_FILES_FACETS.split(",") ]) solr_params += '&fl=*{},name,*_uuid,type,django_id,{}'.format( NodeIndex.GENERIC_SUFFIX, NodeIndex.DOWNLOAD_URL) if facet_field: facet_field = facet_field.split(',') facet_field = insert_facet_field_filter(facet_filter, facet_field) split_facet_fields = generate_facet_fields_query(facet_field) solr_params = ''.join([solr_params, split_facet_fields]) else: # Missing facet_fields, it is generated from Attribute Order Model. attributes_str = AttributeOrder.objects.filter( assay__uuid__in=assay_uuids # TODO: Confirm this syntax ) attributes = AttributeOrderSerializer(attributes_str, many=True) culled_attributes = cull_attributes_from_list(attributes.data, exclude_facets) facet_field_obj = generate_filtered_facet_fields(culled_attributes) facet_field = facet_field_obj.get('facet_field') facet_field = insert_facet_field_filter(facet_filter, facet_field) field_limit = ','.join(facet_field_obj.get('field_limit')) facet_fields_query = generate_facet_fields_query(facet_field) solr_params = ''.join([solr_params, facet_fields_query]) if field_limit: solr_params = ''.join([solr_params, '&fl=', field_limit]) if facet_pivot: solr_params = ''.join([solr_params, '&facet.pivot=', facet_pivot]) if sort: solr_params = ''.join([solr_params, '&sort=', sort]) if facet_filter: # handle default formatting in get request, query_params if isinstance(facet_filter, unicode): facet_filter = urlunquote(facet_filter) facet_filter = json.loads(facet_filter) facet_filter_str = create_facet_filter_query(facet_filter) solr_params = ''.join([solr_params, facet_filter_str]) url = '&'.join([solr_params, fixed_solr_params]) encoded_solr_params = urlquote(url, safe='\\=&! ') return encoded_solr_params
def search(request): timeTaken = time() if request.method != 'POST': if len(searched_query['fieldName']) == 0: fields = default_fields else: fields = sorted(searched_query['results'].keys(), key=lambda x: searched_query['results'][x], reverse=True)[:5] fields = [i.split("-") for i in fields] context = { 'fields': fields, } return render(request, 'searchFields.html', context) num_visits = request.session.get('num_visits', 0) request.session['num_visits'] = num_visits + 1 available_info = [i for i in all_fields if request.POST[i] is not ''] if len(available_info) != 0: query = ' '.join([str(request.POST[i]) for i in available_info]) result = repository.search_books(query) #Hard code raw inputs expecting all queries selected image_url1 = "/static/footer/network.png" image_url2 = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1572343490091&di=97c216a924ed1603a5723045557f3e37&imgtype=0&src=http%3A%2F%2Fimg.pconline.com.cn%2Fimages%2Fupload%2Fupc%2Ftx%2Fsoftbbs%2F1011%2F06%2Fc0%2F5768221_1289012169875_1024x1024.png" fieldName = urlunquote(request.POST['fieldName']) subfieldName = urlunquote(request.POST['subfieldName']) end_time = time() timeTaken = int(end_time - timeTaken) if type(result) == str: messages.error(request, 'Error: No fields matched') if len(searched_query['fieldName']) == 0: fields = default_researchers else: fields = sorted(searched_query['results'].keys(), key=lambda x: searched_query['results'][x], reverse=True)[:5] fields = [i.split("-") for i in fields] context = { 'fields': fields, } return render(request, 'searchFields.html', context) for i in available_info: searched_query[i].append(str(request.POST[i])) for j in result: if j['field'] in searched_query['results']: searched_query['results'][j['field'] + "-" + j['subfield'] + '-' + j['code']] += j['score'] else: searched_query['results'][j['field'] + "-" + j['subfield'] + '-' + j['code']] = j['score'] print(searched_query) temp_results = result context = { 'imageurl1': image_url1, 'imageurl2': image_url2, 'fieldName': fieldName, 'subfieldName': subfieldName, 'timeTaken': timeTaken, 'ranking': temp_results, 'num_visits': num_visits, } return render(request, 'resultsFields.html', context) else: messages.error(request, 'Error: no queries') if len(searched_query['fieldName']) == 0: fields = default_researchers else: fields = sorted(searched_query['results'].keys(), key=lambda x: searched_query['results'][x], reverse=True)[:5] fields = [i.split("-") for i in fields] context = { 'fields': fields, } return render(request, 'searchFields.html', context)
def post(self, request, *args, **kwargs): if getattr(settings, 'UNIT_TESTING', False): return confirm_checkout(request, signature=request.session['signature'], *args, **kwargs) service = get_service_instance() paypal = json.loads(PaymentMean.objects.get(slug='paypal').credentials) order_id = request.POST['order_id'] order = Order.objects.get(pk=order_id) line_items = {} for i in range(len(order.album_list)): album = order.album_list[i] line_items.update({ "L_PAYMENTREQUEST_0_NAME%d" % i: album.title, "L_PAYMENTREQUEST_0_DESC%d" % i: album.title, "L_PAYMENTREQUEST_0_AMT%d" % i: do_currency(album.cost, order.currency.code), "L_PAYMENTREQUEST_0_QTY%d" % i: 1, "L_PAYMENTREQUEST_0_TAXAMT%d" % i: 0, "L_PAYMENTREQUEST_0_NUMBER%d" % i: i + 1, "L_PAYMENTREQUEST_0_ITEMURL%d" % i: service.url + reverse('mediashop:music_item_detail', args=( album.artist.slug, album.slug, )), "L_PAYMENTREQUEST_0_ITEMCATEGORY%d" % i: 'Digital' }) for i in range(len(order.song_list)): song = order.song_list[i] line_items.update({ "L_PAYMENTREQUEST_0_NAME%d" % i: song.title, "L_PAYMENTREQUEST_0_DESC%d" % i: song.title, "L_PAYMENTREQUEST_0_AMT%d" % i: do_currency(song.cost, order.currency.code), "L_PAYMENTREQUEST_0_QTY%d" % i: 1, "L_PAYMENTREQUEST_0_TAXAMT%d" % i: 0, "L_PAYMENTREQUEST_0_NUMBER%d" % i: i + 1, "L_PAYMENTREQUEST_0_ITEMURL%d" % i: service.url + reverse('mediashop:music_item_detail', args=( song.artist.slug, song.slug, )), "L_PAYMENTREQUEST_0_ITEMCATEGORY%d" % i: 'Digital' }) ec_data = { "USER": paypal['username'], "PWD": paypal['password'], "SIGNATURE": paypal['signature'], "METHOD": "DoExpressCheckoutPayment", "VERSION": 124.0, "TOKEN": request.session['token'], "PAYERID": request.session['payer_id'], "PAYMENTREQUEST_0_PAYMENTACTION": "Sale", "PAYMENTREQUEST_0_AMT": do_currency(order.total_cost, order.currency.code), "PAYMENTREQUEST_0_ITEMAMT": do_currency(order.total_cost, order.currency.code), "PAYMENTREQUEST_0_SHIPPINGAMT": 0, "PAYMENTREQUEST_0_TAXAMT": 0, "PAYMENTREQUEST_0_CURRENCYCODE": order.currency.code, "PAYMENTREQUEST_0_DESC": "Purchase on " + service.project_name } ec_data.update(line_items) if getattr(settings, 'DEBUG', False): response = requests.post(EC_ENDPOINT, data=ec_data) result = parse_paypal_response(response.content.decode('utf-8')) ACK = result['ACK'] if ACK == 'Success' or ACK == 'SuccessWithWarning': return confirm_checkout(request, signature=request.session['signature'], *args, **kwargs) else: try: Order.objects.get(pk=request.POST['order_id']).delete() except Order.DoesNotExist: pass context = self.get_context_data(**kwargs) if getattr(settings, 'DEBUG', False): context['paypal_error'] = urlunquote( response.content.decode('utf-8')) else: context['paypal_error'] = urlunquote( result['L_LONGMESSAGE0']) messages.error( request, 'API Error: Terminating PayPal transaction failed.') return HttpResponseRedirect(reverse('mediashop:cart')) else: try: response = requests.post(EC_ENDPOINT, data=ec_data) result = parse_paypal_response( response.content.decode('utf-8')) ACK = result['ACK'] if ACK == 'Success' or ACK == 'SuccessWithWarning': return confirm_checkout( request, signature=request.session['signature'], *args, **kwargs) else: try: Order.objects.get(pk=request.POST['order_id']).delete() except Order.DoesNotExist: pass context = self.get_context_data(**kwargs) if getattr(settings, 'DEBUG', False): context['paypal_error'] = urlunquote( response.content.decode('utf-8')) else: context['paypal_error'] = urlunquote( result['L_LONGMESSAGE0']) messages.error( request, 'API Error: Terminating PayPal transaction failed.') return HttpResponseRedirect(reverse('mediashop:cart')) except Exception as e: logger.error("%s - PayPal error. Order ID: %s" % (service.project_name, order.id), exc_info=True) messages.error( request, 'Could not terminate transaction due to server error. Contact administrator.' ) return HttpResponseRedirect(reverse('mediashop:cart'))
def wx_auth(request): code = request.GET.get("code", None) if code is None: return HttpResponse('No Code Provided.') wx_login = WeixinLogin(conf.APP_ID, conf.APP_SECRET) data = wx_login.access_token(code) openid = data.openid scope = data.scope token = data.access_token # 网页授权access_token和公众号的access_token不一样 # 关于网页授权access_token和普通access_token的区别 # 1、微信网页授权是通过OAuth2.0机制实现的,在用户授权给公众号后,公众号可以获取到一个网页授权特有的接口调用凭证(网页授权access_token),通过网页授权access_token可以进行授权后接口调用,如获取用户基本信息; # 2、其他微信接口,需要通过基础支持中的“获取access_token”接口来获取到的普通access_token调用。 wx_user, created = WxUser.objects.get_or_create(openid=openid) if created or wx_user.need_update(): # continue to get userinfo userinfo = wx_login.user_info(token, openid) wx_user = WxUser.objects.filter(openid=openid).first() or WxUser() # update user info wx_user.openid = openid nickname = userinfo.nickname nickname = ''.join(c for c in unicodedata.normalize('NFC', nickname) if c <= '\uFFFF') # remove emoji wx_user.nickname = nickname wx_user.headimg_url = userinfo.headimgurl wx_user.sex = userinfo.sex wx_user.province = userinfo.province wx_user.city = userinfo.city wx_user.country = userinfo.country wx_user.unionid = userinfo.get('unionid', '') wx_user.privilege = json.dumps(userinfo.privilege) wx_user.language = userinfo.language wx_user.save() # 关于UnionID机制 # 1、请注意,网页授权获取用户基本信息也遵循UnionID机制。即如果开发者有在多个公众号,或在公众号、移动应用之间统一用户帐号的需求,需要前往微信开放平台(open.weixin.qq.com)绑定公众号后,才可利用UnionID机制来满足上述需求。 # 2、UnionID机制的作用说明:如果开发者拥有多个移动应用、网站应用和公众帐号,可通过获取用户基本信息中的unionid来区分用户的唯一性,因为同一用户,对同一个微信开放平台下的不同应用(移动应用、网站应用和公众帐号),unionid是相同的。 user = wx_user.auth_user if not user: user = AuthUser.objects.filter(username=wx_user.openid).first() if not user: user = AuthUser.objects.create_user(username=wx_user.openid, password=wx_user.openid) wx_user.auth_user = user wx_user.save() user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) request.session['wx_openid'] = openid state = request.GET.get('state', None) if state: url = urlunquote(state) else: url = reverse('weixin:index') return HttpResponseRedirect(url)
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import django from django.core.urlresolvers import reverse from django import http from django.utils.http import urlunquote from mox3.mox import IsA # noqa from openstack_dashboard.api import cinder from openstack_dashboard.test import helpers as test VOLUME_INDEX_URL = reverse('horizon:project:volumes:index') VOLUME_CGROUPS_TAB_URL = urlunquote(reverse( 'horizon:project:volumes:cgroups_tab')) class ConsistencyGroupTests(test.TestCase): @test.create_stubs({cinder: ('volume_cgroup_create', 'volume_cgroup_list', 'volume_type_list', 'volume_type_list_with_qos_associations', 'availability_zone_list', 'extension_supported')}) def test_create_cgroup(self): cgroup = self.cinder_consistencygroups.first() volume_types = self.volume_types.list() az = self.cinder_availability_zones.first().zoneName formData = {'volume_types': '1', 'name': 'test CG',
def directory_listing(self, request, folder_id=None, viewtype=None): clipboard = tools.get_user_clipboard(request.user) if viewtype == 'images_with_missing_data': folder = ImagesWithMissingData() elif viewtype == 'unfiled_images': folder = UnsortedImages() elif viewtype == 'last': last_folder_id = request.session.get('filer_last_folder_id') try: self.get_queryset(request).get(id=last_folder_id) except self.model.DoesNotExist: url = reverse('admin:filer-directory_listing-root') url = "%s%s" % (url, admin_url_params_encoded(request)) else: url = reverse('admin:filer-directory_listing', kwargs={'folder_id': last_folder_id}) url = "%s%s" % (url, admin_url_params_encoded(request)) return HttpResponseRedirect(url) elif folder_id is None: folder = FolderRoot() else: folder = get_object_or_404(self.get_queryset(request), id=folder_id) request.session['filer_last_folder_id'] = folder_id # Check actions to see if any are available on this changelist actions = self.get_actions(request) # Remove action checkboxes if there aren't any actions available. list_display = list(self.list_display) if not actions: try: list_display.remove('action_checkbox') except ValueError: pass # search q = request.GET.get('q', None) if q: search_terms = urlunquote(q).split(" ") search_mode = True else: search_terms = [] q = '' search_mode = False # Limit search results to current folder. limit_search_to_folder = request.GET.get('limit_search_to_folder', False) in (True, 'on') if len(search_terms) > 0: if folder and limit_search_to_folder and not folder.is_root: # Do not include current folder itself in search results. folder_qs = folder.get_descendants(include_self=False) # Limit search results to files in the current folder or any # nested folder. file_qs = get_files_distinct_grouper_queryset().filter( folder__in=folder.get_descendants(include_self=True)) else: folder_qs = self.get_queryset(request) file_qs = get_files_distinct_grouper_queryset().all() folder_qs = self.filter_folder(folder_qs, search_terms) file_qs = self.filter_file(file_qs, search_terms) show_result_count = True else: folder_qs = folder.children.all() if isinstance(folder, Folder): file_qs = get_files_distinct_grouper_queryset().filter( folder=folder) else: file_qs = folder.files.all() show_result_count = False folder_qs = folder_qs.order_by('name') order_by = request.GET.get('order_by', None) if order_by is not None: order_by = order_by.split(',') order_by = [ field for field in order_by if re.sub(r'^-', '', field) in self.order_by_file_fields ] if len(order_by) > 0: file_qs = file_qs.order_by(*order_by) folder_children = [] folder_files = [] if folder.is_root and not search_mode: virtual_items = folder.virtual_folders else: virtual_items = [] perms = FolderPermission.objects.get_read_id_list(request.user) root_exclude_kw = {'parent__isnull': False, 'parent__id__in': perms} if perms != 'All': file_qs = file_qs.filter( models.Q(folder__id__in=perms) | models.Q(owner=request.user)) folder_qs = folder_qs.filter( models.Q(id__in=perms) | models.Q(owner=request.user)) else: root_exclude_kw.pop('parent__id__in') if folder.is_root: folder_qs = folder_qs.exclude(**root_exclude_kw) folder_children += folder_qs folder_files += file_qs try: permissions = { 'has_edit_permission': folder.has_edit_permission(request), 'has_read_permission': folder.has_read_permission(request), 'has_add_children_permission': folder.has_add_children_permission(request), } except: # noqa permissions = {} if order_by is None or len(order_by) == 0: folder_files.sort() items = folder_children + folder_files paginator = Paginator(items, filer.settings.FILER_PAGINATE_BY) # Are we moving to clipboard? if request.method == 'POST' and '_save' not in request.POST: # TODO: Refactor/remove clipboard parts for f in folder_files: if "move-to-clipboard-%d" % (f.id, ) in request.POST: clipboard = tools.get_user_clipboard(request.user) if f.has_edit_permission(request): tools.move_file_to_clipboard([f], clipboard) return HttpResponseRedirect(request.get_full_path()) else: raise PermissionDenied selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME) # Actions with no confirmation if (actions and request.method == 'POST' and 'index' in request.POST and '_save' not in request.POST): if selected: response = self.response_action(request, files_queryset=file_qs, folders_queryset=folder_qs) if response: return response else: msg = _("Items must be selected in order to perform " "actions on them. No items have been changed.") self.message_user(request, msg) # Actions with confirmation if (actions and request.method == 'POST' and helpers.ACTION_CHECKBOX_NAME in request.POST and 'index' not in request.POST and '_save' not in request.POST): if selected: response = self.response_action(request, files_queryset=file_qs, folders_queryset=folder_qs) if response: return response # Build the action form and populate it with available actions. if actions: action_form = self.action_form(auto_id=None) action_form.fields['action'].choices = self.get_action_choices(request) else: action_form = None selection_note_all = ungettext('%(total_count)s selected', 'All %(total_count)s selected', paginator.count) # If page request (9999) is out of range, deliver last page of results. try: paginated_items = paginator.page(request.GET.get('page', 1)) except PageNotAnInteger: paginated_items = paginator.page(1) except EmptyPage: paginated_items = paginator.page(paginator.num_pages) context = self.admin_site.each_context(request) context.update({ 'folder': folder, 'clipboard_files': get_files_distinct_grouper_queryset().filter( in_clipboards__clipboarditem__clipboard__user=request.user ).distinct(), 'paginator': paginator, 'paginated_items': paginated_items, 'virtual_items': virtual_items, 'uploader_connections': filer.settings.FILER_UPLOADER_CONNECTIONS, 'permissions': permissions, 'permstest': userperms_for_request(folder, request), 'current_url': request.path, 'title': _('Directory listing for %(folder_name)s') % { 'folder_name': folder.name }, 'search_string': ' '.join(search_terms), 'q': urlquote(q), 'show_result_count': show_result_count, 'folder_children': folder_children, 'folder_files': folder_files, 'limit_search_to_folder': limit_search_to_folder, 'is_popup': popup_status(request), 'filer_admin_context': AdminContext(request), # needed in the admin/base.html template for logout links 'root_path': reverse('admin:index'), 'action_form': action_form, 'actions_on_top': self.actions_on_top, 'actions_on_bottom': self.actions_on_bottom, 'actions_selection_counter': self.actions_selection_counter, 'selection_note': _('0 of %(cnt)s selected') % { 'cnt': len(paginated_items.object_list) }, 'selection_note_all': selection_note_all % { 'total_count': paginator.count }, 'media': self.media, 'enable_permissions': filer.settings.FILER_ENABLE_PERMISSIONS, 'can_make_folder': request.user.is_superuser or (folder.is_root and filer.settings.FILER_ALLOW_REGULAR_USERS_TO_ADD_ROOT_FOLDERS) or permissions.get("has_add_children_permission"), }) return render(request, self.directory_listing_template, context)
def post(self, request, *args, **kwargs): service = get_service_instance() config = service.config payment_mean = PaymentMean.objects.get(slug='paypal') if getattr(settings, 'DEBUG', False): paypal = json.loads(payment_mean.credentials) else: try: paypal = json.loads(payment_mean.credentials) except: return HttpResponse( "Error, Could not parse PayPal parameters.") try: order = parse_order_info(request) except: return HttpResponseRedirect(reverse('shopping:checkout')) order.retailer = service order.payment_mean = payment_mean order.save() # Save first to generate the Order id order = Order.objects.get( pk=order.id ) # Grab the newly created object to avoid create another one in subsequent save() member = request.user if member.is_authenticated(): order.member = member else: order.aotc = generate_tx_code(order.id, order.anonymous_buyer.auto_inc) order.rcc = generate_tx_code(order.id, config.rel_id) order.save() if getattr(settings, 'UNIT_TESTING', False): signature = 'dumb_signature' else: signature = ''.join([ random.SystemRandom().choice(string.ascii_letters + string.digits) for n in range(16) ]) request.session['signature'] = signature request.session['return_url'] = service.url + reverse( 'shopping:cart', args=(order.id, )) if getattr(settings, 'UNIT_TESTING', False): return HttpResponse(json.dumps({"order_id": order.id})) line_items = {} for i in range(len(order.entries)): entry = order.entries[i] product = entry.product line_items.update({ "L_PAYMENTREQUEST_0_NAME%d" % i: product.name, "L_PAYMENTREQUEST_0_DESC%d" % i: product.summary if product.summary else '<' + _("No description") + '>', "L_PAYMENTREQUEST_0_AMT%d" % i: do_currency(product.retail_price, order.currency.code), "L_PAYMENTREQUEST_0_QTY%d" % i: entry.count, "L_PAYMENTREQUEST_0_TAXAMT%d" % i: 0, "L_PAYMENTREQUEST_0_NUMBER%d" % i: i + 1, "L_PAYMENTREQUEST_0_ITEMURL%d" % i: service.url + reverse('shopping:product_detail', args=( product.category.slug, product.slug, )), "L_PAYMENTREQUEST_0_ITEMCATEGORY%d" % i: 'Physical' }) ec_data = { "USER": paypal['username'], "PWD": paypal['password'], "SIGNATURE": paypal['signature'], "METHOD": "SetExpressCheckout", "VERSION": 124.0, "RETURNURL": service.url + reverse('shopping:paypal_get_details') + '?order_id=' + order.id, "CANCELURL": service.url + reverse('shopping:paypal_cancel'), "PAYMENTREQUEST_0_PAYMENTACTION": "Sale", "PAYMENTREQUEST_0_AMT": do_currency(order.total_cost, order.currency.code), "PAYMENTREQUEST_0_ITEMAMT": do_currency(order.items_cost, order.currency.code), "PAYMENTREQUEST_0_SHIPPINGAMT": do_currency(order.delivery_option.cost, order.currency.code), "PAYMENTREQUEST_0_TAXAMT": 0, "PAYMENTREQUEST_0_CURRENCYCODE": order.currency.code, "PAYMENTREQUEST_0_DESC": "Purchase on " + service.project_name } ec_data.update(line_items) try: response = requests.post(EC_ENDPOINT, data=ec_data) result = parse_paypal_response(response.content.decode('utf-8')) ACK = result['ACK'] if ACK == 'Success' or ACK == 'SuccessWithWarning': if getattr(settings, 'DEBUG', False): redirect_url = 'https://www.sandbox.paypal.com/checkoutnow?token=' + result[ 'TOKEN'] else: redirect_url = 'https://www.paypal.com/checkoutnow?token=' + result[ 'TOKEN'] return HttpResponseRedirect(redirect_url) else: order.delete() context = self.get_context_data(**kwargs) if getattr(settings, 'DEBUG', False): context['paypal_error'] = urlunquote( response.content.decode('utf-8')) else: context['paypal_error'] = urlunquote( result['L_LONGMESSAGE0']) return render(request, 'shopping/paypal/cancel.html', context) except Exception as e: logger.error("%s - PayPal error." % service.project_name, exc_info=True) if getattr(settings, 'DEBUG', False): raise e context = self.get_context_data(**kwargs) context[ 'server_error'] = 'Could not initiate transaction due to server error. Contact administrator.' return render(request, 'shopping/paypal/cancel.html', context)
def post(self, request, *args, **kwargs): service = get_service_instance() config = service.config payment_mean = PaymentMean.objects.get(slug='paypal') if getattr(settings, 'DEBUG', False): paypal = json.loads(payment_mean.credentials) else: try: paypal = json.loads(payment_mean.credentials) except: return HttpResponse("Error, Could not parse PayPal parameters.") amount = request.POST["amount"] if getattr(settings, 'UNIT_TESTING', False): signature = 'dumb_signature' else: signature = ''.join([random.SystemRandom().choice(string.ascii_letters + string.digits) for n in range(16)]) request.session['amount'] = amount request.session['signature'] = signature request.session['return_url'] = service.url + reverse('donation:home') if getattr(settings, 'UNIT_TESTING', False): return HttpResponse(json.dumps({"amount": amount})) line_items = { "L_PAYMENTREQUEST_0_NAME0": 'Donation', "L_PAYMENTREQUEST_0_DESC0": '<' + _("No description") + '>', "L_PAYMENTREQUEST_0_AMT0": amount, "L_PAYMENTREQUEST_0_QTY0": 1, "L_PAYMENTREQUEST_0_TAXAMT0": 0, "L_PAYMENTREQUEST_0_NUMBER0": 1, "L_PAYMENTREQUEST_0_ITEMURL0": service.url + reverse('donation:home'), "L_PAYMENTREQUEST_0_ITEMCATEGORY0": 'Physical' } ec_data = { "USER": paypal['username'], "PWD": paypal['password'], "SIGNATURE": paypal['signature'], "METHOD": "SetExpressCheckout", "VERSION": 124.0, "RETURNURL": service.url + reverse('donation:paypal_get_details') + '?amount=' + amount, "CANCELURL": service.url + reverse('donation:paypal_cancel'), "PAYMENTREQUEST_0_PAYMENTACTION": "Sale", "PAYMENTREQUEST_0_AMT": amount, "PAYMENTREQUEST_0_ITEMAMT": amount, "PAYMENTREQUEST_0_SHIPPINGAMT": 0, "PAYMENTREQUEST_0_TAXAMT": 0, "PAYMENTREQUEST_0_CURRENCYCODE": "EUR", "PAYMENTREQUEST_0_DESC": "Donation on " + service.project_name } ec_data.update(line_items) try: response = requests.post(EC_ENDPOINT, data=ec_data) result = parse_paypal_response(response.content.decode('utf-8')) ACK = result['ACK'] if ACK == 'Success' or ACK == 'SuccessWithWarning': if getattr(settings, 'DEBUG', False): redirect_url = 'https://www.sandbox.paypal.com/checkoutnow?token=' + result['TOKEN'] else: redirect_url = 'https://www.paypal.com/checkoutnow?token=' + result['TOKEN'] return HttpResponseRedirect(redirect_url) else: context = self.get_context_data(**kwargs) if getattr(settings, 'DEBUG', False): context['paypal_error'] = urlunquote(response.content.decode('utf-8')) else: context['paypal_error'] = urlunquote(result['L_LONGMESSAGE0']) return render(request, 'donation/institution/home.html', context) except Exception as e: if getattr(settings, 'DEBUG', False): raise e context = self.get_context_data(**kwargs) context['server_error'] = 'Could not initiate transaction due to server error. Contact administrator.' return render(request, 'donation/institution/home.html', context)
def post(self, request, *args, **kwargs): if getattr(settings, 'UNIT_TESTING', False): return confirm_checkout(request, signature=request.session['signature'], *args, **kwargs) service = get_service_instance() paypal = json.loads(PaymentMean.objects.get(slug='paypal').credentials) amount = request.POST['amount'] line_items = { "L_PAYMENTREQUEST_0_NAME0": "Donation", "L_PAYMENTREQUEST_0_DESC0": '<' + _("No description") + '>', "L_PAYMENTREQUEST_0_AMT0": amount, "L_PAYMENTREQUEST_0_QTY0": 1, "L_PAYMENTREQUEST_0_TAXAMT0": 0, "L_PAYMENTREQUEST_0_NUMBER0": 1, "L_PAYMENTREQUEST_0_ITEMURL0": service.url + reverse('donation:home'), "L_PAYMENTREQUEST_0_ITEMCATEGORY0": 'Physical' } ec_data = { "USER": paypal['username'], "PWD": paypal['password'], "SIGNATURE": paypal['signature'], "METHOD": "DoExpressCheckoutPayment", "VERSION": 124.0, "TOKEN": request.session['token'], "PAYERID": request.session['payer_id'], "PAYMENTREQUEST_0_PAYMENTACTION": "Sale", "PAYMENTREQUEST_0_AMT": amount, "PAYMENTREQUEST_0_ITEMAMT": amount, "PAYMENTREQUEST_0_SHIPPINGAMT": 0, "PAYMENTREQUEST_0_TAXAMT": 0, "PAYMENTREQUEST_0_CURRENCYCODE": "EUR", "PAYMENTREQUEST_0_DESC": "Donation on " + service.project_name } ec_data.update(line_items) if getattr(settings, 'DEBUG', False): response = requests.post(EC_ENDPOINT, data=ec_data) result = parse_paypal_response(response.content.decode('utf-8')) ACK = result['ACK'] if ACK == 'Success' or ACK == 'SuccessWithWarning': request.session['mean'] = 'paypal' return donation_do_checkout(request, signature=request.session['signature'], *args, **kwargs) else: context = self.get_context_data(**kwargs) if getattr(settings, 'DEBUG', False): context['paypal_error'] = urlunquote(response.content.decode('utf-8')) else: context['paypal_error'] = urlunquote(result['L_LONGMESSAGE0']) return render(request, 'donation/institution/home.html', context) else: try: response = requests.post(EC_ENDPOINT, data=ec_data) result = parse_paypal_response(response.content.decode('utf-8')) ACK = result['ACK'] if ACK == 'Success' or ACK == 'SuccessWithWarning': return confirm_checkout(request, signature=request.session['signature'], *args, **kwargs) else: context = self.get_context_data(**kwargs) if getattr(settings, 'DEBUG', False): context['paypal_error'] = urlunquote(response.content.decode('utf-8')) else: context['paypal_error'] = urlunquote(result['L_LONGMESSAGE0']) return render(request,'donation/paypal/cancel.html', context) except Exception as e: context = self.get_context_data(**kwargs) context['server_error'] = 'Could not proceed transaction due to server error. Contact administrator.' return render(request, 'donation/paypal/cancel.html', context)
def get_object(self, queryset=None): # Use urlunquote to accept quoted twice URLs (for instance in MPs send # through emarkdown parser) return get_object_or_404(User, username=urlunquote(self.kwargs['user_name']))
def custom_promotion_order_view(admin_view, request, pk, title, read_only): changelist_filters = request.GET.get('_changelist_filters') url_filters = urlunquote(changelist_filters) if changelist_filters else '' order = PromotionOrder.objects.get(id=pk) if request.method != 'POST': user_info = order.user.payment_info try: user_info = simplejson.loads(user_info) user_info = simplejson.dumps(user_info, ensure_ascii=False, indent=2, sort_keys=True) except Exception: pass form = PromotionOrderForm( initial={ 'id': order.id, 'user': order.user, 'amount': order.amount, 'currency': order.currency, 'user_info': user_info, 'instance': order, }) if not read_only: if order.status not in [ REFERRAL_STATUS.pending, REFERRAL_STATUS.processing ]: messages.warning(request, 'Order is in invalid status to process') return HttpResponseRedirect( reverse("admin:coin_exchange_promotionorder_changelist") + '?{}'.format(url_filters)) # Change to processing status if order.status == REFERRAL_STATUS.pending: order.status = REFERRAL_STATUS.processing order.save(update_fields=['status', 'updated_at']) else: action = request.POST['action'].lower() if action == 'approve': order.status = REFERRAL_STATUS.paid order.save(update_fields=['status', 'updated_at']) messages.success(request, 'Order is approved successful.') elif action == 'reject': order.status = REFERRAL_STATUS.rejected order.save(update_fields=['status', 'updated_at']) messages.success(request, 'Order is rejected successful.') return HttpResponseRedirect( reverse("admin:coin_exchange_promotionorder_changelist") + '?{}'.format(url_filters)) context = admin_view.admin_site.each_context(request) context['opts'] = admin_view.model._meta context['form'] = form context['obj'] = order context['title'] = title context['read_only'] = read_only context['url_filters'] = url_filters return TemplateResponse( request, 'admin/order/promotion_order.html', context, )
def custom_fund_view(admin_view, request, pk, title, action): changelist_filters = request.GET.get('_changelist_filters') url_filters = urlunquote(changelist_filters) if changelist_filters else '' fund = CryptoFund.objects.get(id=pk) if request.method != 'POST': form = FundForm( initial={ 'available_amount': '{:.6f}'.format(fund.amount), 'currency': fund.currency, 'to_amount': '', 'to_currency': fund.currency, 'fund_type': fund.fund_type, 'convert': 'convert' in action }) else: form = FundForm(request.POST, initial={ 'available_amount': '{:.6f}'.format(fund.amount), 'currency': fund.currency, 'fund_type': fund.fund_type, 'convert': 'convert' in action }) is_success = True if form.is_valid(): amount = form.cleaned_data['to_amount'] currency = form.cleaned_data['to_currency'] if not currency: currency = fund.currency if action == 'transfer_out_fund': if fund.fund_type == CRYPTO_FUND_TYPE.in_fund: FundManagement.transfer_in_fund_to_out_fund( currency, amount) else: FundManagement.transfer_storage_to_out_fund( currency, amount) messages.success(request, 'Request sent successfully.') elif action == 'transfer_storage_fund': FundManagement.transfer_in_fund_to_storage(currency, amount) messages.success(request, 'Request sent successfully.') elif action == 'convert_from_storage_fund': FundManagement.convert_storage_to_vault(currency, amount) messages.success(request, 'Request sent successfully.') elif action == 'convert_to_storage_fund': if currency != CURRENCY.USDT: FundManagement.convert_vault_to_storage(currency, amount) messages.success(request, 'Request sent successfully.') else: messages.error(request, 'Please choose other currency.') is_success = False if is_success: return HttpResponseRedirect( reverse("admin:coin_exchange_cryptofund_changelist") + '?{}'.format(url_filters)) context = admin_view.admin_site.each_context(request) context['opts'] = admin_view.model._meta context['form'] = form context['obj'] = fund context['title'] = title context['url_filters'] = url_filters return TemplateResponse( request, 'admin/fund/fund.html', context, )
def search(request): timeTaken = 0 if request.method != 'POST': # if not a post, show the search form if 'aainput' in request.GET: # prefill the search form with a referring AA sequence aainput = urlunquote(request.GET['aainput']) messages.success(request, 'Imported AA sequence from previous page') elif 'subunit' in request.GET: # prefill the search form with a referring PKS subunit id subunitid = int(request.GET['subunit']) assert 0 <= subunitid subunit = Subunit.objects.get(id=subunitid) aainput = subunit.sequence messages.success( request, 'Imported sequence for PKS cluster %s subunit %s' % (subunit.cluster.description, subunit.name)) else: aainput = '' context = {'aainput': aainput} return render(request, 'sequencesearch.html', context) elif 'aainput' in request.POST: # if this is a post, validate the input and # run alignment try: # validate all inputs searchDatabase = str(request.POST['searchDatabase']) maxHits = int(request.POST['maxHits']) assert 1 <= maxHits <= 10000 inputs = request.POST['aainput'] evalue = float(request.POST['evalue']) assert 0.0 <= evalue <= 10.0 showAllDomains = int(request.POST['showAllDomains']) assert 0 <= showAllDomains <= 1 inputs = inputs.strip() if len(re.findall('>.*?\n', inputs)) >= 2: messages.error( request, 'Error: Multiple queries detected, please remove until only one query is present' ) return render(request, 'sequencesearch.html') inputs = re.sub('^>.*?\n', '', inputs) inputs = re.sub('\s', '', inputs) if len(inputs) == 0: messages.error(request, 'Error: Empty Query') return render(request, 'sequencesearch.html') if len(inputs) > 50000: messages.error(request, 'Error: max query size is 50,000 residues') return render(request, 'sequencesearch.html') # use alignment cache if it exists alignments = cache.get( (inputs, evalue, maxHits, showAllDomains, searchDatabase)) # run Blast if there is no cached alignment if alignments is None: if searchDatabase == "reviewed": db = os.path.join( settings.BASE_DIR, 'pipeline', 'data', 'blast', 'clustercad_subunits_reviewed', ) else: db = os.path.join( settings.BASE_DIR, 'pipeline', 'data', 'blast', 'clustercad_subunits_all', ) results = blast.delay(query=inputs, evalue=evalue, max_target_seqs=maxHits, sortOutput=True, database=db) results, timeTaken, queries_found = results.get() #If no queries found, then no hits if not queries_found: messages.error(request, 'No hits - please refine query!') return render(request, 'sequencesearch.html') #Read from jsonized pandas dataframe df = pd.read_json(results) #Get the subunits and process domains and modules subjectacc_separater = lambda x: Subunit.objects.get( id=x.split('_')[1], cluster__mibigAccession=x.split('_')[0]) df['subunit'] = df['subject acc.ver'].map(subjectacc_separater) domain_getter = lambda x: Domain.objects.filter( module__subunit=x['subunit'], stop__gte=x['s. start'], start__lte=x['s. end']).select_subclasses().order_by( 'start') df['domains'] = df.apply(domain_getter, axis=1) module_getter = lambda x: list( set([domain.module for domain in x['domains']])) df['modules'] = df.apply(module_getter, axis=1) #User option to show all domains if showAllDomains: show_all_domains_func = lambda x: [{ 'module': module, 'domains': list( Domain.objects.filter(module=module). select_subclasses().order_by('start')) } for module in x['modules']] df['modules'] = df.apply(show_all_domains_func, axis=1) #Other option to show only relevant domains else: module_dict_getter = lambda x: [{ 'module': module, 'domains': list(x['domains'].filter(module=module)) } for module in x['modules']] df['modules'] = df.apply(module_dict_getter, axis=1) #Keep useful columns only df = df[[ 'subunit', 'modules', 'q. start', 'q. end', 's. start', 's. end', 'evalue', 'bit score', 'domains' ]] df = df.sort_values('bit score', ascending=False) alignments = df #Set cache cache.set( (inputs, evalue, maxHits, showAllDomains, searchDatabase), alignments, 60 * 60 * 24 * 7) # cache for one week except ValueError: messages.error(request, 'Error: Invalid query!') return render(request, 'sequencesearch.html') else: raise Http404 # get domain options to display in UI get_all_domains = lambda x: [ domain for module in x['modules'] for domain in module['domains'] ] domains = alignments.apply(get_all_domains, axis=1).tolist() #flatten the list domains = list(chain.from_iterable(domains)) #Extract desired types for html showing ats = list(filter(lambda d: isinstance(d, AT), domains)) atsubstrates = list(set([at.substrate for at in ats])) krs = list(filter(lambda d: isinstance(d, KR), domains)) krtypes = list(set([kr.type for kr in krs])) boolDomains = [] for domain in (DH, ER, cMT, oMT): thesedomains = list(filter(lambda d: isinstance(d, domain), domains)) typelist = list(set([str(d) for d in thesedomains])) if len(typelist) > 0: boolDomains.append((domain.__name__, typelist)) tes = list(filter(lambda d: isinstance(d, TE), domains)) tetypes = list(set([str(te) for te in tes])) alignments = alignments.values.tolist() # create context dict of all results to show the user context = { 'alignments': alignments, 'queryResidues': len(inputs), 'evalue': str(evalue), 'maxHits': str(maxHits), 'timeTaken': timeTaken, 'showAllDomains': showAllDomains, 'atsubstrates': atsubstrates, 'krtypes': krtypes, 'boolDomains': boolDomains, 'tetypes': tetypes, 'searchDatabase': str(searchDatabase), } return render(request, 'sequenceresult.html', context)
def resolve(request, lang='ru', slug=''): if hasattr(request, 'LANGUAGE_CODE' ) and request.LANGUAGE_CODE and lang != request.LANGUAGE_CODE: return redirect('/%s/%s' % (request.LANGUAGE_CODE, slug)) try: slug = Slug.objects.get(slug=slug) except Slug.DoesNotExist: pass staticDir = '{CACHE_URL}cache/html/{device}/{lang}/static/'.format( device=request.folder, lang=lang, CACHE_URL=CACHE_URL) if not os.path.isfile(staticDir + 'categories.html'): StaticView(request, staticDir) if slug and type(slug) != str: Obj = eval(slug.model) page = request.GET.get('page') or '' if Obj == Page: root = staticDir path = '{root}{path}'.format(path=slug.slug or 'index', root=root) + page else: if not slug.slug: raise Http404() if len(slug.slug) > 4: root = '{CACHE_URL}cache/html/{device}/{lang}/{slug[3]}/{slug[4]}/'.format( device=request.folder, lang=lang, slug=slug, CACHE_URL=CACHE_URL) elif len(slug.slug) > 2: root = '{CACHE_URL}cache/html/{device}/{lang}/{slug[1]}/{slug[2]}/'.format( device=request.folder, lang=lang, slug=slug, CACHE_URL=CACHE_URL) else: root = '{CACHE_URL}cache/html/{device}/{lang}/m/a/'.format( device=request.folder, lang=lang, slug=slug, CACHE_URL=CACHE_URL) path = root + str(slug).replace('/', '') + request.GET.urlencode() path = path[:255] if request.is_ajax(): path += 'ajax' if request.user.is_opt: path += 'opt' obj = Obj.objects.values( 'cached', 'description__last_modified').filter(pk=slug.model_id).order_by( 'description__last_modified').last() try: last_modified = http_date( timegm(obj.get('description__last_modified').utctimetuple())) except: last_modified = http_date(timegm(timezone.now().utctimetuple())) if obj and obj.get('cached') and os.path.isfile(path): with open(path, 'rb') as content: if request.is_ajax() and page: response = HttpResponse(content.read(), content_type="text/html") response['Last-Modified'] = last_modified return response else: response = render(request, 'shop/%s/index.html' % request.folder, context={ 'view': slug.view, 'content': content.read() }) response['Last-Modified'] = last_modified return response elif obj: obj = Obj.objects.prefetch_related('description').get( pk=slug.model_id) last_modified = obj.description.order_by('last_modified').last() if not last_modified: last_modified = http_date(timegm( timezone.now().utctimetuple())) else: last_modified = http_date( timegm(last_modified.last_modified.utctimetuple())) view = eval("%sView" % slug.view).as_view() response = view(request, obj, lang=lang) obj.cached = True obj.update() if not os.path.isdir(root): try: os.makedirs(root) except FileExistsError: pass with open(path, 'wb') as file: file.write( response.content.decode('utf8').replace('\n', '').replace( '\t', '').encode('utf8')) if request.is_ajax() and page: response['Last-Modified'] = last_modified return response else: response = render(request, 'shop/%s/index.html' % request.folder, context={ 'view': slug.view, 'content': response.content }) response['Last-Modified'] = last_modified return response try: permanent = Redirect.objects.get(old_path=urlunquote(slug)) return HttpResponsePermanentRedirect('/' + permanent.new_path) except Redirect.DoesNotExist: pass # if not slug: # return render(request,'shop/%s/index.html' % request.folder,context={'view':slug.model,'content':''}) raise Http404('Такой страницы не существует.')
def test_unquote(self): self.assertEqual(urlunquote('Paris%20%26%20Orl%C3%A9ans'), 'Paris & Orl\xe9ans') self.assertEqual(urlunquote('Paris%20&%20Orl%C3%A9ans'), 'Paris & Orl\xe9ans')
def wx_auth(request, app_name): try: app = WxApp.objects.get(name=app_name) request.session['wx_app_name'] = app.name request.session['wx_app_id'] = app.app_id except ObjectDoesNotExist: raise Http404 code = request.GET.get("code", None) if code is None: return HttpResponse('No Code Provided.') wx_login = WeixinLogin(app.app_id, app.app_secret) data = wx_login.access_token(code) openid = data.openid request.session['wx_openid'] = openid scope = data.scope token = data.access_token # 网页授权access_token和公众号的access_token不一样 # 关于网页授权access_token和普通access_token的区别 # 1、微信网页授权是通过OAuth2.0机制实现的,在用户授权给公众号后,公众号可以获取到一个网页授权特有的接口调用凭证(网页授权access_token),通过网页授权access_token可以进行授权后接口调用,如获取用户基本信息; # 2、其他微信接口,需要通过基础支持中的“获取access_token”接口来获取到的普通access_token调用。 if (scope == conf.SCOPE_USERINFO): # continue to get userinfo userinfo = wx_login.user_info(token, openid) wx_user = WxUser.objects.filter(openid=openid).first() or WxUser() # update user info wx_user.openid = openid wx_user.nickname = userinfo.nickname wx_user.headimg_url = userinfo.headimgurl wx_user.sex = userinfo.sex wx_user.province = userinfo.province wx_user.city = userinfo.city wx_user.country = userinfo.country wx_user.unionid = userinfo.get('unionid', None) wx_user.privilege = json.dumps(userinfo.privilege) wx_user.language = userinfo.language # 关于UnionID机制 # 1、请注意,网页授权获取用户基本信息也遵循UnionID机制。即如果开发者有在多个公众号,或在公众号、移动应用之间统一用户帐号的需求,需要前往微信开放平台(open.weixin.qq.com)绑定公众号后,才可利用UnionID机制来满足上述需求。 # 2、UnionID机制的作用说明:如果开发者拥有多个移动应用、网站应用和公众帐号,可通过获取用户基本信息中的unionid来区分用户的唯一性,因为同一用户,对同一个微信开放平台下的不同应用(移动应用、网站应用和公众帐号),unionid是相同的。 if not wx_user.auth_user: user, created = AuthUser.objects.get_or_create( type=AuthUser.WEIXIN, mobile=wx_user.openid) if created or getattr(user, 'customer', None): customer = Customer(name=wx_user.nickname) customer.auth_user = user wx_user.auth_user = user wx_user.save() user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) state = request.GET.get('state', None) # next url if state: url = urlunquote(state) else: url = reverse('weixin:index', args=[app_name]) return HttpResponseRedirect(url)
def post(self, request, *args, **kwargs): if getattr(settings, 'UNIT_TESTING', False): return confirm_checkout(request, signature=request.session['signature'], *args, **kwargs) service = get_service_instance() paypal = json.loads(PaymentMean.objects.get(slug='paypal').credentials) order_id = request.POST['order_id'] order = Order.objects.get(pk=order_id) line_items = {} for i in range(len(order.entries)): entry = order.entries[i] product = entry.product line_items.update({ "L_PAYMENTREQUEST_0_NAME%d" % i: product.name, "L_PAYMENTREQUEST_0_DESC%d" % i: product.summary if product.summary else '<' + _("No description") + '>', "L_PAYMENTREQUEST_0_AMT%d" % i: do_currency(product.retail_price, order.currency.code), "L_PAYMENTREQUEST_0_QTY%d" % i: entry.count, "L_PAYMENTREQUEST_0_TAXAMT%d" % i: 0, "L_PAYMENTREQUEST_0_NUMBER%d" % i: i + 1, "L_PAYMENTREQUEST_0_ITEMURL%d" % i: service.url + reverse('shopping:product_detail', args=( product.category.slug, product.slug, )), "L_PAYMENTREQUEST_0_ITEMCATEGORY%d" % i: 'Physical' }) ec_data = { "USER": paypal['username'], "PWD": paypal['password'], "SIGNATURE": paypal['signature'], "METHOD": "DoExpressCheckoutPayment", "VERSION": 124.0, "TOKEN": request.session['token'], "PAYERID": request.session['payer_id'], "PAYMENTREQUEST_0_PAYMENTACTION": "Sale", "PAYMENTREQUEST_0_AMT": do_currency(order.total_cost, order.currency.code), "PAYMENTREQUEST_0_ITEMAMT": do_currency(order.items_cost, order.currency.code), "PAYMENTREQUEST_0_SHIPPINGAMT": do_currency(order.delivery_option.cost, order.currency.code), "PAYMENTREQUEST_0_TAXAMT": 0, "PAYMENTREQUEST_0_CURRENCYCODE": order.currency.code, "PAYMENTREQUEST_0_DESC": "Purchase on " + service.project_name } ec_data.update(line_items) if getattr(settings, 'DEBUG', False): response = requests.post(EC_ENDPOINT, data=ec_data) result = parse_paypal_response(response.content.decode('utf-8')) ACK = result['ACK'] if ACK == 'Success' or ACK == 'SuccessWithWarning': return confirm_checkout(request, signature=request.session['signature'], *args, **kwargs) else: try: Order.objects.get(pk=request.POST['order_id']).delete() except Order.DoesNotExist: pass context = self.get_context_data(**kwargs) if getattr(settings, 'DEBUG', False): context['paypal_error'] = urlunquote( response.content.decode('utf-8')) else: context['paypal_error'] = urlunquote( result['L_LONGMESSAGE0']) return render(request, 'shopping/paypal/cancel.html', context) else: try: response = requests.post(EC_ENDPOINT, data=ec_data) result = parse_paypal_response( response.content.decode('utf-8')) ACK = result['ACK'] if ACK == 'Success' or ACK == 'SuccessWithWarning': return confirm_checkout( request, signature=request.session['signature'], *args, **kwargs) else: try: Order.objects.get(pk=request.POST['order_id']).delete() except Order.DoesNotExist: pass context = self.get_context_data(**kwargs) if getattr(settings, 'DEBUG', False): context['paypal_error'] = urlunquote( response.content.decode('utf-8')) else: context['paypal_error'] = urlunquote( result['L_LONGMESSAGE0']) return render(request, 'shopping/paypal/cancel.html', context) except Exception as e: logger.error("%s - PayPal error. Order ID: %s" % (service.project_name, order.id), exc_info=True) context = self.get_context_data(**kwargs) context[ 'server_error'] = 'Could not proceed transaction due to server error. Contact administrator.' return render(request, 'shopping/paypal/cancel.html', context)
from django.test.utils import override_settings from django.utils.http import urlunquote from mox3.mox import IsA # noqa from openstack_dashboard import api from openstack_dashboard.dashboards.project.volumes.backups \ import tables as backup_tables from openstack_dashboard.dashboards.project.volumes.snapshots \ import tables as snapshot_tables from openstack_dashboard.dashboards.project.volumes.volumes \ import tables as volume_tables from openstack_dashboard.test import helpers as test INDEX_URL = reverse('horizon:project:volumes:index') VOLUME_SNAPSHOTS_TAB_URL = urlunquote( reverse('horizon:project:volumes:snapshots_tab')) VOLUME_BACKUPS_TAB_URL = urlunquote( reverse('horizon:project:volumes:backups_tab')) class VolumeAndSnapshotsAndBackupsTests(test.TestCase): @test.create_stubs({ api.cinder: ( 'tenant_absolute_limits', 'volume_list', 'volume_list_paged', 'volume_snapshot_list', 'volume_snapshot_list_paged', 'volume_backup_supported', 'volume_backup_list_paged', ),
def _check_internal(self, tested_url): from linkcheck.utils import LinkCheckHandler if not (tested_url): self.message = 'Empty link' elif tested_url.startswith('mailto:'): self.status = None self.message = 'Email link (not automatically checked)' elif tested_url.startswith('#'): self.status = None self.message = 'Link to within the same page (not automatically checked)' elif tested_url.startswith(MEDIA_PREFIX): # TODO Assumes a direct mapping from media url to local filesystem path. This will break quite easily for alternate setups path = settings.MEDIA_ROOT + urlunquote( tested_url)[len(MEDIA_PREFIX) - 1:] decoded_path = html_decode(path) if os.path.exists(path) or os.path.exists(decoded_path): self.message = 'Working file link' self.status = True else: self.message = 'Missing Document' elif getattr(self, '_internal_hash', False) and getattr( self, '_instance', None): # This is a hash link pointing to itself from linkcheck import parse_anchors hash = self._internal_hash instance = self._instance if hash == '#': # special case, point to # self.message = 'Working internal hash anchor' self.status = True else: hash = hash[1:] #'#something' => 'something' html_content = '' for field in instance._linklist.html_fields: html_content += getattr(instance, field, '') names = parse_anchors(html_content) if hash in names: self.message = 'Working internal hash anchor' self.status = True else: self.message = 'Broken internal hash anchor' elif tested_url.startswith('/'): old_prepend_setting = settings.PREPEND_WWW settings.PREPEND_WWW = False c = Client() c.handler = LinkCheckHandler() response = c.get(tested_url) if USE_REVERSION: # using test client will clear the RevisionContextManager stack. revision_context_manager.start() if response.status_code == 200: self.message = 'Working internal link' self.status = True # see if the internal link points an anchor if tested_url[-1] == '#': # special case, point to # self.message = 'Working internal hash anchor' elif tested_url.count('#'): anchor = tested_url.split('#')[1] from linkcheck import parse_anchors names = parse_anchors(response.content) if anchor in names: self.message = 'Working internal hash anchor' self.status = True else: self.message = 'Broken internal hash anchor' self.status = False elif response.status_code == 302 or response.status_code == 301: self.status = None self.message = 'This link redirects: code %d (not automatically checked)' % ( response.status_code, ) else: self.message = 'Broken internal link' settings.PREPEND_WWW = old_prepend_setting else: self.message = 'Invalid URL' self.last_checked = now() self.save()
# Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django import http from django.urls import reverse from django.utils.http import urlunquote from mox3.mox import IsA from openstack_dashboard.api import cinder from openstack_dashboard.test import helpers as test INDEX_URL = reverse('horizon:project:cgroups:index') VOLUME_CGROUPS_SNAP_INDEX_URL = urlunquote( reverse('horizon:project:cg_snapshots:index')) class ConsistencyGroupTests(test.TestCase): @test.create_stubs({ cinder: ('extension_supported', 'availability_zone_list', 'volume_type_list', 'volume_type_list_with_qos_associations', 'volume_cgroup_list', 'volume_cgroup_create') }) def test_create_cgroup(self): cgroup = self.cinder_consistencygroups.first() volume_types = self.cinder_volume_types.list() volume_type_id = self.cinder_volume_types.first().id az = self.cinder_availability_zones.first().zoneName formData = { 'volume_types': '1',
def queryset(self, request, queryset): if self.value(): return queryset.filter(service__name=urlunquote(self.value())) else: return queryset
def unquote_raw(value): return urlunquote(value)
def test_existing_user(self): user = User.objects.create(username='******', ) request = RequestFactory().get('/') send_registration_mail('*****@*****.**', request, user=user) self.assertEqual(len(mail.outbox), 1) body = mail.outbox[0].body url = urlunquote( [line for line in body.splitlines() if 'testserver' in line][0]) self.assertTrue( re.match(r'http://testserver/er/[email protected]:\d+:\w+:', url)) response = self.client.get(url) self.assertContains(response, 'id="id_new_password2"') response = self.client.post(url, { 'new_password1': 'pass', 'new_password2': 'pass', }) self.assertRedirects(response, '/ac/login/') user = User.objects.get() self.assertEqual(user.username, 'test') self.assertEqual(user.email, '') self.assertTrue(user.check_password('pass')) time.sleep(1.1) user.last_login = timezone.now() user.save() response = self.client.get(url, follow=True) self.assertEqual(_messages(response), ['The link has already been used.']) self.assertRedirects(response, '/') response = self.client.get( url.replace('/er/', '/er-quick/', 1), follow=True, ) self.assertEqual( _messages(response), ['The link is expired. Please request another registration link.']) response = self.client.get( url.replace('com:', 'ch:', 1), follow=True, ) self.assertEqual(_messages(response), [ 'Unable to verify the signature.' ' Please request a new registration link.' ]) user.delete() response = self.client.get(url, follow=True) self.assertEqual(_messages(response), [ 'Something went wrong while decoding the' ' registration request. Please try again.' ])
def post(self, request, *args, **kwargs): service = get_service_instance() payment_mean = PaymentMean.objects.get(slug='paypal') if getattr(settings, 'DEBUG', False): paypal = json.loads(payment_mean.credentials) else: try: paypal = json.loads(payment_mean.credentials) except: return HttpResponse( "Error, Could not parse PayPal parameters.") try: order = parse_order_info(request) except: messages.error(request, "Failed to parse order information") return HttpResponseRedirect(reverse('mediashop:cart')) if getattr(settings, 'UNIT_TESTING', False): signature = 'dumb_signature' else: signature = ''.join([ random.SystemRandom().choice(string.ascii_letters + string.digits) for n in range(16) ]) request.session['signature'] = signature request.session['return_url'] = service.url + reverse( 'mediashop:download', args=(order.id, )) if getattr(settings, 'UNIT_TESTING', False): return HttpResponse(json.dumps({"order_id": order.id})) line_items = {} for i in range(len(order.album_list)): album = order.album_list[i] line_items.update({ "L_PAYMENTREQUEST_0_NAME%d" % i: album.title, "L_PAYMENTREQUEST_0_DESC%d" % i: album.title, "L_PAYMENTREQUEST_0_AMT%d" % i: do_currency(album.cost, order.currency.code), "L_PAYMENTREQUEST_0_QTY%d" % i: 1, "L_PAYMENTREQUEST_0_TAXAMT%d" % i: 0, "L_PAYMENTREQUEST_0_NUMBER%d" % i: i + 1, "L_PAYMENTREQUEST_0_ITEMURL%d" % i: service.url + reverse('mediashop:music_item_detail', args=( album.artist.slug, album.slug, )), "L_PAYMENTREQUEST_0_ITEMCATEGORY%d" % i: 'Digital' }) for i in range(len(order.song_list)): song = order.song_list[i] line_items.update({ "L_PAYMENTREQUEST_0_NAME%d" % i: song.title, "L_PAYMENTREQUEST_0_DESC%d" % i: song.title, "L_PAYMENTREQUEST_0_AMT%d" % i: do_currency(song.cost, order.currency.code), "L_PAYMENTREQUEST_0_QTY%d" % i: 1, "L_PAYMENTREQUEST_0_TAXAMT%d" % i: 0, "L_PAYMENTREQUEST_0_NUMBER%d" % i: i + 1, "L_PAYMENTREQUEST_0_ITEMURL%d" % i: service.url + reverse('mediashop:music_item_detail', args=( song.artist.slug, song.slug, )), "L_PAYMENTREQUEST_0_ITEMCATEGORY%d" % i: 'Digital' }) ec_data = { "USER": paypal['username'], "PWD": paypal['password'], "SIGNATURE": paypal['signature'], "METHOD": "SetExpressCheckout", "VERSION": 124.0, "RETURNURL": service.url + reverse('mediashop:paypal_get_details') + '?order_id=' + order.id, "CANCELURL": service.url + reverse('mediashop:cart'), "PAYMENTREQUEST_0_PAYMENTACTION": "Sale", "PAYMENTREQUEST_0_AMT": do_currency(order.total_cost, order.currency.code), "PAYMENTREQUEST_0_ITEMAMT": do_currency(order.total_cost, order.currency.code), "PAYMENTREQUEST_0_SHIPPINGAMT": 0, "PAYMENTREQUEST_0_TAXAMT": 0, "PAYMENTREQUEST_0_CURRENCYCODE": order.currency.code, "PAYMENTREQUEST_0_DESC": "Purchase on " + service.project_name } ec_data.update(line_items) try: response = requests.post(EC_ENDPOINT, data=ec_data) result = parse_paypal_response(response.content.decode('utf-8')) ACK = result['ACK'] if ACK == 'Success' or ACK == 'SuccessWithWarning': if getattr(settings, 'DEBUG', False): redirect_url = 'https://www.sandbox.paypal.com/checkoutnow?token=' + result[ 'TOKEN'] else: redirect_url = 'https://www.paypal.com/checkoutnow?token=' + result[ 'TOKEN'] return HttpResponseRedirect(redirect_url) else: order.delete() context = self.get_context_data(**kwargs) if getattr(settings, 'DEBUG', False): context['paypal_error'] = urlunquote( response.content.decode('utf-8')) else: context['paypal_error'] = urlunquote( result['L_LONGMESSAGE0']) messages.error(request, 'Initiating PayPal transaction failed.') return HttpResponseRedirect(reverse('mediashop:cart')) except Exception as e: logger.error("%s - PayPal error." % service.project_name, exc_info=True) if getattr(settings, 'DEBUG', False): raise e context = self.get_context_data(**kwargs) messages.error( request, 'Could not initiate transaction due to server error. Contact administrator.' ) return render(request, 'shopping/paypal/cancel.html', context)
def get_plugin_id_from_response(self, response): url = urlunquote(response.url) # Ideal case, this looks like: # /en/admin/cms/page/edit-plugin/1/ return re.findall('\d+', url)[0]
def custom_order_view(admin_view, request, pk, title, read_only): changelist_filters = request.GET.get('_changelist_filters') url_filters = urlunquote(changelist_filters) if changelist_filters else '' order = Order.objects.get(id=pk) if request.method != 'POST': form = OrderBankForm( initial={ 'id': order.id, 'user': order.user, 'amount': order.amount, 'currency': order.currency, 'fiat_local_amount': order.fiat_local_amount, 'fiat_local_currency': order.fiat_local_currency, 'address': order.address, 'ref_code': order.ref_code, 'receipt_url': order.receipt_url, 'tx_hash': order.tx_hash, 'instance': order, }) if not read_only: if order.status not in [ORDER_STATUS.fiat_transferring, ORDER_STATUS.processing] and \ order.direction == DIRECTION.buy and \ order.order_type == ORDER_TYPE.bank: messages.warning(request, 'Order is in invalid status to process') return HttpResponseRedirect( reverse("admin:coin_exchange_order_changelist") + '?{}'.format(url_filters)) # Change to processing status if order.status == ORDER_STATUS.fiat_transferring: order.status = ORDER_STATUS.processing order.save(update_fields=['status', 'updated_at']) else: action = request.POST['action'].lower() if action == 'approve': OrderManagement.complete_order(order) messages.success( request, 'Order is approved successful. Sending crypto to destination...' ) elif action == 'reject': OrderManagement.reject_order(order) messages.success(request, 'Order is rejected successful.') return HttpResponseRedirect( reverse("admin:coin_exchange_order_changelist") + '?{}'.format(url_filters)) context = admin_view.admin_site.each_context(request) context['opts'] = admin_view.model._meta context['form'] = form context['obj'] = order context['title'] = title context['read_only'] = read_only context['url_filters'] = url_filters return TemplateResponse( request, 'admin/order/order_bank.html', context, )
def check_add_link_entity(self, uri): """ Checks to see if an entity exists, if not, it adds it if we recognize the URI to be part of a known vocabulary """ ent = LinkEntity.objects.filter(uri=uri).first() if ent: # We found the linked data entity. return ent label = None alt_label = None ent_type = 'class' vocab_uri = None if '.geonames.org' in uri: geo_api = GeonamesAPI() vocab_uri = GeonamesAPI().VOCAB_URI labels = geo_api.get_labels_for_uri(uri) if isinstance(labels, dict): # got the label! label = labels['label'] alt_label = labels['alt_label'] elif 'UBERON' in uri: uber_api = uberonAPI() vocab_uri = uberonAPI().VOCAB_URI label = uber_api.get_uri_label_from_graph(uri) if label is not False: alt_label = label elif 'eol.org' in uri: eol_api = eolAPI() vocab_uri = eolAPI().VOCAB_URI labels = eol_api.get_labels_for_uri(uri) if isinstance(labels, dict): # got the label! label = labels['label'] alt_label = labels['alt_label'] elif 'wikipedia.org' in uri: # page name in the URI of the article link_ex = uri.split('/') label = urlunquote(link_ex[-1]) label = label.replace('_', ' ') # underscores in Wikipedia titles alt_label = label vocab_uri = 'http://www.wikipedia.org/' elif 'vocab.getty.edu/aat' in uri: print('Finding: ' + uri) getty_api = gettyAPI() vocab_uri = gettyAPI().VOCAB_URI labels = getty_api.get_labels_for_uri(uri) if isinstance(labels, dict): # got the label! label = labels['label'] alt_label = labels['alt_label'] elif 'numismatics.org/ocre/id/' in uri: print('Finding: ' + uri) ANSochre = ANSochreAPI() vocab_uri = ANSochreAPI().VOCAB_URI labels = ANSochre.get_labels_for_uri(uri) if isinstance(labels, dict): # got the label! label = labels['label'] alt_label = labels['alt_label'] elif 'gbif.org/species/' in uri: ent = add_get_gbif_link_entity_and_hierarchy(uri) # This adds the linked entity to the database # as well as its hierarchy return ent if not label or not vocab_uri: # Something went wrong. Could not # add the item return None # ok to make an entity then! ent = LinkEntity() ent.uri = uri ent.label = label ent.alt_label = alt_label ent.vocab_uri = vocab_uri ent.ent_type = ent_type ent.sort = '' ent.save() return ent
def get_group_tiles(self, obj): return urlunquote(reverse('terra:group-tiles-pattern', args=[obj.group]))
def test_unmaskurl(self): quoted_url = "/Im5ld29uZXMvP2NhdGVnb3J5PTgxIg%3A1" + \ "XZ0wX%3AWt9m66_JAjW12unX9ggCIBK9eMg" unquoted_url = urlunquote(quoted_url.lstrip('/')) unmasked_url = '/%s' % loads(unquoted_url)
def custom_selling_cod_order_view(admin_view, request, pk, title, read_only): changelist_filters = request.GET.get('_changelist_filters') url_filters = urlunquote(changelist_filters) if changelist_filters else '' order = Order.objects.get(id=pk) if request.method != 'POST': payment = None payment_details = [] if order.selling_order_payments: payment = order.selling_order_payments.first() if payment: payment_details = payment.selling_payment_details user_info = order.user_info try: user_info = simplejson.loads(user_info) user_info = simplejson.dumps(user_info, ensure_ascii=False, indent=2, sort_keys=True) except Exception: pass form = SellingOrderForm( initial={ 'id': order.id, 'user': order.user, 'amount': order.amount, 'currency': order.currency, 'payment': '{:.6f} ({})'.format(payment.amount, PAYMENT_STATUS[ payment.status]), 'payment_details': payment_details, 'fiat_local_amount': order.fiat_local_amount, 'fiat_local_currency': order.fiat_local_currency, 'address': order.address, 'order_user_payment_type': ORDER_USER_PAYMENT_TYPE[order.order_user_payment_type] if order.order_user_payment_type else '-', 'user_info': user_info, 'ref_code': order.ref_code, 'tx_hash': order.tx_hash, 'instance': order, }) if not read_only: if order.status not in [ORDER_STATUS.transferred, ORDER_STATUS.processing] and \ order.direction == DIRECTION.buy and \ order.order_type == ORDER_TYPE.cod: messages.warning(request, 'Order is in invalid status to process') return HttpResponseRedirect( reverse("admin:coin_exchange_sellingorder_changelist") + '?{}'.format(url_filters)) # Change to processing status if order.status == ORDER_STATUS.transferred: order.status = ORDER_STATUS.processing order.save(update_fields=['status', 'updated_at']) else: action = request.POST['action'].lower() if action == 'approve': OrderManagement.complete_order(order) messages.success(request, 'Order is approved successful.') elif action == 'reject': OrderManagement.reject_order(order) messages.success(request, 'Order is rejected successful.') return HttpResponseRedirect( reverse("admin:coin_exchange_sellingorder_changelist") + '?{}'.format(url_filters)) context = admin_view.admin_site.each_context(request) context['opts'] = admin_view.model._meta context['form'] = form context['obj'] = order context['title'] = title context['read_only'] = read_only context['url_filters'] = url_filters return TemplateResponse( request, 'admin/order/selling_cod_order.html', context, )