本文整理汇总了Python中werkzeug.url_decode函数的典型用法代码示例。如果您正苦于以下问题:Python url_decode函数的具体用法?Python url_decode怎么用?Python url_decode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了url_decode函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_extended_fb_token
def get_extended_fb_token(access_token):
# print access_token
payload = {'client_id': FB_CLIENT_ID, 'client_secret': FB_CLIENT_SECRET, 'grant_type': 'fb_exchange_token', 'fb_exchange_token': access_token}
r = requests.get("https://graph.facebook.com/oauth/access_token", params=payload)
try:
access_token = url_decode(r.text).get('access_token')
except Exception as e:
print '(WARNING) Failed to parse retrieve long-lived access token', r.text
print 'EXPIRES: ' + url_decode(r.text).get('expires')
return access_token
示例2: test_url_decoding
def test_url_decoding():
"""Test the URL decoding"""
x = url_decode('foo=42&bar=23&uni=H%C3%A4nsel')
assert x['foo'] == '42'
assert x['bar'] == '23'
assert x['uni'] == u'Hänsel'
x = url_decode('foo=42;bar=23;uni=H%C3%A4nsel', separator=';')
assert x['foo'] == '42'
assert x['bar'] == '23'
assert x['uni'] == u'Hänsel'
x = url_decode('%C3%9Ch=H%C3%A4nsel', decode_keys=True)
assert x[u'Üh'] == u'Hänsel'
示例3: cse_demande
def cse_demande():
def mk_float(s):
s = s.strip()
return float(s) if s else 0
data = url_decode(request.data)
data['logement_gracieux'] = data['logement_gracieux'] == 'Oui'
data['logement_montant'] = mk_float(data['logement_montant'])
data['financement_famille'] = data['financement_famille'] == 'Oui'
data['financement_famille_montant'] = mk_float(data['financement_famille_montant'])
data['financement_autre'] = data['financement_autre'] == 'Oui'
data['financement_autre_montant'] = mk_float(data['financement_autre_montant'])
data['apl'] = data['apl'] == 'Oui'
data['apl_montant'] = mk_float(data['apl_montant'])
# data['boursier'] = data['boursier'] == 'Oui'
data['boursier_montant'] = mk_float(data['boursier_montant'])
print data.to_dict()
demande = DossierCSE(**data.to_dict())
demande.save()
return jsonify(result='saved')
示例4: parse_response
def parse_response(resp, content, strict=False, content_type=None):
"""
Parse the response returned by :meth:`OAuthRemoteApp.http_request`.
"""
ct = resp.headers.get('content-type')
if not ct and content.lower().strip().startswith('callback('):
ct = 'application/json'
if not ct:
ct = content_type
if not ct:
ct = 'application/json'
ct, options = parse_options_header(ct)
if ct in ('application/json', 'text/javascript'):
if content.lower().strip().startswith('callback('):
content = content.strip().replace('callback(', '', 1).strip("); ")
return json.loads(content)
if ct in ('application/xml', 'text/xml'):
return get_etree().fromstring(content)
if ct != 'application/x-www-form-urlencoded' and strict:
return content
charset = options.get('charset', 'utf-8')
return url_decode(content, charset=charset).to_dict()
示例5: __call__
def __call__(self, environ, start_response):
if '_method' in environ.get('QUERY_STRING', ''):
args = url_decode(environ['QUERY_STRING'])
method = args.get('_method')
if method:
method = method.encode('ascii', 'replace')
environ['REQUEST_METHOD'] = method
return self.app(environ, start_response)
# class MethodRewriteMiddleware(object):
# """Legacy Browser and HTTP REST Methods Support
# For HTML form use:
# <input type="hidden" name="_method" value="OPTIONS" />
# """
# HTTP_METHODS = ['GET', 'POST', 'PUT', 'DELETE',
# 'HEAD', 'OPTIONS',
# 'TRACE', 'CONNECT']
# def __init__(self, app, input_name='_method'):
# self.app = app
# self.input_name = input_name
# def __call__(self, environ, start_response):
# request = Request(environ)
if self.input_name in request.form:
method = request.form[self.input_name].upper()
if method in self.HTTP_METHODS:
environ['REQUEST_METHOD'] = method
return self.app(environ, start_response)
示例6: url_add
def url_add(url=None, **kwargs):
scheme, netloc, path, query, fragments = urlsplit(url or request.url)
params = url_decode(query)
for key, value in kwargs.items():
if not value in params.getlist(key):
params.add(key, value)
return Markup(urlunsplit((scheme, netloc, path, url_encode(params), fragments)))
示例7: url_equals
def url_equals(to_check):
if to_check[:4] != check_parts[:4]:
return False
args = url_decode(to_check[4])
for key, value in args.iteritems():
if check_query.get(key) != value:
return False
return True
示例8: __call__
def __call__(self, environ, start_response):
if "METHOD_OVERRIDE" in environ.get("QUERY_STRING", ""):
args = url_decode(environ["QUERY_STRING"])
method = args.get("__METHOD_OVERRIDE__")
if method:
method = method.encode("ascii", "replace")
environ["REQUEST_METHOD"] = method
return self.app(environ, start_response)
示例9: in_url
def in_url(*args, **kwargs):
scheme, netloc, path, query, fragments = urlsplit(request.url)
params = url_decode(query)
return (
all(arg in params for arg in args) and
all(key in params and params[key] == value
for key, value in kwargs.items())
)
示例10: url_rewrite
def url_rewrite(url=None, **kwargs):
scheme, netloc, path, query, fragments = urlsplit(url or request.url)
params = url_decode(query)
for key, value in kwargs.items():
params.setlist(key,
value if isinstance(value, (list, tuple)) else [value])
return Markup(urlunsplit((scheme, netloc, path, url_encode(params),
fragments)))
示例11: __call__
def __call__(self, environ, start_response):
if 'METHOD_OVERRIDE' in environ.get('QUERY_STRING', ''):
args = url_decode(environ['QUERY_STRING'])
method = args.get('__METHOD_OVERRIDE__')
if method:
method = method.encode('ascii', 'replace')
environ['REQUEST_METHOD'] = method
return self.app(environ, start_response)
示例12: __call__
def __call__(self, environ, start_response):
if '__METHOD__' in environ.get('QUERY_STRING', ''):
args = url_decode(environ['QUERY_STRING'])
method = args.get('__METHOD__').upper()
if method in ['GET', 'POST', 'PUT', 'DELETE']:
method = method.encode('ascii', 'replace')
environ['REQUEST_METHOD'] = method
return self.app(environ, start_response)
示例13: get_redirect_target
def get_redirect_target(self, invalid_targets=()):
"""Check the request and get the redirect target if possible.
If not this function returns just `None`. The return value of this
function is suitable to be passed to `redirect`.
"""
check_target = self.values.get('_redirect_target') or \
self.values.get('next') or \
self.referrer
# if there is no information in either the form data
# or the wsgi environment about a jump target we have
# to use the target url
if not check_target:
return
# otherwise drop the leading slash
check_target = check_target.lstrip('/')
root_url = self.url_root
root_parts = urlparse(root_url)
check_parts = urlparse(urljoin(root_url, check_target))
check_query = url_decode(check_parts[4])
def url_equals(to_check):
if to_check[:4] != check_parts[:4]:
return False
args = url_decode(to_check[4])
for key, value in args.iteritems():
if check_query.get(key) != value:
return False
return True
# if the jump target is on a different server we probably have
# a security problem and better try to use the target url.
# except the host is whitelisted in the config
if root_parts[:2] != check_parts[:2]:
host = check_parts[1].split(':', 1)[0]
for rule in settings.ALLOWED_REDIRECTS:
if fnmatch(host, rule):
break
else:
return
# if the jump url is the same url as the current url we've had
# a bad redirect before and use the target url to not create a
# infinite redirect.
if url_equals(urlparse(self.url)):
return
# if the `check_target` is one of the invalid targets we also
# fall back.
for invalid in invalid_targets:
if url_equals(urlparse(urljoin(root_url, invalid))):
return
return check_target
示例14: create_engine
def create_engine(uri, relative_to=None, debug=False):
"""Create a new engine. This works a bit like SQLAlchemy's
`create_engine` with the difference that it automaticaly set's MySQL
engines to 'utf-8', and paths for SQLite are relative to the path
provided as `relative_to`. Also hooks in LookLively to catch MySQL's
weird way of connection termination without termination.
Furthermore the engine is created with `convert_unicode` by default.
"""
# This is a good idea in any case
options = {'convert_unicode': True}
# special case sqlite. We want nicer urls for that one.
if uri.startswith('sqlite:'):
match = _sqlite_re.match(uri)
if match is None:
raise ArgumentError('Could not parse rfc1738 URL')
database, query = match.groups()
if database is None:
database = ':memory:'
elif relative_to is not None:
database = path.join(relative_to, database)
if query:
query = url_decode(query).to_dict()
else:
query = {}
info = URL('sqlite', database=database, query=query)
else:
info = make_url(uri)
# if mysql is the database engine and no connection encoding is
# provided we set it to utf-8
if info.drivername == 'mysql':
info.query.setdefault('charset', 'utf8')
options['listeners'] = [LookLively()]
# alternative pool sizes / recycle settings and more. These are
# interpreter wide and not from the config for the following reasons:
#
# - system administrators can set it independently from the webserver
# configuration via SetEnv and friends.
# - this setting is deployment dependent should not affect a development
# server for the same instance or a development shell
for key in 'pool_size', 'pool_recycle', 'pool_timeout':
value = os.environ.get("PYCLANSPHERE_" + key.upper())
if value is not None:
options[key] = int(value)
# if debugging is enabled, hook the ConnectionDebugProxy in
if debug:
options['proxy'] = ConnectionDebugProxy()
return sqlalchemy.create_engine(info, **options)
示例15: insert_param_url_query_str
def insert_param_url_query_str(url_query_string, param_name, param_val):
"""
Given an url query string this function:
appends a new instance of param_name containing param_val (it doesn't remove existing ones)
"""
if not param_name or not param_val:
return url_query_string
query_params = url_decode(url_query_string)
query_params.update({param_name:param_val})
return url_encode(query_params)