def test_quoting(self): self.assert_strict_equal(urls.url_quote(u'\xf6\xe4\xfc'), '%C3%B6%C3%A4%C3%BC') self.assert_strict_equal(urls.url_unquote(urls.url_quote(u'#%="\xf6')), u'#%="\xf6') self.assert_strict_equal(urls.url_quote_plus('foo bar'), 'foo+bar') self.assert_strict_equal(urls.url_unquote_plus('foo+bar'), u'foo bar') self.assert_strict_equal(urls.url_quote_plus('foo+bar'), 'foo%2Bbar') self.assert_strict_equal(urls.url_unquote_plus('foo%2Bbar'), u'foo+bar') self.assert_strict_equal( urls.url_encode({ b'a': None, b'b': b'foo bar' }), 'b=foo+bar') self.assert_strict_equal( urls.url_encode({ u'a': None, u'b': u'foo bar' }), 'b=foo+bar') self.assert_strict_equal( urls.url_fix( u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)'), 'http://de.wikipedia.org/wiki/Elf%20(Begriffskl%C3%A4rung)') self.assert_strict_equal(urls.url_quote_plus(42), '42') self.assert_strict_equal(urls.url_quote(b'\xff'), '%FF')
def handle_password_api(): if not request.headers['Content-Type'] == 'application/json': return unsupported_media_type_api() payload = request.get_json() password = payload.get('password', None) if not password: return bad_request_api() time_period = payload.get('ttl', 'hour').lower() if not time_period in TIME_CONVERSION: return bad_request_api() ttl = TIME_CONVERSION[time_period] key = set_password(password, ttl) base_url = make_base_url() link_web = base_url + url_quote_plus(key) link_api = base_url + "api/" + url_quote_plus(key) data = { 'web': link_web, 'api': link_api, } return jsonify(data)
def oracle_get(): popular_words = oracle.popular_words(90) random.shuffle(popular_words) question = request.args.get("question") if question: show_cloud="block" answer = oracle.the_oracle_speaks(question) if answer.couplet['artist'].name['name_list'][0] == '': artist = answer.couplet['artist'].name['name_list'][1] else: artist = ' name_part_two '.join(answer.couplet['artist'].name['name_list']).strip() og_description="Asked the glitch oracle: '"+question+"' and am told '"+answer.couplet['couplet'][0]+answer.couplet['couplet'][1]+"'" page_title="The Glitch Oracle - Psychic Answers from the Infinite Glitch" meta_description="Asked the glitch oracle: '"+question+"' and am told '"+answer.couplet['couplet'][0]+answer.couplet['couplet'][1]+"'" # TODO: Turn every bit of this info into plain text, then make it possible to share these things. og_url="http://www.infiniteglitch.net/share_oracle/"+url_quote_plus(question)+"/"+url_quote_plus(answer.couplet['couplet'][0])+"/"+url_quote_plus(answer.couplet['couplet'][1])+"/"+url_quote_plus(artist) else: question = answer = "" show_cloud = "none" page_title="Ask The Glitch Oracle" og_description="Ask The Glitch Oracle" meta_description="Ask The Glitch Oracle" og_url="http://www.infiniteglitch.net/oracle" return render_template("oracle.html", page_title="Glitch Oracle", question=question, answer=answer, popular_words=popular_words, show_cloud=show_cloud, og_description=og_description, meta_description=meta_description, og_url=og_url, url_quote_plus=url_quote_plus)
def stripe_form_generate_values(self, tx_values): self.ensure_one() base_url = self.get_base_url() stripe_session_data = { "payment_method_types[]": "card", "line_items[][amount]": int(tx_values["amount"] if tx_values["currency"].name in INT_CURRENCIES else float_round(tx_values["amount"] * 100, 2)), "line_items[][currency]": tx_values["currency"].name, "line_items[][quantity]": 1, "line_items[][name]": tx_values["reference"], "client_reference_id": tx_values["reference"], "success_url": urls.url_join(base_url, StripeController._success_url) + "?reference=%s" % urls.url_quote_plus(tx_values["reference"]), "cancel_url": urls.url_join(base_url, StripeController._cancel_url) + "?reference=%s" % urls.url_quote_plus(tx_values["reference"]), "payment_intent_data[description]": tx_values["reference"], "customer_email": tx_values.get("partner_email") or tx_values.get("billing_partner_email"), } tx_values["session_id"] = self._create_stripe_session( stripe_session_data) return tx_values
def mail_tag(env, mail, encode=None, **kwds): options = { 'cc': None, 'bcc': None, 'subject': None, 'body': None, } options.update(kwds) name = mail extras = [] htmloptions = [] for key, value in options.iteritems(): if not value: continue elif 'cc' == key or 'bcc' == key: value = value.strip() if value: value = url_quote_plus(value) value = value.replace('+', '%20') value = value.replace('%40', '@') value = value.replace('%2C', ',') extras.append('%s=%s' % (key, value)) elif 'body' == key or 'subject' == key: value = to_str(value).strip() if value: value = url_quote_plus(value) value = value.replace('+', '%20') extras.append('%s=%s' % (key, value)) elif 'name' == key: name = value else: htmloptions.append('%s=%s' % (jinja2.escape(key), jinja2.escape(value))) extras = '&'.join(extras) if extras: extras = '?' + extras htmloptions = ' '.join(htmloptions) if encode is None: result = '<a href="mailto:%s%s" %s>%s</a>' % (mail, extras, htmloptions, name) else: mailto = obfuscate('mailto:%s' % mail) atag = '<a href="%s%s" %s>%s</a>' % (mailto, extras, htmloptions, obfuscate(name)) if 'js' != encode: result = atag else: tmp = obfuscate('document.write(\'%s\');' % atag, js=True) result = '<script type="text/javascript">eval(unescape(\'%s\'));</script>' % tmp if env.autoescape: result = jinja2.Markup(result) return result
def test_quoting(self): self.assert_strict_equal(urls.url_quote(u'\xf6\xe4\xfc'), '%C3%B6%C3%A4%C3%BC') self.assert_strict_equal(urls.url_unquote(urls.url_quote(u'#%="\xf6')), u'#%="\xf6') self.assert_strict_equal(urls.url_quote_plus('foo bar'), 'foo+bar') self.assert_strict_equal(urls.url_unquote_plus('foo+bar'), u'foo bar') self.assert_strict_equal(urls.url_encode({b'a': None, b'b': b'foo bar'}), 'b=foo+bar') self.assert_strict_equal(urls.url_encode({u'a': None, u'b': u'foo bar'}), 'b=foo+bar') self.assert_strict_equal(urls.url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)'), 'http://de.wikipedia.org/wiki/Elf%20(Begriffskl%C3%A4rung)') self.assert_strict_equal(urls.url_quote_plus(42), '42') self.assert_strict_equal(urls.url_quote(b'\xff'), '%FF')
def create_login_url(self, url): import os hostname = get_appid() + '.appspot.com' url = url_for("auth/login", next=url_quote_plus(url), original_host_url=url_quote_plus(local.request.host_url), owned_domain_hack=True) if 'SERVER_SOFTWARE' in os.environ and \ os.environ['SERVER_SOFTWARE'].startswith('Dev'): return url else: return "https://%s%s" % (hostname, url)
def mail_tag(env, mail, encode=None, **kwds): ### from symfony options = { 'cc': None, 'bcc': None, 'subject': None, 'body': None, } options.update(kwds) name = mail extras = [] htmloptions = [] for key, value in options.iteritems(): if not value: continue elif 'cc' == key or 'bcc' == key: value = value.strip() if value: value = url_quote_plus(value) value = value.replace('+', '%20') value = value.replace('%40', '@') value = value.replace('%2C', ',') extras.append('%s=%s' % (key, value)) elif 'body' == key or 'subject' == key: value = to_str(value).strip() if value: value = url_quote_plus(value) value = value.replace('+', '%20') extras.append('%s=%s' % (key, value)) elif 'name' == key: name = value else: htmloptions.append('%s=%s' % (jinja2.escape(key), jinja2.escape(value))) extras = ('?' + '&'.join(extras)) if extras else '' htmloptions = (' ' + ' '.join(htmloptions)) if htmloptions else '' if encode is None: e_mail = jinja2.escape(mail) e_name = jinja2.escape(name) result = '<a href="mailto:%s%s"%s>%s</a>' % (e_mail, extras, htmloptions, e_name) else: o_mail = obfuscate(env, 'mailto:%s' % mail) o_name = obfuscate(env, name) result = '<a href="%s%s"%s>%s</a>' % (o_mail, extras, htmloptions, o_name) if 'js' == encode: o_str = obfuscate(env, 'document.write(\'%s\');' % result, js=True) result = '<script type="text/javascript">eval(unescape(\'%s\'));</script>' % o_str return to_markup(env, result)
def _url(req, action, id=None, errormsg=""): if id is not None and action == 'view' and len(errormsg) < 2: # I can do this because .htaccess has this line: # RewriteRule ^([a-z0-9]+)$ /moerderspiel/view?id=$1 [R=302] return "%s%s" % (req.host_url, id) else: url = "%s%s" % (url_for('.index'), action) if id != None: url += '?id=' + id if len(errormsg) > 1 and id == None: url += '?msg=' + url_quote_plus(errormsg) elif len(errormsg) > 1: url += '&msg=' + url_quote_plus(errormsg) return url
def test_quoting(): strict_eq(urls.url_quote(u"\xf6\xe4\xfc"), "%C3%B6%C3%A4%C3%BC") strict_eq(urls.url_unquote(urls.url_quote(u'#%="\xf6')), u'#%="\xf6') strict_eq(urls.url_quote_plus("foo bar"), "foo+bar") strict_eq(urls.url_unquote_plus("foo+bar"), u"foo bar") strict_eq(urls.url_quote_plus("foo+bar"), "foo%2Bbar") strict_eq(urls.url_unquote_plus("foo%2Bbar"), u"foo+bar") strict_eq(urls.url_encode({b"a": None, b"b": b"foo bar"}), "b=foo+bar") strict_eq(urls.url_encode({u"a": None, u"b": u"foo bar"}), "b=foo+bar") strict_eq( urls.url_fix(u"http://de.wikipedia.org/wiki/Elf (Begriffsklärung)"), "http://de.wikipedia.org/wiki/Elf%20(Begriffskl%C3%A4rung)", ) strict_eq(urls.url_quote_plus(42), "42") strict_eq(urls.url_quote(b"\xff"), "%FF")
def test_quoting(): assert urls.url_quote("\xf6\xe4\xfc") == "%C3%B6%C3%A4%C3%BC" assert urls.url_unquote(urls.url_quote('#%="\xf6')) == '#%="\xf6' assert urls.url_quote_plus("foo bar") == "foo+bar" assert urls.url_unquote_plus("foo+bar") == "foo bar" assert urls.url_quote_plus("foo+bar") == "foo%2Bbar" assert urls.url_unquote_plus("foo%2Bbar") == "foo+bar" assert urls.url_encode({b"a": None, b"b": b"foo bar"}) == "b=foo+bar" assert urls.url_encode({"a": None, "b": "foo bar"}) == "b=foo+bar" assert ( urls.url_fix("http://de.wikipedia.org/wiki/Elf (Begriffsklärung)") == "http://de.wikipedia.org/wiki/Elf%20(Begriffskl%C3%A4rung)" ) assert urls.url_quote_plus(42) == "42" assert urls.url_quote(b"\xff") == "%FF"
def serialize(self, expires=None): """Serialize the secure cookie into a string. If expires is provided, the session will be automatically invalidated after expiration when you unseralize it. This provides better protection against session cookie theft. :param expires: an optional expiration date for the cookie (a :class:`datetime.datetime` object) """ if self.secret_key is None: raise RuntimeError('no secret key defined') if expires: self['_expires'] = _date_to_unix(expires) result = [] mac = hmac(self.secret_key, None, self.hash_method) for key, value in sorted(self.items()): result.append(('%s=%s' % ( url_quote_plus(key), self.quote(value).decode('ascii') )).encode('ascii')) mac.update(b'|' + result[-1]) return b'?'.join([ base64.b64encode(mac.digest()).strip(), b'&'.join(result) ])
def handle_password(): try: r = requests.post('https://www.google.com/recaptcha/api/siteverify', data={ 'secret': SP_PRIVATE_KEY, 'response': request.form['g-recaptcha-response'] }) google_response = json.loads(r.text) print('JSON: ', google_response) except: print("Error in captcha") google_response = ['exception error'] if google_response['success']: ttl, password = clean_input() token = set_password(password, ttl) if NO_SSL: # base_url = request.url_root base_url = "http://sendpass.ru/" else: base_url = STATIC_URL # base_url = request.url_root.replace("http://", "https://") if URL_PREFIX: base_url = base_url + URL_PREFIX.strip("/") + "/" link = base_url + url_quote_plus(token) return render_template('confirm.html', password_link=link) else: return render_template('set_password.html', password=password)
def validate_character(self, server_name, character_name): # Search for character character_name = character_name.encode('utf-8') url = self.lodestone_url + '/character/?q={}&worldname={}'.format( url_quote_plus(character_name), server_name) r = self.make_request(url=url) '''if not r: return None''' soup = bs4.BeautifulSoup(r.content, "html5lib") '''with open("data/searchsoup.txt", "a") as log_file: log_file.write(str(soup)) log_file.close()''' if "Due to ongoing maintenance, this page is currently unavailable." in str( soup): return "lodestone is under maintainence. what did you do? what have you DONE????" for tag in soup.select('.entry'): char_name = tag.p.contents[0].encode('utf-8') if char_name.lower() == character_name.lower(): return { 'lodestone_id': re.findall(r'(\d+)', str(tag.a['href']))[0], 'name': char_name, } return None
def handle_password(): token = [] link = [] ttl, password, duplicate = clean_input() for i in range(duplicate): token.append(set_password(password, ttl)) if NO_SSL: if HOST_OVERRIDE: base_url = f'http://{HOST_OVERRIDE}/' else: base_url = request.url_root else: if HOST_OVERRIDE: base_url = f'https://{HOST_OVERRIDE}/' else: base_url = request.url_root.replace("http://", "https://") if URL_PREFIX: base_url = base_url + URL_PREFIX.strip("/") + "/" for i in range(duplicate): link.append(base_url + url_quote_plus(token[i])) if request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html: return jsonify(link=link, ttl=ttl) else: return render_template('confirm.html', password_link=link)
def _get_canonical_url_localized(self, lang, canonical_params): """Returns the canonical URL for the current request with translatable elements appropriately translated in `lang`. If `request.endpoint` is not true, returns the current `path` instead. `url_quote_plus` is applied on the returned path. """ self.ensure_one() if request.endpoint: router = request.httprequest.app.get_db_router(request.db).bind('') arguments = dict(request.endpoint_arguments) for key, val in list(arguments.items()): if isinstance(val, models.BaseModel): if val.env.context.get('lang') != lang.code: arguments[key] = val.with_context(lang=lang.code) path = router.build(request.endpoint, arguments) else: # The build method returns a quoted URL so convert in this case for consistency. path = urls.url_quote_plus(request.httprequest.path, safe='/') lang_path = ('/' + lang.url_code) if lang != self.default_lang_id else '' canonical_query_string = '?%s' % urls.url_encode( canonical_params) if canonical_params else '' return self.get_base_url() + lang_path + path + canonical_query_string
def handle_password(): # ttl, password = clean_input() #edgarin time_period, password, email, message = clean_input() ttl = TIME_CONVERSION[time_period] timestamp = datetime.datetime.now().replace(microsecond=0).isoformat() contentObj = { 'password': password, 'email': email, 'message': message, 'timestamp': timestamp } #edgarin expiration = get_expiry_date_formatted(time_period) # print(json.dumps(contentObj)) token = set_password(json.dumps(contentObj), ttl) if NO_SSL: base_url = request.url_root else: base_url = request.url_root.replace("http://", "https://") link = base_url + url_quote_plus(token) async_send_mail('You set a secret', contentObj['email'], get_secret_set_email_body(contentObj, time_period)) return render_template('confirm.html', password_link=link, timestamp=timestamp.replace('T', ' '), expiration=expiration)
def admin_save(): title = request.form.get('title', None) if not title: return redirect(url_for('admin_edit')) f = open('posts/' + urlsafe_b64encode(title), 'w') f.write(request.form.get('body', '')) f.close() return redirect(url_for('post', url=url_quote_plus(title)))
def create_login_url(self, next_url='/'): if hasattr(local.request, settings.MARKETPLACE_DOMAIN_NAME_KEY): # marketplace domain = getattr(local.request, settings.MARKETPLACE_DOMAIN_NAME_KEY) return create_marketplace_login_url(domain, next_url) return url_for('gaema/select_service', targets='|'.join(self.valid_services), next_url=url_quote_plus(next_url))
def test_quoting(self): assert urls.url_quote(u'\xf6\xe4\xfc') == '%C3%B6%C3%A4%C3%BC' assert urls.url_unquote(urls.url_quote(u'#%="\xf6')) == u'#%="\xf6' assert urls.url_quote_plus('foo bar') == 'foo+bar' assert urls.url_unquote_plus('foo+bar') == 'foo bar' assert urls.url_encode({'a': None, 'b': 'foo bar'}) == 'b=foo+bar' assert urls.url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)') == \ 'http://de.wikipedia.org/wiki/Elf%20%28Begriffskl%C3%A4rung%29'
def oracle_get(): popular_words = oracle.popular_words(90) random.shuffle(popular_words) question = request.args.get("question") print(question) if not len(question) == 0: question = question show_cloud = "block" answer = oracle.the_oracle_speaks(question) if answer.couplet['artist'].name['name_list'][0] == '': artist = answer.couplet['artist'].name['name_list'][1] else: artist = ' name_part_two '.join( answer.couplet['artist'].name['name_list']).strip() og_description = "Asked the glitch oracle: '" + question + "' and am told '" + answer.couplet[ 'couplet'][0] + answer.couplet['couplet'][1] + "'" page_title = "The Glitch Oracle - Psychic Answers from the Infinite Glitch" meta_description = "Asked the glitch oracle: '" + question + "' and am told '" + answer.couplet[ 'couplet'][0] + answer.couplet['couplet'][1] + "'" og_url = "http://www.infiniteglitch.net/share_oracle/" + url_quote_plus( question) + "/" + url_quote_plus( answer.couplet['couplet'][0]) + "/" + url_quote_plus( answer.couplet['couplet'][1]) + "/" + url_quote_plus( artist) print(answer.couplet['artist'].name['display_name']) print(answer.couplet['couplet'][0]) print(question) print(111111111) redirect(og_url) else: question, answer = ("", "") show_cloud = "none" page_title = "Ask The Glitch Oracle" og_description = "Ask The Glitch Oracle" meta_description = "Ask The Glitch Oracle" og_url = "http://www.infiniteglitch.net/oracle" return render_template("oracle.html", page_title="Glitch Oracle", question=question, answer=answer, popular_words=popular_words[:90], show_cloud=show_cloud, og_description=og_description, meta_description=meta_description, og_url=og_url, url_quote_plus=url_quote_plus)
def add_protected_view(self): url = '/_protected' quoted_url = url_quote_plus('/_protected') self.redirect_url = '/login?next={0}'.format(quoted_url) @self.app.route(url) @login_required def protected(): return 'success'
def add_protected_view(self): url = '/_protected' quoted_url = url_quote_plus('/_protected') self.redirect_url = '/login?next={}'.format(quoted_url) @self.app.route(url) @login_required def protected(): return 'success'
def handle_password(): ttl, password = clean_input() token = set_password(password, ttl) base_url = make_base_url() if URL_PREFIX: base_url = base_url + URL_PREFIX.strip("/") + "/" link = base_url + url_quote_plus(token) return render_template('confirm.html', password_link=link)
def handle_password(): ttl, password = clean_input() token = set_password(password, ttl) if NO_SSL: base_url = request.url_root else: base_url = request.url_root.replace("http://", "https://") link = base_url + url_quote_plus(token) return render_template('confirm.html', password_link=link)
def test_quoting(self): assert urls.url_quote(u"\xf6\xe4\xfc") == "%C3%B6%C3%A4%C3%BC" assert urls.url_unquote(urls.url_quote(u'#%="\xf6')) == u'#%="\xf6' assert urls.url_quote_plus("foo bar") == "foo+bar" assert urls.url_unquote_plus("foo+bar") == "foo bar" assert urls.url_encode({"a": None, "b": "foo bar"}) == "b=foo+bar" assert ( urls.url_fix(u"http://de.wikipedia.org/wiki/Elf (Begriffsklärung)") == "http://de.wikipedia.org/wiki/Elf%20%28Begriffskl%C3%A4rung%29" )
def key_rename(db: int, key: str) -> Response: conn = server.connection conn.execute_command("SELECT", db) key = url_unquote_plus(key) new_name = request.form["keyname"] conn.rename(key, new_name) return jsonify({ "code": 0, "data": url_for("redisboard.key_detail", db=db, key=url_quote_plus(new_name)), })
def handle_password(): password = request.form['password'] token = set_password(password) if NO_SSL: base_url = request.url_root else: base_url = request.url_root.replace("http://", "https://") if URL_PREFIX: base_url = base_url + URL_PREFIX.strip("/") + "/" link = base_url + url_quote_plus(token) return render_template('confirm.html', password_link=link)
def stripe_form_generate_values(self, tx_values): self.ensure_one() base_url = self.get_base_url() stripe_session_data = { 'line_items[][amount]': int(tx_values['amount'] if tx_values['currency'].name in INT_CURRENCIES else float_round(tx_values['amount'] * 100, 2)), 'line_items[][currency]': tx_values['currency'].name, 'line_items[][quantity]': 1, 'line_items[][name]': tx_values['reference'], 'client_reference_id': tx_values['reference'], 'success_url': urls.url_join(base_url, StripeController._success_url) + '?reference=%s' % urls.url_quote_plus(tx_values['reference']), 'cancel_url': urls.url_join(base_url, StripeController._cancel_url) + '?reference=%s' % urls.url_quote_plus(tx_values['reference']), 'payment_intent_data[description]': tx_values['reference'], 'customer_email': tx_values.get('partner_email') or tx_values.get('billing_partner_email'), } if tx_values['type'] == 'form_save': stripe_session_data[ 'payment_intent_data[setup_future_usage]'] = 'off_session' self._add_available_payment_method_types(stripe_session_data, tx_values) tx_values['session_id'] = self.with_context( stripe_manual_payment=True)._create_stripe_session( stripe_session_data) return tx_values
def handle_login(request, userobj=None, username=None, password=None, attended=True, openid_identifier=None, stage=None): """ Process a 'login' request by going through the configured authentication methods in turn. The passable keyword arguments are explained in more detail at the top of this file. """ params = { 'username': username, 'password': password, 'attended': attended, 'openid_identifier': openid_identifier, 'multistage': (stage and True) or None } for authmethod in request.cfg.auth: if stage and authmethod.name != stage: continue ret = authmethod.login(request, userobj, **params) userobj = ret.user_obj cont = ret.continue_flag if stage: stage = None del params['multistage'] if ret.multistage: request._login_multistage = ret.multistage request._login_multistage_name = authmethod.name return userobj if ret.redirect_to: nextstage = get_multistage_continuation_url( request, authmethod.name) url = ret.redirect_to url = url.replace('%return_form', url_quote_plus(nextstage)) url = url.replace('%return', url_quote(nextstage)) abort(redirect(url)) msg = ret.message if msg and not msg in request._login_messages: request._login_messages.append(msg) if not cont: break return userobj
def unauthenticated(): """ Prepare a Flash message and redirect to USER_UNAUTHENTICATED_ENDPOINT""" # Prepare Flash message url = request.url flash(_("You must be signed in to access '%(url)s'.", url=url), 'error') # quote the fully qualified url quoted_url = url_quote_plus(url) # Redirect to USER_UNAUTHENTICATED_ENDPOINT user_manager = current_app.user_manager return redirect( _endpoint_url(user_manager.unauthenticated_endpoint) + '?next=' + quoted_url)
def handle_login(userobj, **kw): """ Process a 'login' request by going through the configured authentication methods in turn. The passable keyword arguments are explained in more detail at the top of this file. """ stage = kw.get('stage') params = { 'username': kw.get('login_username'), 'password': kw.get('login_password'), 'multistage': (stage and True) or None, 'attended': True } # add the other parameters from the form for param in kw.keys(): params[param] = kw.get(param) for authmethod in app.cfg.auth: if stage and authmethod.name != stage: continue ret = authmethod.login(userobj, **params) userobj = ret.user_obj cont = ret.continue_flag if stage: stage = None del params['multistage'] if ret.multistage: flaskg._login_multistage = ret.multistage flaskg._login_multistage_name = authmethod.name return userobj if ret.redirect_to: nextstage = get_multistage_continuation_url(authmethod.name) url = ret.redirect_to url = url.replace('%return_form', url_quote_plus(nextstage)) url = url.replace('%return', url_quote(nextstage)) abort(redirect(url)) msg = ret.message if msg and msg not in flaskg._login_messages: flaskg._login_messages.append(msg) if not cont: break return userobj
def _generate_link(self): for payment_link in self: record = self.env[payment_link.res_model].browse( payment_link.res_id) link = ( '%s/website_payment/pay?reference=%s&amount=%s¤cy_id=%s' '&partner_id=%s&access_token=%s') % ( record.get_base_url(), urls.url_quote_plus(payment_link.description), payment_link.amount, payment_link.currency_id.id, payment_link.partner_id.id, payment_link.access_token) if payment_link.company_id: link += '&company_id=%s' % payment_link.company_id.id if payment_link.res_model == 'account.move': link += '&invoice_id=%s' % payment_link.res_id payment_link.link = link
def handle_password(): ttl, password = clean_input() token = set_password(password, ttl) if HOST: base_url = "http://" + HOST + '/' else: base_url = request.url_root if NO_SSL: base_url = base_url else: base_url = base_url.replace("http://", "https://") if URL_PREFIX: base_url = base_url + URL_PREFIX.strip("/") + "/" link = base_url + url_quote_plus(token) return render_template('confirm.html', password_link=link)
def _compute_l10n_do_electronic_stamp(self): l10n_do_ecf_invoice = self.filtered( lambda i: i.is_ecf_invoice and not i. l10n_latam_manual_document_number and i.l10n_do_ecf_security_code) for invoice in l10n_do_ecf_invoice: ecf_service_env = self.env.context.get("l10n_do_ecf_service_env", "CerteCF") doc_code_prefix = invoice.l10n_latam_document_type_id.doc_code_prefix is_rfc = ( # Es un Resumen Factura Consumo doc_code_prefix == "E32" and invoice.amount_total_signed < 250000) qr_string = "https://%s.dgii.gov.do/%s/ConsultaTimbre%s?" % ( "fc" if is_rfc else "ecf", ecf_service_env, "FC" if is_rfc else "", ) qr_string += "RncEmisor=%s&" % invoice.company_id.vat or "" if not is_rfc: qr_string += ( "RncComprador=%s&" % invoice.commercial_partner_id.vat if invoice.l10n_latam_document_type_id.doc_code_prefix[1:] != "43" else invoice.company_id.vat) qr_string += "ENCF=%s&" % invoice.l10n_do_fiscal_number or "" if not is_rfc: qr_string += "FechaEmision=%s&" % ( invoice.invoice_date or fields.Date.today()).strftime("%d-%m-%Y") qr_string += "MontoTotal=%s&" % ("%f" % sum( invoice.line_ids.mapped("credit"))).rstrip("0").rstrip(".") if not is_rfc: qr_string += "FechaFirma=%s&" % invoice.l10n_do_ecf_sign_date.strftime( "%d-%m-%Y%%20%H:%M:%S") special_chars = " !#$&'()*+,/:;=?@[]\"-.<>\\^_`" security_code = "".join( c.replace(c, "%" + c.encode("utf-8").hex()).upper() if c in special_chars else c for c in invoice.l10n_do_ecf_security_code or "") qr_string += "CodigoSeguridad=%s" % security_code invoice.l10n_do_electronic_stamp = urls.url_quote_plus(qr_string) (self - l10n_do_ecf_invoice).l10n_do_electronic_stamp = False
def image_fetch(self): q = '"%s" %d poster' % (self.title, self.year) q = 'http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=' + url_quote_plus(q) q = requests.get(q) q = json_loads(q.content) try: q = q['responseData']['results'] except (TypeError, KeyError): return for item in q: img = item['url'] img_lower = img.lower() cond = [forbidden not in img_lower for forbidden in forbidden_domains] if all(cond): self.img = img return
def validate_character(self, server_name, character_name): # Search for character url = self.lodestone_url + "/character/?q=%s&worldname=%s" % (url_quote_plus(character_name), server_name) r = self.make_request(url=url) if not r: return None soup = bs4.BeautifulSoup(r.content) for tag in soup.select(".player_name_area .player_name_gold a"): if tag.string.lower() == character_name.lower(): return {"lodestone_id": re.findall(r"(\d+)", tag["href"])[0], "name": str(tag.string)} return None
def primary_key_value(instance, as_string=False): """Returns the value of the primary key field of the specified `instance` of a SQLAlchemy model. This is a convenience function for:: getattr(instance, primary_key_name(instance)) If `as_string` is ``True``, try to coerce the return value to a string. """ result = getattr(instance, primary_key_name(instance)) if not as_string: return result try: return str(result) except UnicodeEncodeError: return url_quote_plus(result.encode('utf-8'))
def primary_key_value(instance, as_string=False): """Returns the value of the primary key field of the specified `instance` of a SQLAlchemy model. This essentially a convenience function for:: getattr(instance, primary_key_for(instance)) If `as_string` is ``True``, try to coerce the return value to a string. """ result = getattr(instance, primary_key_for(instance)) if not as_string: return result try: return str(result) except UnicodeEncodeError: return url_quote_plus(result.encode('utf-8'))
def validate_character(self, server_name, character_name): # Search for character url = self.lodestone_url + '/character/?q=%s&worldname=%s' \ % (url_quote_plus(character_name), server_name) r = self.make_request(url=url) if not r: return None soup = bs4.BeautifulSoup(r.content, "html.parser") for tag in soup.select('.player_name_area .player_name_gold a'): if tag.string.lower() == character_name.lower(): return { 'lodestone_id': re.findall(r'(\d+)', tag['href'])[0], 'name': str(tag.string), } return None
def urlencode_filter(strval): """ A template filter to return a URL-encoded string. """ return url_quote_plus(strval)
def index(): posts = [{"title": title, "url": url_quote_plus(title)} for title in db.list()] return render_template("index.html", posts=posts)
#iterate through courses and get their membership info via LTI timestamp = oauth.generate_timestamp() nonce = oauth.generate_nonce(16) postParams = {} postParams['lti_message_type'] = 'basic-lis-readmembershipsforcontext' postParams['id'] = course.LTIid postParams['lti_version'] = 'LTI-1p0' postParams['oauth_consumer_key'] = 'LTI_ACJ' postParams['oauth_callback'] = 'about:blank' postParams['oauth_version'] = '1.0' postParams['oauth_signature_method'] = 'HMAC-SHA1' postParams['oauth_timestamp'] = timestamp postParams['oauth_nonce'] = nonce req = oauth.OAuthRequest(http_url=course.LTIURL, http_method='POST', parameters=postParams) hmacAlg = hmac.HMAC('acjsecret&', urls.url_quote_plus(req.get_normalized_http_method()) + '&' + urls.url_quote_plus(course.LTIURL) + '&' + urls.url_quote_plus(req.get_normalized_parameters()), hashlib.sha1) postParams['oauth_signature'] = base64.b64encode(hmacAlg.digest()) xmlString = requests.post(course.LTIURL, data=postParams).text root = ET.fromstring(xmlString) #find the course in ACJ, create if it does not exist tmpCourse = Course.query.filter_by(name = course.courseName).first() if not tmpCourse: newCourse = Course(course.courseName) db_session.add(newCourse) commit() #create a list with all users in the course userlist = [] for member in root.find('memberships').findall('member'):
def admin_save(): title = request.form.get("title", None) if not title: return redirect(url_for("admin_edit")) db.save(title, request.form.get("body", "")) return redirect(url_for("post", url=url_quote_plus(title)))
def __call__(self, instance, only=None): """Returns a dictionary representing the fields of the specified instance of a SQLAlchemy model. The returned dictionary is suitable as an argument to :func:`flask.jsonify`; :class:`datetime.date` and :class:`uuid.UUID` objects are converted to string representations, so no special JSON encoder behavior is required. If `only` is a list, only the fields and relationships whose names appear as strings in `only` will appear in the resulting dictionary. The only exception is that the keys ``'id'`` and ``'type'`` will always appear, regardless of whether they appear in `only`. Since this function creates absolute URLs to resources linked to the given instance, it must be called within a `Flask request context`_. .. _Flask request context: http://flask.pocoo.org/docs/0.10/reqcontext/ """ # Always include at least the type, ID, and the self link, regardless # of what the user requested. if only is not None: # TODO Should the 'self' link be mandatory as well? # # TODO In Python 2.7 or later, this should be # # only = set(only) | {'type', 'id'} # only = set(only) | set(['type', 'id']) model = type(instance) try: inspected_instance = inspect(model) except NoInspectionAvailable: return instance column_attrs = inspected_instance.column_attrs.keys() descriptors = inspected_instance.all_orm_descriptors.items() # hybrid_columns = [k for k, d in descriptors # if d.extension_type == hybrid.HYBRID_PROPERTY # and not (deep and k in deep)] hybrid_columns = [k for k, d in descriptors if d.extension_type == HYBRID_PROPERTY] columns = column_attrs + hybrid_columns # Also include any attributes specified by the user. if self.additional_attributes is not None: columns += self.additional_attributes # Only include fields allowed by the user during the instantiation of # this object. if self.default_fields is not None: columns = (c for c in columns if c in self.default_fields) # If `only` is a list, only include those columns that are in the list. if only is not None: columns = (c for c in columns if c in only) # Exclude columns specified by the user during the instantiation of # this object. if self.exclude is not None: columns = (c for c in columns if c not in self.exclude) # Exclude column names that are blacklisted. columns = (c for c in columns if not c.startswith('__') and c not in COLUMN_BLACKLIST) # Exclude column names that are foreign keys. foreign_key_columns = foreign_keys(model) columns = (c for c in columns if c not in foreign_key_columns) # Create a dictionary mapping attribute name to attribute value for # this particular instance. # # TODO In Python 2.7 and later, this should be a dict comprehension. attributes = dict((column, getattr(instance, column)) for column in columns) # Call any functions that appear in the result. # # TODO In Python 2.7 and later, this should be a dict comprehension. attributes = dict((k, (v() if callable(v) else v)) for k, v in attributes.items()) # Serialize any date- or time-like objects that appear in the # attributes. # # TODO In Flask 1.0, the default JSON encoder for the Flask # application object does this automatically. Alternately, the # user could have set a smart JSON encoder on the Flask # application, which would cause these attributes to be # converted to strings when the Response object is created (in # the `jsonify` function, for example). However, we should not # rely on that JSON encoder since the user could set any crazy # encoder on the Flask application. for key, val in attributes.items(): if isinstance(val, (date, datetime, time)): attributes[key] = val.isoformat() elif isinstance(val, timedelta): attributes[key] = val.total_seconds() # Recursively serialize any object that appears in the # attributes. This may happen if, for example, the return value # of one of the callable functions is an instance of another # SQLAlchemy model class. for k, v in attributes.items(): # This is a bit of a fragile test for whether the object # needs to be serialized: we simply check if the class of # the object is a mapped class. if is_mapped_class(type(v)): attributes[k] = simple_serialize(v) # Get the ID and type of the resource. id_ = attributes.pop('id') type_ = collection_name(model) # Create the result dictionary and add the attributes. result = dict(id=id_, type=type_) if attributes: result['attributes'] = attributes # Add the self link unless it has been explicitly excluded. if ((self.default_fields is None or 'self' in self.default_fields) and (only is None or 'self' in only)): instance_id = primary_key_value(instance) # `url_for` may raise a `BuildError` if the user has not created a # GET API endpoint for this model. In this case, we simply don't # provide a self link. # # TODO This might fail if the user has set the # `current_app.build_error_handler` attribute, in which case, the # exception may not be raised. try: path = url_for(model, instance_id, _method='GET') except BuildError: pass else: url = urljoin(request.url_root, path) result['links'] = dict(self=url) # # add any included methods # if include_methods is not None: # for method in include_methods: # if '.' not in method: # value = getattr(instance, method) # # Allow properties and static attributes in # # include_methods # if callable(value): # value = value() # result[method] = value # Recursively serialize values that are themselves SQLAlchemy # models. # # TODO We really need to serialize each model using the # serializer defined for that class when the user called # APIManager.create_api for key, value in result.items(): if key not in column_attrs and is_mapped_class(type(value)): result[key] = simple_serialize(value) # If the primary key is not named "id", we'll duplicate the # primary key under the "id" key. pk_name = primary_key_name(model) if pk_name != 'id': result['id'] = result['attributes'][pk_name] # TODO Same problem as above. # # In order to comply with the JSON API standard, primary keys must be # returned to the client as strings, so we convert it here. if 'id' in result: try: result['id'] = str(result['id']) except UnicodeEncodeError: result['id'] = url_quote_plus(result['id'].encode('utf-8')) # If there are relations to convert to dictionary form, put them into a # special `links` key as required by JSON API. relations = get_relations(model) if self.default_fields is not None: relations = [r for r in relations if r in self.default_fields] # Only consider those relations listed in `only`. if only is not None: relations = [r for r in relations if r in only] if not relations: return result # For the sake of brevity, rename this function. cr = create_relationship # TODO In Python 2.7 and later, this should be a dict comprehension. result['relationships'] = dict((rel, cr(model, instance, rel)) for rel in relations) return result
def _dump(self, instance, only=None): # Always include at least the type and ID, regardless of what # the user requested. if only is not None: # TODO In Python 2.7 or later, this should be a set literal. only = set(only) | set(['type', 'id']) model = type(instance) try: inspected_instance = inspect(model) except NoInspectionAvailable: message = 'failed to get columns for model {0}'.format(model) raise SerializationException(instance, message=message) column_attrs = inspected_instance.column_attrs.keys() descriptors = inspected_instance.all_orm_descriptors.items() # hybrid_columns = [k for k, d in descriptors # if d.extension_type == hybrid.HYBRID_PROPERTY # and not (deep and k in deep)] hybrid_columns = [k for k, d in descriptors if d.extension_type == HYBRID_PROPERTY] columns = column_attrs + hybrid_columns # Also include any attributes specified by the user. if self.additional_attributes is not None: columns += self.additional_attributes # Only include fields allowed by the user during the instantiation of # this object. if self.default_fields is not None: columns = (c for c in columns if c in self.default_fields) # If `only` is a list, only include those columns that are in the list. if only is not None: columns = (c for c in columns if c in only) # Exclude columns specified by the user during the instantiation of # this object. if self.exclude is not None: columns = (c for c in columns if c not in self.exclude) # Exclude column names that are blacklisted. columns = (c for c in columns if not c.startswith('__') and c not in COLUMN_BLACKLIST) # Exclude column names that are foreign keys. foreign_key_columns = foreign_keys(model) columns = (c for c in columns if c not in foreign_key_columns) # Create a dictionary mapping attribute name to attribute value for # this particular instance. # # TODO In Python 2.7 and later, this should be a dict comprehension. attributes = dict((column, getattr(instance, column)) for column in columns) # Call any functions that appear in the result. # # TODO In Python 2.7 and later, this should be a dict comprehension. attributes = dict((k, (v() if callable(v) else v)) for k, v in attributes.items()) # Serialize any date- or time-like objects that appear in the # attributes. # # TODO In Flask 0.11, the default JSON encoder for the Flask # application object does this automatically. Alternately, the # user could have set a smart JSON encoder on the Flask # application, which would cause these attributes to be # converted to strings when the Response object is created (in # the `jsonify` function, for example). However, we should not # rely on that JSON encoder since the user could set any crazy # encoder on the Flask application. for key, val in attributes.items(): if isinstance(val, (date, datetime, time)): attributes[key] = val.isoformat() elif isinstance(val, timedelta): attributes[key] = total_seconds(val) # Recursively serialize any object that appears in the # attributes. This may happen if, for example, the return value # of one of the callable functions is an instance of another # SQLAlchemy model class. for key, val in attributes.items(): # This is a bit of a fragile test for whether the object # needs to be serialized: we simply check if the class of # the object is a mapped class. if is_mapped_class(type(val)): model_ = get_model(val) try: serializer = serializer_for(model_) serialized_val = serializer.serialize(val) except ValueError: # TODO Should this cause an exception, or fail # silently? See similar comments in `views/base.py`. # # raise SerializationException(instance) serialized_val = simple_serialize(val) # We only need the data from the JSON API document, not # the metadata. (So really the serializer is doing more # work than it needs to here.) attributes[key] = serialized_val['data'] # Get the ID and type of the resource. id_ = attributes.pop('id') type_ = collection_name(model) # Create the result dictionary and add the attributes. result = dict(id=id_, type=type_) if attributes: result['attributes'] = attributes # Add the self link unless it has been explicitly excluded. is_self_in_default = (self.default_fields is None or 'self' in self.default_fields) is_self_in_only = only is None or 'self' in only if is_self_in_default and is_self_in_only: instance_id = primary_key_value(instance) # `url_for` may raise a `BuildError` if the user has not created a # GET API endpoint for this model. In this case, we simply don't # provide a self link. # # TODO This might fail if the user has set the # `current_app.build_error_handler` attribute, in which case, the # exception may not be raised. try: path = url_for(model, instance_id, _method='GET') except BuildError: pass else: url = urljoin(request.url_root, path) result['links'] = dict(self=url) # # add any included methods # if include_methods is not None: # for method in include_methods: # if '.' not in method: # value = getattr(instance, method) # # Allow properties and static attributes in # # include_methods # if callable(value): # value = value() # result[method] = value # If the primary key is not named "id", we'll duplicate the # primary key under the "id" key. pk_name = primary_key_for(model) if pk_name != 'id': result['id'] = result['attributes'][pk_name] # TODO Same problem as above. # # In order to comply with the JSON API standard, primary keys must be # returned to the client as strings, so we convert it here. if 'id' in result: try: result['id'] = str(result['id']) except UnicodeEncodeError: result['id'] = url_quote_plus(result['id'].encode('utf-8')) # If there are relations to convert to dictionary form, put them into a # special `links` key as required by JSON API. relations = get_relations(model) if self.default_fields is not None: relations = [r for r in relations if r in self.default_fields] # Only consider those relations listed in `only`. if only is not None: relations = [r for r in relations if r in only] # Exclude relations specified by the user during the instantiation of # this object. if self.exclude is not None: relations = [r for r in relations if r not in self.exclude] if not relations: return result # For the sake of brevity, rename this function. cr = create_relationship # TODO In Python 2.7 and later, this should be a dict comprehension. result['relationships'] = dict((rel, cr(model, instance, rel)) for rel in relations) return result
def create_facebook_login_url(self, url): return url_for("fb/fb_login", next=url_quote_plus(url))
def index(): posts = [] for filename in os.listdir('posts'): title = urlsafe_b64decode(filename) posts.append({'title': title, 'url': url_quote_plus(title)}) return render_template('index.html', posts=posts)
def _dump(self, instance, only=None): # Always include at least the type and ID, regardless of what # the user requested. if only is not None: # TODO In Python 2.7 or later, this should be a set literal. only = set(only) | set(['type', 'id']) model = type(instance) try: inspected_instance = inspect(model) except NoInspectionAvailable: message = 'failed to get columns for model {0}'.format(model) raise SerializationException(instance, message=message) # Determine the columns to serialize as "attributes". # # This include plain old columns (like strings and integers, for # example), hybrid properties, and association proxies to scalar # collections (like a list of strings, for example). column_attrs = inspected_instance.column_attrs.keys() assoc_scalars = list(assoc_proxy_scalar_collections(model)) descriptors = inspected_instance.all_orm_descriptors.items() hybrid_columns = [k for k, d in descriptors if d.extension_type == HYBRID_PROPERTY] columns = column_attrs + assoc_scalars + hybrid_columns # Also include any attributes specified by the user. if self.additional_attributes is not None: columns += self.additional_attributes # Serialize each attribute, excluding those that should be excluded. attributes = {} foreign_key_columns = foreign_keys(model) pk_name = primary_key_for(model) for column in columns: if self._is_excluded(column, only=only): continue # Exclude column names that are blacklisted. if column.startswith('__') or column in COLUMN_BLACKLIST: continue # Exclude column names that are foreign keys (unless the # foreign key is the primary key for the model; this can # happen in the joined table inheritance database # configuration). if column in foreign_key_columns and column != pk_name: continue # Get the value for this column. Call it if it is callable. value = getattr(instance, column) if callable(value): value = value() # Attributes values that come from association proxy # collections need to be cast to plain old Python data types # so that the JSON serializer can handle them. if isinstance(value, _AssociationList): value = list(value) elif isinstance(value, _AssociationSet): value = set(value) elif isinstance(value, _AssociationDict): value = dict(value) # Serialize any date- or time-like objects that appear in # the attributes. # # TODO In Flask 0.11, the default JSON encoder for the Flask # application object does this automatically. Alternately, # the user could have set a smart JSON encoder on the Flask # application, which would cause these attributes to be # converted to strings when the Response object is created # (in the `jsonify` function, for example). However, we # should not rely on that JSON encoder since the user could # set any crazy encoder on the Flask application. if isinstance(value, (date, datetime, time)): value = value.isoformat() elif isinstance(value, timedelta): value = total_seconds(value) # Recursively serialize any object that appears in the # attributes. This may happen if, for example, the return # value of one of the callable functions is an instance of # another SQLAlchemy model class. # # This is a bit of a fragile test for whether the object # needs to be serialized: we simply check if the class of # the object is a mapped class. if is_mapped_class(type(value)): model_ = get_model(value) try: serializer = serializer_for(model_) serialized_val = serializer.serialize(value) except ValueError: # TODO Should this cause an exception, or fail # silently? See similar comments in `views/base.py`. # # raise SerializationException(instance) serialized_val = simple_serialize(value) # We only need the data from the JSON API document, not # the metadata. (So really the serializer is doing more # work than it needs to here.) value = serialized_val['data'] # Set this column's value in the attributes dictionary. attributes[column] = value # Get the ID and type of the resource. id_ = attributes.pop('id', None) type_ = collection_name(model) # Create the result dictionary and add the attributes. result = dict(id=id_, type=type_) if attributes: result['attributes'] = attributes # Add the self link unless it has been explicitly excluded. is_self_in_default = (self.default_fields is None or 'self' in self.default_fields) is_self_in_only = only is None or 'self' in only if is_self_in_default and is_self_in_only: instance_id = primary_key_value(instance) # `url_for` may raise a `BuildError` if the user has not created a # GET API endpoint for this model. In this case, we simply don't # provide a self link. # # TODO This might fail if the user has set the # `current_app.build_error_handler` attribute, in which case, the # exception may not be raised. try: path = url_for(model, instance_id, _method='GET') except BuildError: pass else: # HACK In order to support users using Python 2.7 with # the `future` compatibility library, we need to ensure # that both `request.url_root` and `path` are of the # same type. path = to_unicode(path) url = urljoin(request.url_root, path) result['links'] = dict(self=url) # # add any included methods # if include_methods is not None: # for method in include_methods: # if '.' not in method: # value = getattr(instance, method) # # Allow properties and static attributes in # # include_methods # if callable(value): # value = value() # result[method] = value # If the primary key is not named "id", we'll duplicate the # primary key under the "id" key. if pk_name != 'id': result['id'] = result['attributes'][pk_name] # TODO Same problem as above. # # In order to comply with the JSON API standard, primary keys must be # returned to the client as strings, so we convert it here. if 'id' in result: try: result['id'] = str(result['id']) except UnicodeEncodeError: result['id'] = url_quote_plus(result['id'].encode('utf-8')) # Serialize each relationship, excluding those that should be excluded. relationships = {} for r in get_relations(model): if not self._is_excluded(r, only=only): relationships[r] = create_relationship(model, instance, r) if relationships: result['relationships'] = relationships return result
def quoted_url(self): return url_quote_plus(self.url)
def inner(request, *args, **kwargs): for service in targets: if get_gaema_user(service): return func(request, *args, **kwargs) return redirect(url_for('gaema/select_service', targets='|'.join(targets), next_url=url_quote_plus(request.url)))
def create_lang_url(lang=None, url=None): from werkzeug.urls import url_quote_plus from kay.utils import url_for if not url: url = local.request.url return url_for("i18n/set_language", lang=lang, next=url_quote_plus(url))
def create_logout_url(self, url): return url_for("auth/logout", next=url_quote_plus(url))