def get_links(self, request): edit_link = URL(request.link(self.submission)) edit_link = edit_link.query_param("edit", "") edit_link = edit_link.query_param("return-to", request.url) return [Link(text=_("Edit submission"), url=edit_link.as_string(), classes=("edit-link",))]
def test_stripe_prepare_oauth_request(): stripe = StripeConnect() stripe.oauth_gateway = 'https://oauth.example.org' stripe.oauth_gateway_auth = 'gateway_auth' stripe.oauth_gateway_secret = 'gateway_secret' stripe.client_id = 'client_id' stripe.client_secret = 'client_secret' with requests_mock.Mocker() as m: m.post('https://oauth.example.org/register/gateway_auth', json={ 'token': '0xdeadbeef' }) url = stripe.prepare_oauth_request( redirect_uri='https://endpoint', success_url='https://success', error_url='https://error' ) assert quote('https://oauth.example.org/redirect', safe='') in url url = URL(url) assert url.query_param('state') == '0xdeadbeef' assert url.query_param('scope') == 'read_write' assert url.query_param('client_id') == 'client_id'
def get_links(self, request): if not self.event: return [] links = [] if self.event.state == "submitted": link = URL(request.link(self.event, "publish")) link = link.query_param("return-to", request.link(self.ticket)) links.append(Link(text=_("Accept event"), url=link.as_string(), classes=("accept-link",))) links.append( DeleteLink( text=_("Reject event"), url=request.link(self.event), confirm=_("Do you really want to reject this event?"), extra_information=_("Rejecting this event can't be undone."), yes_button_text=_("Reject event"), redirect_after=request.link(self.ticket), ) ) link = URL(request.link(self.event, "bearbeiten")) link = link.query_param("return-to", request.url) links.append(Link(text=_("Edit event"), url=link.as_string(), classes=("edit-link",))) return links
def get_submission_link(request, submission, confirm_link): url = URL(request.link(submission)) url = url.query_param('return-to', confirm_link) url = url.query_param('title', request.translate( _("Details about the reservation")) ) url = url.query_param('edit', 1) url = url.query_param('quiet', 1) return url.as_string()
class UnicodeTests(TestCase): def setUp(self): self.base = URL('http://127.0.0.1/') self.text = u'ć' self.bytes = self.text.encode('utf8') def test_set_unicode_query_param_value(self): url = self.base.query_param('q', self.text) self.assertEqual(self.text, url.query_param('q')) def test_set_bytestring_query_param_value(self): url = self.base.query_param('q', self.bytes) self.assertEqual(self.text, url.query_param('q')) def test_set_unicode_query_param_key(self): url = self.base.query_param(self.text, 'value') self.assertEqual('value', url.query_param(self.text)) def test_set_bytestring_query_param_key(self): url = self.base.query_param(self.bytes, 'value') self.assertEqual('value', url.query_param(self.text)) def test_append_unicode_query_param(self): url = self.base.append_query_param('q', self.text) self.assertEqual(self.text, url.query_param('q')) def test_append_bytestring_query_param(self): url = self.base.append_query_param('q', self.bytes) self.assertEqual(self.text, url.query_param('q')) def test_set_unicode_query_params(self): url = self.base.query_params({'q': self.text}) self.assertEqual(self.text, url.query_param('q')) def test_set_bytestring_query_params(self): url = self.base.query_params({'q': self.bytes}) self.assertEqual(self.text, url.query_param('q')) def test_add_unicode_path_segment(self): url = self.base.add_path_segment(self.text) self.assertEqual(self.text, url.path_segment(0)) def test_add_bytestring_path_segment(self): url = self.base.add_path_segment(self.bytes) self.assertEqual(self.text, url.path_segment(0)) def test_add_bytestring_path_segment(self): url = self.base.add_path_segment(self.bytes) self.assertEqual(self.text, url.path_segment(0)) def test_add_unicode_fragment(self): url = self.base.fragment(self.text) self.assertEqual(self.text, url.fragment())
class UnicodeTests(TestCase): def setUp(self): self.base = URL("http://127.0.0.1/") self.text = u"ć" self.bytes = self.text.encode("utf8") def test_set_unicode_query_param_value(self): url = self.base.query_param("q", self.text) self.assertEqual(self.text, url.query_param("q")) def test_set_bytestring_query_param_value(self): url = self.base.query_param("q", self.bytes) self.assertEqual(self.text, url.query_param("q")) def test_set_unicode_query_param_key(self): url = self.base.query_param(self.text, "value") self.assertEqual("value", url.query_param(self.text)) def test_set_bytestring_query_param_key(self): url = self.base.query_param(self.bytes, "value") self.assertEqual("value", url.query_param(self.text)) def test_append_unicode_query_param(self): url = self.base.append_query_param("q", self.text) self.assertEqual(self.text, url.query_param("q")) def test_append_bytestring_query_param(self): url = self.base.append_query_param("q", self.bytes) self.assertEqual(self.text, url.query_param("q")) def test_set_unicode_query_params(self): url = self.base.query_params({"q": self.text}) self.assertEqual(self.text, url.query_param("q")) def test_set_bytestring_query_params(self): url = self.base.query_params({"q": self.bytes}) self.assertEqual(self.text, url.query_param("q")) def test_add_unicode_path_segment(self): url = self.base.add_path_segment(self.text) self.assertEqual(self.text, url.path_segment(0)) def test_add_bytestring_path_segment(self): url = self.base.add_path_segment(self.bytes) self.assertEqual(self.text, url.path_segment(0)) def test_add_bytestring_path_segment(self): url = self.base.add_path_segment(self.bytes) self.assertEqual(self.text, url.path_segment(0)) def test_add_unicode_fragment(self): url = self.base.fragment(self.text) self.assertEqual(self.text, url.fragment())
def get_links(self, request): edit_link = URL(request.link(self.submission)) edit_link = edit_link.query_param('edit', '') edit_link = edit_link.query_param('return-to', request.url) return [ Link( text=_('Edit submission'), url=edit_link.as_string(), classes=('edit-link', ) ) ]
def get_wikipedia(args, name): url = URL( "http://en.wikipedia.org/w/api.php?format=json&action=query&prop=info&inprop=url") def get_result(res): """ { "query": { "pages": { "45724": { "contentmodel": "wikitext", "counter": "", "editurl": "http://en.wikipedia.org/w/index.php?title=Panthera_leo&action=edit", "fullurl": "http://en.wikipedia.org/wiki/Panthera_leo", "lastrevid": 535861485, "length": 71, "ns": 0, "pageid": 45724, "pagelanguage": "en", "redirect": "", "title": "Panthera leo", "touched": "2014-02-27T02:04:39Z" } } } } """ res = res.json().get('query', {}).get('pages', {}) return res.values()[0] if res else {} return get_data(args, name, 'wikipedia', url.query_param('titles', name), get_result)
def set_param(request=None, url=None, **kwargs): if not request and not url: return '/' url = URL(path=request.path, query=request.META['QUERY_STRING']) if request else URL(url) for k, v in kwargs.items(): url = url.query_param(k, v) return url.as_string()
def editbar_links(self): if self.request.is_logged_in: edit_url = URL(self.request.link(self.model.event, 'bearbeiten')) edit_url = edit_url.query_param( 'return-to', self.request.link(self.model.event) ) edit_link = Link( text=_("Edit"), url=edit_url.as_string(), classes=('edit-link', ) ) if self.event_deletable(self.model.event): delete_link = DeleteLink( text=_("Delete"), url=self.request.link(self.model.event), confirm=_("Do you really want to delete this event?"), yes_button_text=_("Delete event"), redirect_after=self.events_url ) else: delete_link = DeleteLink( text=_("Delete"), url=self.request.link(self.model.event), confirm=_("This event can't be deleted."), extra_information=_( "To remove this event, go to the ticket and reject it." ) ) return [edit_link, delete_link]
def __call__(self, data: str): try: url = URL(data) except ValueError: raise ValidationError(_("URL cannot be parsed"), code="parse_error") if url.has_query_param('db'): if not url.query_param('db').isdigit(): raise ValidationError(_("Invalid port specified"), code="invalid_port") if url.scheme() == "unix": if url.host(): raise ValidationError( _("Hostname not supported for unix domain sockets"), code="unix_domain_socket_hostname") if url.port(): raise ValidationError( _("Port not supported for unix domain sockets"), code="unix_domain_socket_port") if not url.path(): raise ValidationError( _("No path specified for unix domain socket"), code="unix_domain_socket_path") if url.scheme() in ("redis", "redis+tls"): if not url.host(): raise ValidationError(_("No host specified"), code="host_missing")
def url(self, path='/', **query): url = URL(path) if not url.host(): url = url.host(self.host) if not url.scheme(): url = url.scheme('http') for k, v in query.items(): url = url.query_param(k, v) return url
def get_video_id_from_url(self, video_url): video_url = URL(video_url) if 'youtube' not in video_url.host(): raise DownytError( 'Provided URL is not from YouTube: {}'.format(video_url) ) return video_url.query_param('v')
def get_eol(args, name): """ http://eol.org/api/search/1.0.json?q=Panthera+leo&page=1&exact=true&\ filter_by_taxon_concept_id=&filter_by_hierarchy_entry_id=&filter_by_string= """ url = URL('http://eol.org/api/search/1.0.json?page=1&exact=true') def get_result(res): res = res.json().get('results') return res[0] if res else {} return get_data(args, name, 'eol', url.query_param('q', name), get_result)
def get_links(self, request): if self.deleted: return [] links = [] data = self.reservations[0].data or {} if not data.get("accepted"): link = URL(request.link(self.reservations[0], "annehmen")) link = link.query_param("return-to", request.url) links.append(Link(text=_("Accept reservation"), url=link.as_string(), classes=("accept-link",))) link = URL(request.link(self.reservations[0], "absagen")) link = link.query_param("return-to", request.url) links.append( DeleteLink( text=_("Reject reservation"), url=link.as_string(), confirm=_("Do you really want to reject this reservation?"), extra_information=_("Rejecting this reservation can't be undone."), yes_button_text=_("Reject reservation"), request_method="GET", redirect_after=request.url, ) ) if self.submission: link = URL(request.link(self.submission)) link = link.query_param("edit", "") link = link.query_param("return-to", request.url) link = link.query_param("title", request.translate(_("Details about the reservation"))) links.append(Link(text=_("Edit details"), url=link.as_string(), classes=("edit-link",))) return links
async def forward_request(token, request): """ Takes the given token and forwards the request to the associated redirect (must exist in database). Returns a web response with the same status code as the returned by the redirect. If the response was successful, the token is deleted immediately. """ token_bound = request.app.db[token] url = token_bound['url'] payload = copy(dict(request.query)) payload.update(await request.json(loads=quiet_json)) payload['oauth_redirect_secret'] = token_bound['secret'] async with ClientSession() as session: if token_bound['method'] == 'GET': url = URL(url) for key, value in payload.items(): url = url.query_param(key, value) def send_request(): return session.get(url.as_string()) elif token_bound['method'] == 'POST': def send_request(): return session.post(url, data=json.dumps(payload)) elif token_bound['method'] == 'PUT': def send_request(): return session.put(url, data=json.dumps(payload)) async with send_request() as response: if 200 <= response.status < 300: del request.app.db[token] return web.HTTPFound(token_bound['success_url']) else: return web.HTTPFound(token_bound['error_url'])
def handle_forbidden(self, request): """ If a view is forbidden, the request is redirected to the login view. There, the user may login to the site and be redirected back to the originally forbidden view. """ @request.after def set_status_code(response): response.status_code = self.code # pass along 403 url = URL(request.link(request.app.town, name='login')) url = url.query_param('to', request.url) return { 'layout': DefaultLayout(self, request), 'title': _(u"Access Denied"), 'login_url': url }
def handle_pending_submission(self, request): """ Renders a pending submission, takes it's input and allows the user to turn the submission into a complete submission, once all data is valid. """ collection = FormCollection(request.app.session()) form = request.get_form(self.form_class, data=self.data) form.action = request.link(self) form.validate() if not request.POST: form.ignore_csrf_error() else: collection.submissions.update(self, form) if 'return-to' in request.GET: action = URL(form.action) action = action.query_param('return-to', request.GET['return-to']) form.action = action.as_string() completable = not form.errors and 'edit' not in request.GET if completable and 'return-to' in request.GET: request.success(_(u"Your changes were saved")) return morepath.redirect(request.GET['return-to']) return { 'layout': FormSubmissionLayout(self, request), 'title': self.form.title, 'form': form, 'completable': completable, 'edit_link': request.link(self) + '?edit', 'complete_link': request.link(self, 'complete'), 'is_pending': self.state == 'pending', 'readonly': 'readonly' in request.GET }
def handle_edit_event(self, request, form): """ Edit an event. An anonymous user might edit an initiated event, a logged in user can also edit all events. """ assert_anonymous_access_only_temporary(request, self) if form.submitted(request): form.update_model(self) request.success(_("Your changes were saved")) if 'return-to' in request.GET: return morepath.redirect(request.GET['return-to']) return morepath.redirect(request.link(self)) form.apply_model(self) if 'return-to' in request.GET: action = URL(form.action) action = action.query_param('return-to', request.GET['return-to']) form.action = action.as_string() layout = EventLayout(self, request) layout.breadcrumbs.append(Link(_("Edit"), '#')) layout.editbar_links = [] return { 'layout': layout, 'title': self.title, 'form': form, 'form_width': 'large' }
def test_setting_list_as_query_param(self): url = URL().query_param('q', ['testing', 'eggs']) self.assertEqual(['testing', 'eggs'], url.query_param('q', as_list=True))
def test_setting_single_item_list_as_query_param(self): url = URL().query_param('q', ['testing']) self.assertEqual('testing', url.query_param('q'))
def test_setting_single_item_list_as_query_param(self): url = URL().query_param("q", ["testing"]) self.assertEqual("testing", url.query_param("q"))
def for_username(self, username): url = URL(self.action) url = url.query_param('username', username) return url.as_string()
def test_setting_single_item_list_as_query_param(self): url = URL().query_param('q', ['testing']) self.assertEqual('testing', url.query_param('q'))
def test_set_list(self): base = URL("http://127.0.0.1/") url = base.query_param("q", ["something", "else"]) values = url.query_param("q", as_list=True) self.assertEqual(["something", "else"], values)
#!/usr/bin/python __author__ = 'oracle' from purl import URL from_str = URL('https://www.google.com/search?q=testing') print from_str.query_param('q')
'search').query_param('q', 'google') print(inline_url) print(inline_url.as_string()) u = URL('postgres://*****:*****@localhost:1234/test?ssl=true') print(u.scheme()) print(u.host()) print(u.domain()) print(u.username()) print(u.password()) print(u.netloc()) print(u.port()) print(u.path()) print(u.query()) print(u.path_segments()) print(u.query_param('ssl')) print(u.query_param('ssl', as_list=True)) print(u.query_params()) print(u.has_query_param('ssl')) print(u.subdomains()) u = URL.from_string('https://github.com/minwook-shin') print(u.path_segment(0)) new_url = u.add_path_segment('minwook-shin.github.com') print(new_url.as_string()) from purl import expand print(expand(u"{/path*}", {'path': ['sub', 'index']})) from purl import Template
import requests from purl import URL from bs4 import BeautifulSoup from_str = URL('https://www.google.com/search?q=testing') print from_str.query_param('q') r = requests.get('http://www.oschina.net') html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """ bs=BeautifulSoup(r.text) print bs.text
def test_set_list(self): base = URL('http://127.0.0.1/') url = base.query_param('q', ['something', 'else']) values = url.query_param('q', as_list=True) self.assertEqual(['something', 'else'], values)
def test_set_list(self): base = URL('http://127.0.0.1/') url = base.query_param('q', ['something', 'else']) values = url.query_param('q', as_list=True) self.assertEqual(['something', 'else'], values)
def test_setting_list_as_query_param(self): url = URL().query_param('q', ['testing', 'eggs']) self.assertEqual(['testing', 'eggs'], url.query_param('q', as_list=True))
def test_setting_list_as_query_param(self): url = URL().query_param("q", ["testing", "eggs"]) self.assertEqual(["testing", "eggs"], url.query_param("q", as_list=True))