def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) self.form.full_clean() search_params = {k: self.form.data[k] for k, v in self.form.cleaned_data.items() if v not in [None, '']} if hasattr(self, 'order'): search_params['order'] = self.order context['order'] = self.order else: context['order'] = self.get_model()._meta.ordering[0] if len(search_params): context['querystring'] = urlencode(search_params) try: search_params.pop('order') except Exception: pass context['querystring_without_order'] = urlencode(search_params) if len(context['querystring_without_order']) > 0: context['querystring_without_order'] += '&' else: context['querystring_without_order'] = '' if self.form.is_submitted(): context['add_search_form'] = SavedSearchForm() context['saved_search_url'] = resolve_url( 'contacts:search-save', type=self.model._meta.model_name, ) + '?' + context['querystring'] return context
def construct_url(url, query_dict = None, clean=False): parse_result = urlparse(url) query = {} if not clean: if len(parse_result.query) > 0: query = parse_qs(parse_result.query) for key, value in query.iteritems(): query[key] = value if query_dict is not None: for key, value in query_dict.iteritems(): if value is not None: query[key] = [value] if len(query.keys()) > 0: _query= [] for key, values in query.iteritems(): if len(values) == 1: _query.append(urlencode({key: values[0]})) else: for value in values: _query.append(urlencode({key: value})) query = '&'.join(_query) else: query = None return "%s%s%s" % ( parse_result.path, "?%s" % query if query is not None else '', "#%s" % parse_result.fragment if len(parse_result.fragment) > 0 else '')
def search(request): pagesize = 30 # per Flickr API TOS query = request.GET.get('q', '') or request.POST.get('q', '') try: page = int(request.GET.get('p', 1)) except ValueError: page = 1 f = FlickrSearch() results = f.search(query, page, pagesize) if query else None if results['records']: # Map URLs to IDs and find out which ones are already selected urls = [r['record_url'] for r in results['records']] ids = dict(Record.objects.filter(source__in=urls, manager='flickr').values_list('source', 'id')) selected = request.session.get('selected_records', ()) for r in results['records']: r['id'] = ids.get(r['record_url']) r['selected'] = r['id'] in selected pages = int(math.ceil(float(results['hits']) / pagesize)) if results else 0 prev_page_url = "?" + urlencode((('q', query), ('p', page - 1))) if page > 1 else None next_page_url = "?" + urlencode((('q', query), ('p', page + 1))) if page < pages else None return render_to_response('flickr-results.html', {'query': query, 'results': results, 'page': page, 'pages': pages, 'prev_page': prev_page_url, 'next_page': next_page_url, }, context_instance=RequestContext(request))
def search(request): pagesize = 50 query = request.GET.get('q', '') or request.POST.get('q', '') try: page = int(request.GET.get('p', 1)) except ValueError: page = 1 a = ArtstorSearch() try: results = a.search(query, page, pagesize) if query else None failure = False except urllib2.HTTPError: results = None failure = True pages = int(math.ceil(float(results['hits']) / pagesize)) if results else 0 prev_page_url = "?" + urlencode((('q', query), ('p', page - 1))) if page > 1 else None next_page_url = "?" + urlencode((('q', query), ('p', page + 1))) if page < pages else None return render_to_response('artstor-results.html', {'query': query, 'results': results, 'page': page, 'failure': failure, 'pages': pages, 'prev_page': prev_page_url, 'next_page': next_page_url, }, context_instance=RequestContext(request))
def assert_pic_is_correct(self, cd_key, pic, disc_pic_nbr=None): """Assert that the CD has the correct picture.""" assert cd_key in CDS_DATA assert pic in ('cover', 'disc') if pic == 'disc': assert disc_pic_nbr in (1, 2) cd = get_cd(cd_key=cd_key) cd_data = CDS_DATA[cd_key] if pic == 'cover': picture_path = cd_data['cover_path'] else: # disc picture_path = cd_data['disc%s_path' % disc_pic_nbr] download_url = reverse('db_file_storage.download_file') if pic == 'cover': download_url += '?' + urlencode({'name': cd.cover.name}) else: # disc download_url += '?' + urlencode({'name': cd.disc.name}) response = self.client.get(download_url) with open(picture_path, 'rb') as pic_file: # Assert that the contents of the saved picture are correct self.assertEqual(pic_file.read(), response.content) # Assert that the mimetype of the saved picture is correct self.assertEqual( mimetypes.guess_type(picture_path)[0], response['Content-Type'] )
def test_macos_apps_sha_256_search(self): self.log_user_in() # cert signature response = self.client.get("{}?{}".format( reverse("inventory:macos_apps"), urlencode({"sha_256": "7afc9d01a62f03a2de9637936d4afe68090d2de18d03f29c88cfb0b1ba63587f"}) )) self.assertContains(response, "1 macOS application") # binary signature response = self.client.get("{}?{}".format( reverse("inventory:macos_apps"), urlencode({"sha_256": 64 * "a"}) )) self.assertContains(response, "1 macOS application") # bad sha 256 response = self.client.get("{}?{}".format( reverse("inventory:macos_apps"), urlencode({"sha_256": 64 * "z"}) )) self.assertFormError(response, "search_form", "sha_256", "Enter a valid sha256.") # another sha 256 response = self.client.get("{}?{}".format( reverse("inventory:macos_apps"), urlencode({"sha_256": 64 * "f"}) )) self.assertContains(response, "0 macOS applications")
def add_query_for_user(self, user, query_string, hits): parsed_query = urlparse.parse_qs(urlencode(dict(query_string.items()))) for key, value in parsed_query.items(): parsed_query[key] = ' '.join(value) if 'q' in query_string: # Is a simple query if not query_string['q']: # Don't store empty simple searches return else: # Cleanup query string and only store the q parameter parsed_query = {'q': parsed_query['q']} if parsed_query and not isinstance(user, AnonymousUser): # If the URL query has at least one variable with a value new_recent, created = self.model.objects.get_or_create(user=user, query=urlencode(parsed_query), defaults={'hits': hits}) if not created: new_recent.hits = hits new_recent.save() for recent_to_delete in self.model.objects.filter(user=user)[RECENT_COUNT:]: recent_to_delete.delete()
def test_select_active_organization(self): redirect_url = ( "http://testserver/") url = '%s?%s' % (reverse( 'organizations:select-active', args=(self.organization.slug,)), urlencode({'next': redirect_url})) self.client.logout() self.assertRedirects(self.client.get(url), '%s?next=%s' % ( reverse('login'), urlquote(url))) self.client.login(username=self.user.username, password='******') response = self.client.get(url) self.assertRedirects(response, redirect_url) self.assertEqual( self.client.session.get(ORGANIZATION_SESSION_KEY), self.organization.pk) # check redirect for missing next param and external redirect url = reverse( 'organizations:select-active', args=(self.organization.slug,)) self.assertRedirects(self.client.get(url), reverse('home')) url = '%s?%s' % (reverse( 'organizations:select-active', args=(self.organization.slug,)), urlencode({'next': 'http://google.com'})) self.assertRedirects(self.client.get(url), reverse('home')) self.organization.organizationuserrelation_set.filter( user=self.user).delete() self.assertEqual(self.client.get(url).status_code, 404)
def multi_object_action_view(request): """ Proxy view called first when using a multi object action, which then redirects to the appropiate specialized view """ next = request.POST.get( "next", request.GET.get("next", request.META.get("HTTP_REFERER", reverse(settings.LOGIN_REDIRECT_URL))) ) action = request.GET.get("action", None) id_list = ",".join([key[3:] for key in request.GET.keys() if key.startswith("pk_")]) items_property_list = [(key[11:]) for key in request.GET.keys() if key.startswith("properties_")] if not action: messages.error(request, _("No action selected.")) return HttpResponseRedirect(request.META.get("HTTP_REFERER", reverse(settings.LOGIN_REDIRECT_URL))) if not id_list and not items_property_list: messages.error(request, _("Must select at least one item.")) return HttpResponseRedirect(request.META.get("HTTP_REFERER", reverse(settings.LOGIN_REDIRECT_URL))) # Separate redirects to keep backwards compatibility with older # functions that don't expect a properties_list parameter if items_property_list: return HttpResponseRedirect( "%s?%s" % (action, urlencode({"items_property_list": dumps(items_property_list), "next": next})) ) else: return HttpResponseRedirect("%s?%s" % (action, urlencode({"id_list": id_list, "next": next})))
def _fetch(self, uri, post_args, **url_args): # Use Django's urlencode because it is unicode safe from django.utils.http import urlencode url_args["format"] = "json" args = urlencode(url_args) url = "http://friendfeed.com" + uri + "?" + args headers = {} if post_args is not None: # If we are POSTing then set the method/content-type (urllib2 # does this for you but urlfetch does not) payload = urlencode(post_args) method = urlfetch.POST headers["Content-Type"] = "application/x-www-form-urlencoded" else: payload = None method = urlfetch.GET if self.auth_nickname and self.auth_key: pair = "%s:%s" % (self.auth_nickname, self.auth_key) token = base64.b64encode(pair) headers["Authorization"] = "Basic %s" % token result = urlfetch.fetch(url, payload=payload, method=method, headers=headers) # urllib2 will raise an Exception when you get any error code but # urlfetch does not; raise our own (TODO: make an Exception class) if result.status_code != 200: raise Exception, result.status_code return parse_json(result.content)
def _fetch(self, uri, post_args, **url_args): # Use Django's urlencode because it is unicode safe from django.utils.http import urlencode url_args["format"] = "json" APIKEY = getattr(settings, "APIKEY", None) if APIKEY: url_args["apikey"] = APIKEY args = urlencode(url_args) url = "http://friendfeed.com" + uri + "?" + args headers = {} if post_args is not None: # If we are POSTing then set the method/content-type (urllib2 # does this for you but urlfetch does not) payload = urlencode(post_args) method = urlfetch.POST headers["Content-Type"] = "application/x-www-form-urlencoded" else: payload = None method = urlfetch.GET if self.auth_nickname and self.auth_key: pair = "%s:%s" % (self.auth_nickname, self.auth_key) token = base64.b64encode(pair) headers["Authorization"] = "Basic %s" % token result = urlfetch.fetch(url, payload=payload, method=method, headers=headers) try: data = parse_json(result.content) except Exception, e: data = { "errorCode": str(e), }
def get(self, request, *args, **kwargs): if not request.user.is_authenticated(): configure_uri = u'{}?{}'.format( reverse('vsts-extension-configuration'), urlencode({ 'targetId': request.GET['targetId'], 'targetName': request.GET['targetName'], }), ) redirect_uri = u'{}?{}'.format( reverse('sentry-login'), urlencode({'next': configure_uri}), ) return self.redirect(redirect_uri) if request.user.get_orgs().count() == 1: org = request.user.get_orgs()[0] pipeline = self.init_pipeline( request, org, request.GET['targetId'], request.GET['targetName'], ) return pipeline.current_step() else: return self.redirect(u'/extensions/vsts/link/?{}'.format( urlencode({ 'targetId': request.GET['targetId'], 'targetName': request.GET['targetName'], }) ))
def mail_documents(request): if request.method == 'POST': redirect_to = reverse('mail-success') mail_failed_url = reverse('mail-failed') subject = request.POST.get('subject') message = request.POST.get('message_area') documents_pks = request.POST.get('document_pks') common_pks = request.POST.get('common_pks') if not all([subject, message, documents_pks]): return HttpResponseRedirect( mail_failed_url + '?%s' % urlencode({'error': 'No se llenaron todos los campos'})) documents = Documento.objects.filter(pk__in=documents_pks.split(',')) commons = [] if common_pks: commons = [(common.common_name, common.common_file.file.read()) for common in Comun.objects.filter(pk__in=common_pks.split(','))] for document in documents: document_name = document.document_name recipients = [i.strip() for i in document.consorcista.emails.split('/')] mail = EmailMessage(subject, message, settings.EMAIL_HOST_USER, recipients + [settings.EMAIL_HOST_USER]) mail.attach(filename=document_name, content=document.document_file.file.read()) for common_name, common_content in commons: mail.attach(filename=common_name, content=common_content) try: mail.send() except Exception, e: redirect_to = mail_failed_url + '?%s' % urlencode({'error': e.message}) break return HttpResponseRedirect(redirect_to)
def test_urlencode(self): # 2-tuples (the norm) result = http.urlencode((('a', 1), ('b', 2), ('c', 3))) self.assertEqual(result, 'a=1&b=2&c=3') # A dictionary result = http.urlencode({ 'a': 1, 'b': 2, 'c': 3}) acceptable_results = [ # Need to allow all of these as dictionaries have to be treated as # unordered 'a=1&b=2&c=3', 'a=1&c=3&b=2', 'b=2&a=1&c=3', 'b=2&c=3&a=1', 'c=3&a=1&b=2', 'c=3&b=2&a=1' ] self.assertTrue(result in acceptable_results) # A MultiValueDict result = http.urlencode(MultiValueDict({ 'name': ['Adrian', 'Simon'], 'position': ['Developer'] }), doseq=True) acceptable_results = [ # MultiValueDicts are similarly unordered 'name=Adrian&name=Simon&position=Developer', 'position=Developer&name=Adrian&name=Simon' ] self.assertTrue(result in acceptable_results)
def init(self, request, paypal_request, paypal_response): """Initialize a PayPalNVP instance from a HttpRequest.""" if request: # allow request=None self.ipaddress = request.META.get('REMOTE_ADDR', '').split(':')[0] if hasattr(request, "user") and request.user.is_authenticated(): self.user = request.user if not self.ipaddress: self.ipaddress = '0.0.0.0' # No storing credit card info. query_data = dict( (k,v) for k, v in paypal_request.iteritems() if k not in self.RESTRICTED_FIELDS) self.query = urlencode(query_data) self.response = urlencode(paypal_response) # Was there a flag on the play? ack = paypal_response.get('ACK', False) if ack != "Success": if ack == "SuccessWithWarning": self.flag_info = paypal_response.get('L_LONGMESSAGE0', '') else: self.set_flag( paypal_response.get('L_LONGMESSAGE0', ''), paypal_response.get('L_ERRORCODE', ''))
def on_not_logged_in(self, request, url, error=None): """Called whenever the user is not logged in.""" if request.is_ajax(): logger.debug('Request is Ajax, returning HTTP 403.') return HttpResponseForbidden() try: for lookup_view in settings.LOGIN_REDIRECT["redirect"]: try: if url == reverse(lookup_view): url = parse_url(settings.LOGIN_REDIRECT) except NoReverseMatch: try: resolve(lookup_view) if url == lookup_view: url = parse_url(settings.LOGIN_REDIRECT) except Http404: logger.error('Cannot resolve url %s' % lookup_view) except KeyError: pass except Exception: logger.error( 'Error while redirection on not logged in.', exc_info=True) args = {'url': url} logger.debug( 'Request is not Ajax, redirecting to %s?%s' % (self.login_url, urlencode(args))) return HttpResponseRedirect( '%s?%s' % (self.login_url, urlencode(args)))
def multi_object_action_view(request): """ Proxy view called first when using a multi object action, which then redirects to the appropiate specialized view """ next = request.POST.get('next', request.GET.get('next', request.META.get('HTTP_REFERER', reverse('main:home')))) action = request.GET.get('action', None) id_list = ','.join([key[3:] for key in request.GET.keys() if key.startswith('pk_')]) items_property_list = [loads(key[11:]) for key in request.GET.keys() if key.startswith('properties_')] if not action: messages.error(request, _('No action selected.')) return HttpResponseRedirect(request.META.get('HTTP_REFERER', reverse('main:home'))) if not id_list and not items_property_list: messages.error(request, _('Must select at least one item.')) return HttpResponseRedirect(request.META.get('HTTP_REFERER', reverse('main:home'))) # Separate redirects to keep backwards compatibility with older # functions that don't expect a properties_list parameter if items_property_list: return HttpResponseRedirect('%s?%s' % ( action, urlencode({'items_property_list': dumps(items_property_list), 'next': next})) ) else: return HttpResponseRedirect('%s?%s' % ( action, urlencode({'id_list': id_list, 'next': next})) )
def test_create_accounts(self): # check invalid email address email = "[email protected]@" contact_email = "*****@*****.**" response = self.client.post('/accounts/', urlencode({'account_id' : email,'full_name':'fl','contact_email':contact_email,'password':'******','primary_secret_p':'primaryp','secondary_secret_p':'secondaryp'}),'application/x-www-form-urlencoded') self.assertEquals(response.status_code, 400) # check invalid contact email address email = "*****@*****.**" contact_email = "mybadmail2" response = self.client.post('/accounts/', urlencode({'account_id' : email,'full_name':'fl','contact_email':contact_email,'password':'******','primary_secret_p':'primaryp','secondary_secret_p':'secondaryp'}),'application/x-www-form-urlencoded') self.assertEquals(response.status_code, 400) # valid email and contact addresses # Make sure DEMO_MODE = False works as expected prev_num_accounts = Account.objects.all().count() demo_mode = settings.DEMO_MODE settings.DEMO_MODE = False contact_email = "*****@*****.**" # create an Account, normally: should be no records response = self.client.post('/accounts/', urlencode({'account_id' : email,'full_name':'fl','contact_email':contact_email,'password':'******','primary_secret_p':'primaryp','secondary_secret_p':'secondaryp'}),'application/x-www-form-urlencoded') self.assertEquals(response.status_code, 200) self.assertEqual(Account.objects.all().count(), prev_num_accounts+1) new_acct = Account.objects.get(email=email) self.assertEqual(list(new_acct.records_owned_by.all()), []) settings.DEMO_MODE = demo_mode
def to_link(self, request, instance, urlpattern, kwargs=None, query_kwargs=None): """Return an absolute url for the given urlpattern.""" if query_kwargs: query_kwargs = {k: getattr(instance, v) for k, v in query_kwargs.items()} if not kwargs: url = reverse(urlpattern, request=request) if not query_kwargs: return {'href': url} return {'href': '%s?%s' % (url, urlencode(query_kwargs))} if isinstance(kwargs, basestring): # `(ref, urlpattern, string)` where `string` is equivalent to # `{string: string}` url = reverse(urlpattern, kwargs={kwargs: getattr(instance, kwargs)}, request=request) if not query_kwargs: return {'href': url} return {'href': '%s?%s' % (url, urlencode(query_kwargs))} reverse_kwargs = {} if kwargs: for k, v in kwargs.items(): reverse_kwargs[k] = getattr(instance, v) try: url = reverse(urlpattern, kwargs=reverse_kwargs, request=request) if not query_kwargs: return {'href': url} return {'href': '%s?%s' % (url, urlencode(query_kwargs))} except NoReverseMatch: return None
def make_paypal_url(request, payment): signer = Signer() item_number = signer.sign(unicode(payment.id)) params = {"cmd": "_xclick", "business": settings.ARTSHOW_PAYPAL_ACCOUNT, "undefined_quantity": "0", "item_name": "Art Show Payment from " + payment.artist.artistname(), "item_number": item_number, "amount": unicode(payment.amount), "shipping": "0", "no_shipping": "1", "return": request.build_absolute_uri(reverse("artshow.manage.payment_made_paypal", args=(payment.artist_id,))), "cancel_return": request.build_absolute_uri( reverse("artshow.manage.payment_cancelled_paypal", args=(payment.artist_id,)) + "?" + urlencode({"item_number": item_number})), "currency_code": "USD", "bn": "PP-BuyNow", "charset": "UTF-8", "notify_url": request.build_absolute_uri(reverse(ipn_handler)), } return settings.ARTSHOW_PAYPAL_URL + "?" + urlencode(params)
def connect(self, handler, **query): url = urljoin(API_URL, handler) # removes queries with empty values query = self.filter_querydict(query) is_empty_query = not bool(query) # save for later reference if query: url += "?" for k, v in query.copy().items(): # handle OR-ing of search parameters if "|" in k: del query[k] url += "|".join(urlencode({i: v}) for i in k.split("|")) if query: url += "&" + urlencode(query).replace("%7C", "|") if handler == "activity" and is_empty_query: # Handles caching for the main search page cached_data = cache.get("all-activities") remote_last_updated = unicode(self.html_or_404(urljoin(API_URL, "last_updated/"))) cache_invalid = cache.get("last_updated") != remote_last_updated if cached_data and not cache_invalid: # Cache hit! json = cached_data else: # No cache! Get data and fill cache json = self.json_or_404(url) cache.set("all-activities", json, 60 * 60 * 24) cache.set("last_updated", remote_last_updated) else: json = self.json_or_404(url) return json
def hardcodedopenid(request, domain): parameters = { 'openid.mode': "checkid_setup", 'openid.ns': "http://specs.openid.net/auth/2.0", 'openid.return_to': 'http://%s/login/callback' % request.get_host(), #'openid.return_to': 'http://test.escolarea.com/login/callback', 'openid.claimed_id': 'http://specs.openid.net/auth/2.0/identifier_select', 'openid.identity':'http://specs.openid.net/auth/2.0/identifier_select', 'openid.assoc_handle': CONSUMER_SECRET, 'openid.realm': 'http://%s' % request.get_host(), 'openid.ns.ax': "http://openid.net/srv/ax/1.0", 'openid.ax.mode': "fetch_request", 'openid.ax.required': "firstname,lastname,email", 'openid.ax.type.email': "http://axschema.org/contact/email", 'openid.ax.type.firstname': "http://axschema.org/namePerson/first", 'openid.ax.type.lastname': "http://axschema.org/namePerson/last", 'openid.ns.oauth': 'http://specs.openid.net/extensions/oauth/1.0', 'openid.oauth.consumer': CONSUMER_KEY, 'openid.oauth.scope': ' '.join(OAUTH_SCOPE), } if domain is 'default': url = "https://www.google.com/accounts/o8/ud?%s" % urlencode(parameters) else: url = "https://www.google.com/a/%s/o8/ud?be=o8&%s" % (domain, urlencode(parameters)) print url return redirect(to=url)
def dashboard(request): args = [] # params to pass to l10nstats json query = [] # params to pass to shipping json subtitles = [] if 'ms' in request.GET: mstone = get_object_or_404(Milestone, code=request.GET['ms']) args.append(('tree', mstone.appver.tree.code)) subtitles.append(str(mstone)) query.append(('ms', mstone.code)) elif 'av' in request.GET: appver = get_object_or_404(AppVersion, code=request.GET['av']) args.append(('tree', (appver.tree is not None and appver.tree.code) or appver.lasttree.code)) subtitles.append(str(appver)) query.append(('av', appver.code)) # sanitize the list of locales to those that are actually on the dashboard locales = Locale.objects.filter(code__in=request.GET.getlist('locale')) locales = locales.values_list('code', flat=True) args += [("locale", loc) for loc in locales] query += [("locale", loc) for loc in locales] subtitles += list(locales) return render_to_response('shipping/dashboard.html', { 'subtitles': subtitles, 'query': mark_safe(urlencode(query)), 'args': mark_safe(urlencode(args)), }, context_instance=RequestContext(request))
def test_urlencode(self): # 2-tuples (the norm) result = http.urlencode((("a", 1), ("b", 2), ("c", 3))) self.assertEqual(result, "a=1&b=2&c=3") # A dictionary result = http.urlencode({"a": 1, "b": 2, "c": 3}) acceptable_results = [ # Need to allow all of these as dictionaries have to be treated as # unordered "a=1&b=2&c=3", "a=1&c=3&b=2", "b=2&a=1&c=3", "b=2&c=3&a=1", "c=3&a=1&b=2", "c=3&b=2&a=1", ] self.assertTrue(result in acceptable_results) # A MultiValueDict result = http.urlencode(MultiValueDict({"name": ["Adrian", "Simon"], "position": ["Developer"]}), doseq=True) acceptable_results = [ # MultiValueDicts are similarly unordered "name=Adrian&name=Simon&position=Developer", "position=Developer&name=Adrian&name=Simon", ] self.assertTrue(result in acceptable_results)
def test_permission_resource_detail(self): """Test access permission to resource details (JSON & CSV) """ for i in [ models.VegetationVisit, models.StratumSpecies, models.TransectDistinctChanges, models.BasalBitterlichObservation, models.ErosionPeg, models.PegObservation, models.StratumSummary, models.DisturbanceIndicator, models.PlantObservation, models.BiodiversityIndicator]: self.client.logout() obj = i.objects.all()[0] url = reverse('api_dispatch_detail', kwargs={ 'resource_name': i._meta.object_name.lower(), 'api_name': 'v1', 'pk': obj.pk}) url_json = url + '?' + urlencode({'format': 'json'}) url_csv = url + '?' + urlencode({'format': 'csv'}) response = self.client.get(url_json) # Anonymous user self.assertEqual(response.status_code, 401) # Authorised users for user in ['custodian', 'uploader']: self.client.login(username=user, password='******') response = self.client.get(url_json) self.assertEqual(response.status_code, 200) response = self.client.get(url_csv) self.assertEqual(response.status_code, 200)
def rpx_response(request): ''' Handles the POST response from RPX API. This is where the user is sent after signing in through RPX. @param request: Django request object. @return: Redirect that takes user to 'next' or LOGIN_REDIRECT_URL. ''' #According to http://rpxwiki.com/Passing-state-through-RPX, the query #string parameters in our token url will be POST to our rpx_response so #that we can retain some state information. We use this for 'next', a #var that specifies where the user should be redirected after successful #login. destination = request.POST.get('next', settings.LOGIN_REDIRECT_URL) if request.method == 'POST': #RPX also sends token back via POST. We pass this token to our RPX auth #backend which, then, uses the token to access the RPX API to confirm #that the user logged in successfully and to obtain the user's login #information. token = request.POST.get('token', False) if token: response = auth.authenticate(token = token) #The django_rpx_plus auth backend can return three things: None (means #that auth has failed), a RpxData object (means that user has passed #auth but is not registered), or a User object (means that user is #auth AND registered). if type(response) == User: #Successful auth and user is registered so we login user. auth.login(request, response) return redirect(destination) elif type(response) == RpxData: #Successful auth, but user is NOT registered! So we redirect #user to the register page. However, in order to tell the #register view that the user is authed but not registered, #we set a session var that points to the RpxData object #primary ID. After the user has been registered, this session #var will be removed. request.session[RPX_ID_SESSION_KEY] = response.id #For security purposes, there could be a case where user #decides not to register but then never logs out either. #Another person can come along and then use the REGISTER_URL #to continue creating the account. So we expire this session #after a set time interval. (Note that this session expiry #setting will be cleared when user completes registration.) request.session.set_expiry(60 * 10) #10 min query_params = urlencode({'next': destination}) return redirect(settings.REGISTER_URL+'?'+query_params) else: #Do nothing, auth has failed. pass #Authentication has failed. We'll send user back to login page where error #message is displayed. messages.error(request, 'There was an error in signing you in. Try again?') query_params = urlencode({'next': destination}) return redirect(reverse('auth_login')+'?'+query_params)
def test_limit_offset_filter(self): filter_url = self.url + '?' + urlencode({'map': self.obj.map.id, 'limit': 1, 'offset': 0}) response = self.client.get(filter_url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertIn(self.data, response.data['results']) filter_url = self.url + '?' + urlencode({'map': self.obj.map.id, 'limit': 1, 'offset': 1}) response = self.client.get(filter_url) self.assertNotIn(self.data, response.data['results'])
def test_url(self): eq_(self.s.deserialize(urlencode({'foo': 'bar'}), 'application/x-www-form-urlencoded'), {'foo': 'bar'}) eq_(self.s.deserialize(urlencode({'foo': u'baré'}), 'application/x-www-form-urlencoded'), {'foo': u'baré'})
def passthrough_next_redirect_url(request, url, redirect_field_name): next_url = get_next_redirect_url(request, redirect_field_name) if next_url: if url.find("?") == -1: url = url + "?" + urlencode({redirect_field_name: next_url}) else: url = url + "&" + urlencode({redirect_field_name: next_url}) return url
def metadata_add(request, document_id=None, document_id_list=None): check_permissions(request.user, [PERMISSION_METADATA_DOCUMENT_ADD]) if document_id: documents = [get_object_or_404(Document, pk=document_id)] elif document_id_list: documents = [get_object_or_404(Document, pk=document_id) for document_id in document_id_list.split(',')] else: messages.error(request, _(u'Must provide at least one document.')) return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) for document in documents: RecentDocument.objects.add_document_for_user(request.user, document) post_action_redirect = reverse('document_list_recent') next = request.POST.get('next', request.GET.get('next', request.META.get('HTTP_REFERER', post_action_redirect))) if request.method == 'POST': form = AddMetadataForm(request.POST) if form.is_valid(): metadata_type = form.cleaned_data['metadata_type'] for document in documents: document_metadata, created = DocumentMetadata.objects.get_or_create(document=document, metadata_type=metadata_type, defaults={'value': u''}) if created: messages.success(request, _(u'Metadata type: %(metadata_type)s successfully added to document %(document)s.') % { 'metadata_type': metadata_type, 'document': document}) else: messages.warning(request, _(u'Metadata type: %(metadata_type)s already present in document %(document)s.') % { 'metadata_type': metadata_type, 'document': document}) if len(documents) == 1: return HttpResponseRedirect(u'%s?%s' % ( reverse(metadata_edit, args=[document.pk]), urlencode({'next': next})) ) elif len(documents) > 1: return HttpResponseRedirect(u'%s?%s' % ( reverse('metadata_multiple_edit'), urlencode({'id_list': document_id_list, 'next': next})) ) else: form = AddMetadataForm() context = { #'form_display_mode_table': True, 'form': form, 'next': next, } if len(documents) == 1: context['object'] = documents[0] context['title'] = _(u'Add metadata type to document: %s') % ', '.join([unicode(d) for d in documents]) elif len(documents) > 1: context['title'] = _(u'Add metadata type to documents: %s') % ', '.join([unicode(d) for d in documents]) return render_to_response('generic_form.html', context, context_instance=RequestContext(request))
def get_chart_url(self, name, v): return self.model_admin_url('chart', name) + "?" + urlencode( self.list_params)
def _build_url(self, *args, **kwargs): get = kwargs.pop("get", {}) url = reverse(*args, **kwargs) if get: url += "?" + urlencode(get) return url
def get_aid_url(url, aid_code): return '?'.join([url, urlencode({app_settings.PARAM_NAME: aid_code})])
def replace(text, max_width=MAX_WIDTH, max_height=MAX_HEIGHT): """ Scans a block of text, replacing anything matched by a ``ProviderRule`` pattern with an OEmbed html snippet, if possible. Templates should be stored at oembed/{format}.html, so for example: oembed/video.html These templates are passed a context variable, ``response``, which is a dictionary representation of the response. """ rules = list(ProviderRule.objects.all()) patterns = [re.compile(r'[\'"=]?' + r.regex) for r in rules] # Compiled patterns from the rules parts = [] # The parts that we will assemble into the final return value. indices = [ ] # List of indices of parts that need to be replaced with OEmbed stuff. indices_rules = [ ] # List of indices into the rules in order for which index was gotten by. urls = set() # A set of URLs to try to lookup from the database. stored = {} # A mapping of URLs to StoredOEmbed objects. index = 0 # First we pass through the text, populating our data structures. for i, part in re_parts(patterns, text): # if it starts with a quote or equals sign we're going to assume it's # inside an html tag attribute which means it doesn't need to get # re-embedded if i == -1 or part[0] in ('"', "'", "="): parts.append(part) index += 1 else: to_append = "" # If the link ends with one of our overrides, build a list while part[-1] in END_OVERRIDES: to_append += part[-1] part = part[:-1] indices.append(index) urls.add(part) indices_rules.append(i) parts.append(part) index += 1 if to_append: parts.append(to_append) index += 1 # Now we fetch a list of all stored patterns, and put it in a dictionary # mapping the URL to to the stored model instance. for stored_embed in StoredOEmbed.objects.filter(match__in=urls, max_width=max_width, max_height=max_height): stored[stored_embed.match] = stored_embed # Now we're going to do the actual replacement of URL to embed. for i, id_to_replace in enumerate(indices): rule = rules[indices_rules[i]] part = parts[id_to_replace] try: # Try to grab the stored model instance from our dictionary, and # use the stored HTML fragment as a replacement. parts[id_to_replace] = stored[part].html except KeyError: try: # Build the URL based on the properties defined in the OEmbed spec. sep = "?" in rule.endpoint and "&" or "?" q = urlencode({ "url": part, "maxwidth": max_width, "maxheight": max_height, "format": FORMAT }) url = u"%s%s%s" % (rule.endpoint, sep, q) # Fetch the link and parse the JSON. resp = simplejson.loads(fetch(url)) # Depending on the embed type, grab the associated template and # pass it the parsed JSON response as context. replacement = render_to_string('oembed/%s.html' % resp['type'], {'response': resp}) if replacement: stored_embed = StoredOEmbed.objects.create( match=part, max_width=max_width, max_height=max_height, html=replacement, ) stored[stored_embed.match] = stored_embed parts[id_to_replace] = replacement else: raise ValueError except ValueError: parts[id_to_replace] = part except KeyError: parts[id_to_replace] = part except urllib2.HTTPError: parts[id_to_replace] = part # Combine the list into one string and return it. return mark_safe(u''.join(parts))
def _get_editable_context(self, context, instance, language, edit_fields, view_method, view_url, querystring, editmode=True): """ Populate the contex with the requested attributes to trigger the changeform """ request = context['request'] if hasattr(request, 'toolbar'): lang = request.toolbar.toolbar_language else: lang = get_language() with force_language(lang): extra_context = {} if edit_fields == 'changelist': instance.get_plugin_name = u"%s %s list" % (smart_text( _('Edit')), smart_text(instance._meta.verbose_name)) extra_context['attribute_name'] = 'changelist' elif editmode: instance.get_plugin_name = u"%s %s" % (smart_text( _('Edit')), smart_text(instance._meta.verbose_name)) if not context.get('attribute_name', None): # Make sure CMS.Plugin object will not clash in the frontend. extra_context['attribute_name'] = '-'.join(edit_fields) \ if not isinstance('edit_fields', six.string_types) else edit_fields else: instance.get_plugin_name = u"%s %s" % (smart_text( _('Add')), smart_text(instance._meta.verbose_name)) extra_context['attribute_name'] = 'add' extra_context['instance'] = instance extra_context['generic'] = instance._meta # view_method has the precedence and we retrieve the corresponding # attribute in the instance class. # If view_method refers to a method it will be called passing the # request; if it's an attribute, it's stored for later use if view_method: method = getattr(instance, view_method) if callable(method): url_base = method(context['request']) else: url_base = method else: # The default view_url is the default admin changeform for the # current instance if not editmode: view_url = 'admin:%s_%s_add' % (instance._meta.app_label, instance._meta.module_name) url_base = reverse(view_url) elif not edit_fields: if not view_url: view_url = 'admin:%s_%s_change' % ( instance._meta.app_label, instance._meta.module_name) if isinstance(instance, Page): url_base = reverse(view_url, args=(instance.pk, language)) else: url_base = reverse(view_url, args=(instance.pk, )) else: if not view_url: view_url = 'admin:%s_%s_edit_field' % ( instance._meta.app_label, instance._meta.module_name) if view_url.endswith('_changelist'): url_base = reverse(view_url) else: url_base = reverse(view_url, args=(instance.pk, language)) querystring['edit_fields'] = ",".join( context['edit_fields']) if editmode: extra_context['edit_url'] = "%s?%s" % (url_base, urlencode(querystring)) else: extra_context['edit_url'] = "%s" % url_base extra_context['refresh_page'] = True # We may be outside the CMS (e.g.: an application which is not attached via Apphook) # in this case we may only go back to the home page if getattr(context['request'], 'current_page', None): extra_context['redirect_on_close'] = context[ 'request'].current_page.get_absolute_url(language) else: extra_context['redirect_on_close'] = '' return extra_context
def get_link_url(self, datum): base_url = reverse(self.url) params = urlencode({"snapshot_id": self.table.get_object_id(datum)}) return "?".join([base_url, params])
def test_environ(self): f = self.urlopen('/environ_view/?%s' % urlencode({'q': 'тест'})) self.assertIn(b"QUERY_STRING: 'q=%D1%82%D0%B5%D1%81%D1%82'", f.read())
def replace_query_params(self, url, params): (scheme, netloc, path, query, fragment) = urlparse.urlsplit(url) query_dict = QueryDict(query).dict() query_dict.update(params) query = urlencode(query_dict) return urlparse.urlunsplit((scheme, netloc, path, query, fragment))
def make_twitter_url(page_url, message): url = "https://twitter.com/share/?%s" url_param = urlencode({'text': message, 'url': page_url}) return url % url_param
def get_link_url(self, domain): step = 'update_group_members' base_url = reverse(self.url, args=[domain.id]) param = urlencode({"step": step}) return "?".join([base_url, param])
def show_dictionary(request, project, lang): prj = get_project(request, project) lang = get_object_or_404(Language, code=lang) if request.method == 'POST' and request.user.has_perm('glossary.add', prj): form = WordForm(request.POST) if form.is_valid(): Dictionary.objects.create(request.user, project=prj, language=lang, source=form.cleaned_data['source'], target=form.cleaned_data['target']) return redirect_next(request.POST.get('next'), request.get_full_path()) form = WordForm() uploadform = DictUploadForm() words = Dictionary.objects.filter(project=prj, language=lang).order_by(Lower('source')) letterform = LetterForm(request.GET) searchform = OneWordForm(request.GET) if searchform.is_valid() and searchform.cleaned_data['term'] != '': words = words.filter(source__icontains=searchform.cleaned_data['term']) search = searchform.cleaned_data['term'] else: search = '' if letterform.is_valid() and letterform.cleaned_data['letter'] != '': words = words.filter( source__istartswith=letterform.cleaned_data['letter']) letter = letterform.cleaned_data['letter'] else: letter = '' words = get_paginator(request, words) last_changes = Change.objects.last_changes(request.user).filter( dictionary__project=prj, dictionary__language=lang)[:10] return render( request, 'dictionary.html', { 'title': dict_title(prj, lang), 'project': prj, 'language': lang, 'page_obj': words, 'form': form, 'query_string': urlencode({ 'term': search, 'letter': letter }), 'uploadform': uploadform, 'letterform': letterform, 'searchform': searchform, 'letter': letter, 'last_changes': last_changes, 'last_changes_url': urlencode({ 'project': prj.slug, 'lang': lang.code, 'glossary': 1 }), })
def make_facebook_url(page_url, msg): title = u'%s: %s' % (msg, page_url) url = "https://www.facebook.com/sharer.php?%s" url_param = urlencode({'u': page_url, 't': title}) return url % url_param
def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(object_list=object_list, **kwargs) context['form'] = self.form if self.search_value: context['query'] = urlencode({'search': self.search_value}) return context
def get_context_data(self, **kwargs): """Create context for rendering page.""" context = super().get_context_data(**kwargs) context["project"] = self.project url = {} if self.translation is not None: context["project"] = self.translation.component.project context["component"] = self.translation.component context["translation"] = self.translation url["lang"] = self.translation.language.code url["component"] = self.translation.component.slug url["project"] = self.translation.component.project.slug context["changes_rss"] = reverse("rss-translation", kwargs=url) context["title"] = ( pgettext("Changes in translation", "Changes in %s") % self.translation) elif self.component is not None: context["project"] = self.component.project context["component"] = self.component url["component"] = self.component.slug url["project"] = self.component.project.slug context["changes_rss"] = reverse("rss-component", kwargs=url) context["title"] = ( pgettext("Changes in component", "Changes in %s") % self.component) elif self.project is not None: context["project"] = self.project url["project"] = self.project.slug context["changes_rss"] = reverse("rss-project", kwargs=url) context["title"] = ( pgettext("Changes in project", "Changes in %s") % self.project) if self.language is not None: context["language"] = self.language url["lang"] = self.language.code if "changes_rss" not in context: context["changes_rss"] = reverse("rss-language", kwargs=url) if "title" not in context: context["title"] = ( pgettext("Changes in language", "Changes in %s") % self.language) if self.user is not None: context["changes_user"] = self.user url["user"] = self.user.username if "title" not in context: context["title"] = ( pgettext("Changes by user", "Changes by %s") % self.user.full_name) url = list(url.items()) for action in self.actions: url.append(("action", action)) if self.start_date: url.append(("start_date", self.start_date.date())) if self.end_date: url.append(("end_date", self.end_date.date())) if not url: context["changes_rss"] = reverse("rss") context["query_string"] = urlencode(url) context["form"] = ChangesForm(self.request, data=self.request.GET) context["search_items"] = url return context
def add_context(self): return dict( page=urlencode(self.request.GET.items()) )
def __call__(self, request, context=None): self.request = request self.form = self.build_form() if 'search_object' in request.GET: if request.GET['search_object'] != "all": self.form.selected_facets = [u'facet_model_name_exact:%s' % \ request.GET['search_object']] self.query = self.get_query().strip('\\') #TODO List of fields should be gathered # automatically from our SearchIndex classes fields = ['content', 'name', 'title'] sq, not_sq = parse_query_into_sq(self.query, fields) if sq: self.form.searchqueryset = self.form.searchqueryset.filter(sq) if not_sq: self.form.searchqueryset = self.form.searchqueryset.exclude(not_sq) self.results = self.get_results() if 'sort' in request.GET: self.sort = request.GET['sort'] else: self.sort = '' if self.sort == 'country': self.results = self.results.order_by('country', '-_score') elif self.sort == 'year': self.results = self.results.order_by('year', '-_score') elif len(self.form.selected_facets) == 1: if self.sort: if self.form.selected_facets[0] in \ [u'facet_model_name_exact:publisher', u'facet_model_name_exact:indicia publisher', u'facet_model_name_exact:brand group', u'facet_model_name_exact:brand emblem', u'facet_model_name_exact:series']: if request.GET['sort'] == 'alpha': self.results = self.results.order_by( 'sort_name', 'year') elif request.GET['sort'] == 'chrono': self.results = self.results.order_by( 'year', 'sort_name') elif u'facet_model_name_exact:issue' in self.form.selected_facets: if request.GET['sort'] == 'alpha': self.results = self.results.order_by( 'sort_name', 'key_date', 'sort_code') elif request.GET['sort'] == 'chrono': self.results = self.results.order_by( 'key_date', 'sort_name', 'sort_code') elif u'facet_model_name_exact:story' in self.form.selected_facets: if request.GET['sort'] == 'alpha': self.results = self.results.order_by( 'sort_name', 'key_date', 'sort_code', 'sequence_number') elif request.GET['sort'] == 'chrono': self.results = self.results.order_by( 'key_date', 'sort_name', 'sort_code', 'sequence_number') if self.query: self.query = urlencode({'q': self.query.encode('utf-8')}) self.paginator = ResponsePaginator(self.results, view=self.create_response, vars=context) return self.paginator.paginate(request)
if not style in ('drag', 'button'): raise TemplateSyntaxError('style argument must be set to \'drag\' or \'button\'') container_id = 'bambu_fileupload_%s' % ''.join(random.sample(string.digits + string.letters, 6)) script = """\n<script>\n//<![CDATA[\njQuery(document).ready( function($) { bambu.fileupload.init('%s','%s?%s', %s%s); %s } );\n//]]>\n</script>\n""" % ( container_id, reverse('fileupload'), urlencode( { 'handler': handler, 'params': urlencode(kwargs) } ), callback_js, deletable and ", '%s?%s'" % ( reverse('fileupload_delete'), urlencode( { 'handler': handler, 'params': urlencode(kwargs) } ) ) or '', listable and ( 'bambu.fileupload.list(\'%s\', \'%s?%s\');' % (container_id, reverse('fileupload_list'),
def run(cls, database=DEFAULT_DB_ALIAS, **kwargs): import frepple # Uncomment the following lines to bypass the connection to odoo and use # a XML flat file alternative. This can be useful for debugging. #with open("my_path/my_data_file.xml", 'rb') as f: # frepple.readXMLdata(f.read().decode('utf-8'), False, False) # frepple.printsize() # return odoo_user = Parameter.getValue("odoo.user", database) if settings.ODOO_PASSWORDS.get(database) == '': odoo_password = Parameter.getValue("odoo.password", database) else: odoo_password = settings.ODOO_PASSWORDS.get(database) odoo_db = Parameter.getValue("odoo.db", database) odoo_url = Parameter.getValue("odoo.url", database) odoo_company = Parameter.getValue("odoo.company", database) ok = True if not odoo_user: logger.error("Missing or invalid parameter odoo.user") ok = False if not odoo_password: logger.error("Missing or invalid parameter odoo.password") ok = False if not odoo_db: logger.error("Missing or invalid parameter odoo.db") ok = False if not odoo_url: logger.error("Missing or invalid parameter odoo.url") ok = False if not odoo_company: logger.error("Missing or invalid parameter odoo.company") ok = False odoo_language = Parameter.getValue("odoo.language", database, 'en_US') if not ok: raise Exception("Odoo connector not configured correctly") # Connect to the odoo URL to GET data url = "%sfrepple/xml?%s" % (odoo_url, urlencode({ 'database': odoo_db, 'language': odoo_language, 'company': odoo_company, 'mode': cls.mode })) try: request = Request(url) encoded = base64.encodestring( ('%s:%s' % (odoo_user, odoo_password)).encode('utf-8'))[:-1] request.add_header("Authorization", "Basic %s" % encoded.decode('ascii')) except HTTPError as e: logger.error("Error connecting to odoo at %s: %s" % (url, e)) raise e # Download and parse XML data with urlopen(request) as f: frepple.readXMLdata(f.read().decode('utf-8'), False, False) frepple.printsize()
def get_link_url(self, project): step = 'update_quotas' base_url = reverse(self.url, args=[project.id]) param = urlencode({"step": step}) return "?".join([base_url, param])
def browse(request, parent_page_id=None): # A missing or empty page_type parameter indicates 'all page types' # (i.e. descendants of wagtailcore.page) page_type_string = request.GET.get("page_type") or "wagtailcore.page" user_perm = request.GET.get("user_perms", False) try: desired_classes = page_models_from_string(page_type_string) except (ValueError, LookupError): raise Http404 # Find parent page if parent_page_id: parent_page = get_object_or_404(Page, id=parent_page_id) elif desired_classes == (Page, ): # Just use the root page parent_page = Page.get_first_root_node() else: # Find the highest common ancestor for the specific classes passed in # In many cases, such as selecting an EventPage under an EventIndex, # this will help the administrator find their page quicker. all_desired_pages = Page.objects.all().type(*desired_classes) parent_page = all_desired_pages.first_common_ancestor() parent_page = parent_page.specific # Get children of parent page (without streamfields) pages = parent_page.get_children().defer_streamfields().specific() # allow hooks to modify the queryset for hook in hooks.get_hooks("construct_page_chooser_queryset"): pages = hook(pages, request) # Filter them by page type if desired_classes != (Page, ): # restrict the page listing to just those pages that: # - are of the given content type (taking into account class inheritance) # - or can be navigated into (i.e. have children) choosable_pages = pages.type(*desired_classes) descendable_pages = pages.filter(numchild__gt=0) pages = choosable_pages | descendable_pages can_choose_root = request.GET.get("can_choose_root", False) target_pages = Page.objects.filter(pk__in=[ int(pk) for pk in request.GET.get("target_pages", "").split(",") if pk ]) match_subclass = request.GET.get("match_subclass", True) # Do permission lookups for this user now, instead of for every page. permission_proxy = UserPagePermissionsProxy(request.user) # Parent page can be chosen if it is a instance of desired_classes parent_page.can_choose = can_choose_page( parent_page, permission_proxy, desired_classes, can_choose_root, user_perm, target_pages=target_pages, match_subclass=match_subclass, ) selected_locale = None locale_options = [] show_locale_labels = getattr(settings, "WAGTAIL_I18N_ENABLED", False) if show_locale_labels: pages = pages.select_related("locale") if parent_page_id is None: # 'locale' is the current value of the "Locale" selector in the UI if request.GET.get("locale"): selected_locale = get_object_or_404( Locale, language_code=request.GET["locale"]) active_locale_id = selected_locale.pk else: active_locale_id = Locale.get_active().pk # we are at the Root level, so get the locales from the current pages choose_url = reverse("wagtailadmin_choose_page") locale_options = [{ "locale": locale, "url": choose_url + "?" + urlencode({ "page_type": page_type_string, "locale": locale.language_code }), } for locale in Locale.objects.filter( pk__in=pages.values_list("locale_id")).exclude( pk=active_locale_id)] else: # We have a parent page (that is not the root page). Use its locale as the selected localer selected_locale = parent_page.locale # and get the locales based on its available translations locales_and_parent_pages = { item["locale"]: item["pk"] for item in Page.objects.translation_of(parent_page).values( "locale", "pk") } locales_and_parent_pages[selected_locale.pk] = parent_page.pk for locale in Locale.objects.filter( pk__in=list(locales_and_parent_pages.keys())).exclude( pk=selected_locale.pk): choose_child_url = reverse( "wagtailadmin_choose_page_child", args=[locales_and_parent_pages[locale.pk]], ) locale_options.append({ "locale": locale, "url": choose_child_url + "?" + urlencode({"page_type": page_type_string}), }) # finally, filter the browseable pages on the selected locale if selected_locale: pages = pages.filter(locale=selected_locale) # Pagination # We apply pagination first so we don't need to walk the entire list # in the block below paginator = Paginator(pages, per_page=25) pages = paginator.get_page(request.GET.get("p")) # Annotate each page with can_choose/can_decend flags for page in pages: page.can_choose = can_choose_page( page, permission_proxy, desired_classes, can_choose_root, user_perm, target_pages=target_pages, match_subclass=match_subclass, ) page.can_descend = page.get_children_count() # Render context = shared_context( request, { "parent_page": parent_page, "parent_page_id": parent_page.pk, "pages": pages, "search_form": SearchForm(), "page_type_string": page_type_string, "page_type_names": [ desired_class.get_verbose_name() for desired_class in desired_classes ], "page_types_restricted": (page_type_string != "wagtailcore.page"), "show_locale_labels": show_locale_labels, "locale_options": locale_options, "selected_locale": selected_locale, }, ) return render_modal_workflow( request, "wagtailadmin/chooser/browse.html", None, context, json_data={ "step": "browse", "parent_page_id": context["parent_page_id"] }, )
def urlReplace(context, **kwargs): query = context['request'].GET.dict() query.update(kwargs) return urlencode(query)
def ask_query_string(self): # TODO: test me """returns string to prepopulate title field on the "Add your exercise" page""" ask_title = self.stripped_query or self.query or '' if not ask_title: return '' return '?' + urlencode({'title': ask_title})
def query(self, **params): url = '%s?%s' % (self.list_endpoint, urlencode(params, doseq=True)) return self._assert_auth_get_resource(url)
def passthrough_next_redirect_url(request, url, redirect_field_name): assert url.find("?") < 0 # TODO: Handle this case properly next_url = get_next_redirect_url(request, redirect_field_name) if next_url: url = url + '?' + urlencode({redirect_field_name: next_url}) return url
def test_forward(self): """测试转发回复""" scheme = "http" netloc = "example.com" path = "/debug" url = "{scheme}://{netloc}{path}".format(scheme=scheme, netloc=netloc, path=path) token = self.app.token timestamp = str(int(time.time())) nonce = "123456" query_data = dict(timestamp=timestamp, nonce=nonce) signer = WeChatSigner() signer.add_data(token, timestamp, nonce) signature = signer.signature query_data["signature"] = signature sender = "openid" content = "xyz" xml = """<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[{sender}]]></FromUserName> <CreateTime>1348831860</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[{content}]]></Content> <MsgId>1234567890123456</MsgId> </xml>""".format(sender=sender, content=content) req_url = url + "?" + urlencode(query_data) request = RequestFactory().post(req_url, xml, content_type="text/xml") patch_request(request, self.app.name, WeChatMessageInfo) message = request.wechat reply_text = "abc" def reply_test(url, request): self.assertEqual(url.scheme, scheme) self.assertEqual(url.netloc, netloc) self.assertEqual(url.path, path) query = dict(parse_qsl(url.query)) self.assertEqual(query["timestamp"], timestamp) self.assertEqual(query["nonce"], nonce) self.assertEqual(query["signature"], signature) check_signature(self.app.token, query["signature"], timestamp, nonce) msg = parse_message(request.body) self.assertIsInstance(msg, messages.TextMessage) self.assertEqual(msg.source, sender) self.assertEqual(msg.content, content) reply = replies.create_reply(reply_text, msg) return response(content=reply.render()) handler = self._create_handler( replies=dict(type=Reply.MsgType.FORWARD, url=url)) with common_interceptor(reply_test): reply = handler.reply(message) self.assertIsInstance(reply, replies.TextReply) self.assertEqual(reply.content, reply_text) self.assertEqual(reply.target, sender) def bad_reply(url, request): return response(404) with common_interceptor(bad_reply): self.assertRaises(HTTPError, lambda: handler.reply(message))
def get_link_url(self, datum): base_url = reverse(self.url) vol_id = "%s:vol" % self.table.get_object_id(datum) params = urlencode({"source_type": "volume_id", "source_id": vol_id}) return "?".join([base_url, params])
def test_get_form_passing_auth_url_transport(self): """Ensure GETing form over OAuth with correct client credentials in query succeed when DEBUG is True""" query = urlencode({'access_token': self.access_token.token}) response = self.csrf_client.get('/oauth2-test-debug/?%s' % query) self.assertEqual(response.status_code, 200)
def translate(request, project, component, lang): """Generic entry point for translating, suggesting and searching.""" obj, project, unit_set = parse_params(request, project, component, lang) # Search results search_result = search(obj, unit_set, request, PositionSearchForm) # Handle redirects if isinstance(search_result, HttpResponse): return search_result # Get numer of results num_results = len(search_result["ids"]) # Search offset offset = search_result["offset"] # Checksum unit access checksum_form = ChecksumForm(unit_set, request.GET or request.POST) if checksum_form.is_valid(): unit = checksum_form.cleaned_data["unit"] try: offset = search_result["ids"].index(unit.id) + 1 except ValueError: messages.warning(request, _("No string matched your search!")) return redirect(obj) else: # Check boundaries if not 0 < offset <= num_results: messages.info(request, _("The translation has come to an end.")) # Delete search del request.session[search_result["key"]] return redirect(obj) # Grab actual unit try: unit = unit_set.get(pk=search_result["ids"][offset - 1]) except Unit.DoesNotExist: # Can happen when using SID for other translation messages.error(request, _("Invalid search string!")) return redirect(obj) # Check locks locked = unit.translation.component.locked # Some URLs we will most likely use base_unit_url = "{0}?{1}&offset=".format(obj.get_translate_url(), search_result["url"]) this_unit_url = base_unit_url + str(offset) next_unit_url = base_unit_url + str(offset + 1) response = None # Any form submitted? if "skip" in request.POST: return redirect(next_unit_url) if request.method == "POST": if (not locked and "accept" not in request.POST and "accept_edit" not in request.POST and "delete" not in request.POST and "spam" not in request.POST and "upvote" not in request.POST and "downvote" not in request.POST): # Handle translation response = handle_translate(request, unit, this_unit_url, next_unit_url) elif not locked or "delete" in request.POST or "spam" in request.POST: # Handle accepting/deleting suggestions response = handle_suggestions(request, unit, this_unit_url, next_unit_url) # Handle translation merging elif "merge" in request.GET and not locked: response = handle_merge(unit, request, next_unit_url) # Handle reverting elif "revert" in request.GET and not locked: response = handle_revert(unit, request, this_unit_url) # Pass possible redirect further if response is not None: return response # Show secondary languages for signed in users if request.user.is_authenticated: secondary = unit.get_secondary_units(request.user) else: secondary = None # Spam protection antispam = AntispamForm() # Prepare form form = TranslationForm(request.user, unit) sort = get_sort_name(request) return render( request, "translate.html", { "this_unit_url": this_unit_url, "first_unit_url": base_unit_url + "1", "last_unit_url": base_unit_url + str(num_results), "next_unit_url": next_unit_url, "prev_unit_url": base_unit_url + str(offset - 1), "object": obj, "project": project, "unit": unit, "nearby": unit.nearby(request.user.profile.nearby_strings), "nearby_keys": unit.nearby_keys(request.user.profile.nearby_strings), "others": get_other_units(unit), "search_url": search_result["url"], "search_items": search_result["items"], "search_query": search_result["query"], "offset": offset, "sort_name": sort["name"], "sort_query": sort["query"], "filter_name": search_result["name"], "filter_count": num_results, "filter_pos": offset, "form": form, "antispam": antispam, "comment_form": CommentForm( project, initial={ "scope": "global" if unit.translation.is_source else "translation" }, ), "context_form": ContextForm(instance=unit.source_info, user=request.user), "search_form": search_result["form"].reset_offset(), "secondary": secondary, "locked": locked, "glossary": Term.objects.get_terms(unit), "addterm_form": TermForm(project), "last_changes": unit.change_set.prefetch().order()[:10], "last_changes_url": urlencode(unit.translation.get_reverse_url_kwargs()), "display_checks": list(get_display_checks(unit)), "machinery_services": json.dumps(list(MACHINE_TRANSLATION_SERVICES.keys())), }, )
def encode_optional(params): if params: return '?{0}'.format(urlencode(params)) else: return ''
def test_get_form_failing_auth_url_transport(self): """Ensure GETing form over OAuth with correct client credentials in query fails when DEBUG is False""" query = urlencode({'access_token': self.access_token.token}) response = self.csrf_client.get('/oauth2-test/?%s' % query) self.assertIn(response.status_code, (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN))