本文整理汇总了Python中itsdangerous.Signer.get_signature方法的典型用法代码示例。如果您正苦于以下问题:Python Signer.get_signature方法的具体用法?Python Signer.get_signature怎么用?Python Signer.get_signature使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类itsdangerous.Signer
的用法示例。
在下文中一共展示了Signer.get_signature方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: validate_fingerprints
# 需要导入模块: from itsdangerous import Signer [as 别名]
# 或者: from itsdangerous.Signer import get_signature [as 别名]
def validate_fingerprints(fp_secret_key, fp_salt, client_ip_fingerprint, browser_fingerprint, client_ip, user_agent,
accept_language):
is_valid = True
signer = Signer(fp_secret_key, fp_salt)
logging.debug('client_ip_fingerprint: %s', client_ip_fingerprint)
calculated_client_ip_fingerprint = signer.get_signature(client_ip)
logging.debug('calculated_client_ip_fingerprint: %s', calculated_client_ip_fingerprint)
if calculated_client_ip_fingerprint != client_ip_fingerprint:
logging.warn('Client IP does not match fingerprint in signature')
is_valid = False
# TODO:
# Uncomment return line below until atmobeta sends the right fingerprint signature.
# Just ignore fingerprint for now.
return is_valid
browser_fingerprint_input = ''.join([
user_agent,
accept_language])
logging.debug('browser_fingerprint_input: %s', browser_fingerprint_input)
logging.debug('browser_fingerprint: %s', browser_fingerprint)
calculated_browser_fingerprint = signer.get_signature(browser_fingerprint_input)
logging.debug('calculated_browser_fingerprint: %s', calculated_browser_fingerprint)
if calculated_browser_fingerprint != browser_fingerprint:
logging.warn('Browser fingerprint does not match calculated fingerprint')
is_valid = False
return is_valid
示例2: build_url
# 需要导入模块: from itsdangerous import Signer [as 别名]
# 或者: from itsdangerous.Signer import get_signature [as 别名]
def build_url(self, local_path, **kwargs):
local_path = local_path.strip('/')
for key in 'background mode width height quality format padding'.split():
if key in kwargs:
kwargs[key[0]] = kwargs.pop(key)
# Remote URLs are encoded into the query.
parsed = urlparse(local_path)
if parsed.netloc:
kwargs['u'] = local_path
local_path = 'remote'
# Local ones are not.
else:
abs_path = self.find_img(local_path)
if abs_path:
kwargs['v'] = encode_int(int(os.path.getmtime(abs_path)))
# Sign the query.
public_kwargs = ((k, v) for k, v in kwargs.iteritems() if not k.startswith('_'))
query = urlencode(sorted(public_kwargs), True)
signer = Signer(current_app.secret_key)
sig = signer.get_signature('%s?%s' % (local_path, query))
return '%s/%s?%s&s=%s' % (
current_app.config['IMAGES_URL'],
local_path,
query,
sig,
)
示例3: build_url
# 需要导入模块: from itsdangerous import Signer [as 别名]
# 或者: from itsdangerous.Signer import get_signature [as 别名]
def build_url(self, local_path, **kwargs):
# Make the path relative.
local_path = local_path.strip('/')
# We complain when we see non-normalized paths, as it is a good
# indicator that unsanitized data may be getting through.
# Mutating the scheme syntax to match is a little gross, but it works
# for today.
norm_path = os.path.normpath(local_path)
if local_path.replace('://', ':/') != norm_path or norm_path.startswith('../'):
raise ValueError('path is not normalized')
for key in 'background mode width height quality format padding'.split():
if key in kwargs:
kwargs[key[0]] = kwargs.pop(key)
# Remote URLs are encoded into the query.
parsed = urlparse(local_path)
if parsed.scheme or parsed.netloc:
if parsed.scheme not in ALLOWED_SCHEMES:
raise ValueError('scheme %r is not allowed' % parsed.scheme)
kwargs['u'] = local_path
local_path = 'remote'
# Local ones are not.
else:
abs_path = self.find_img(local_path)
if abs_path:
kwargs['v'] = encode_int(int(os.path.getmtime(abs_path)))
# Sign the query.
public_kwargs = ((k, v) for k, v in kwargs.iteritems() if not k.startswith('_'))
query = urlencode(sorted(public_kwargs), True)
signer = Signer(current_app.secret_key)
sig = signer.get_signature('%s?%s' % (local_path, query))
return '%s/%s?%s&s=%s' % (
current_app.config['IMAGES_URL'],
urlquote(local_path),
query,
sig,
)
示例4: handle_request
# 需要导入模块: from itsdangerous import Signer [as 别名]
# 或者: from itsdangerous.Signer import get_signature [as 别名]
def handle_request(self, path):
# Verify the signature.
query = dict(request.args.iteritems())
old_sig = str(query.pop('s', None))
if not old_sig:
abort(404)
signer = Signer(current_app.secret_key)
new_sig = signer.get_signature('%s?%s' % (path, urlencode(sorted(query.iteritems()), True)))
if not constant_time_compare(old_sig, new_sig):
abort(404)
# Expand kwargs.
query = dict((SHORT_TO_LONG.get(k, k), v) for k, v in query.iteritems())
remote_url = query.get('url')
if remote_url:
# This is redundant for newly built URLs, but not for those which
# have already been generated and cached.
parsed = urlparse(remote_url)
if parsed.scheme not in ALLOWED_SCHEMES:
abort(404)
# Download the remote file.
makedirs(current_app.config['IMAGES_CACHE'])
path = os.path.join(
current_app.config['IMAGES_CACHE'],
hashlib.md5(remote_url).hexdigest() + os.path.splitext(parsed.path)[1]
)
if not os.path.exists(path):
log.info('downloading %s' % remote_url)
tmp_path = path + '.tmp-' + str(os.getpid())
fh = open(tmp_path, 'wb')
fh.write(urlopen(remote_url).read())
fh.close()
call(['mv', tmp_path, path])
else:
path = self.find_img(path)
if not path:
abort(404) # Not found.
raw_mtime = os.path.getmtime(path)
mtime = datetime.datetime.utcfromtimestamp(raw_mtime)
# log.debug('last_modified: %r' % mtime)
# log.debug('if_modified_since: %r' % request.if_modified_since)
if request.if_modified_since and request.if_modified_since >= mtime:
return '', 304
mode = query.get('mode')
transform = query.get('transform')
transform = re.split(r'[;,_/ ]', transform) if transform else None
background = query.get('background')
width = query.get('width')
width = int(width) if width else None
height = query.get('height')
height = int(height) if height else None
quality = query.get('quality')
quality = int(quality) if quality else 75
format = (query.get('format', '') or os.path.splitext(path)[1][1:] or 'jpeg').lower()
format = {'jpg' : 'jpeg'}.get(format, format)
has_version = 'version' in query
use_cache = query.get('cache', True)
if use_cache:
cache_key_parts = [path, mode, width, height, quality, format, background]
if transform:
cache_key_parts.append(transform)
cache_key = hashlib.md5(repr(tuple(cache_key_parts))).hexdigest()
cache_dir = os.path.join(current_app.config['IMAGES_CACHE'], cache_key[:2])
cache_path = os.path.join(cache_dir, cache_key + '.' + format)
cache_mtime = os.path.getmtime(cache_path) if os.path.exists(cache_path) else None
mimetype = 'image/%s' % format
cache_timeout = 31536000 if has_version else current_app.config['IMAGES_MAX_AGE']
if not use_cache or not cache_mtime or cache_mtime < raw_mtime:
log.info('resizing %r for %s' % (path, query))
img = image.open(path)
img = self.resize(img,
width=width,
height=height,
mode=mode,
background=background,
transform=transform,
)
if not use_cache:
fh = StringIO()
img.save(fh, format, quality=quality)
return fh.getvalue(), 200, [
('Content-Type', mimetype),
('Cache-Control', cache_timeout),
]
makedirs(cache_dir)
#.........这里部分代码省略.........
示例5: build_url
# 需要导入模块: from itsdangerous import Signer [as 别名]
# 或者: from itsdangerous.Signer import get_signature [as 别名]
def build_url(self, local_path, **kwargs):
# Make the path relative.
local_path = local_path.strip('/')
# We complain when we see non-normalized paths, as it is a good
# indicator that unsanitized data may be getting through.
# Mutating the scheme syntax to match is a little gross, but it works
# for today.
norm_path = os.path.normpath(local_path)
if local_path.replace('://', ':/') != norm_path or norm_path.startswith('../'):
raise ValueError('path is not normalized')
external = kwargs.pop('external', None) or kwargs.pop('_external', None)
scheme = kwargs.pop('scheme', None)
if scheme and not external:
raise ValueError('cannot specify scheme without external=True')
if kwargs.get('_anchor'):
raise ValueError('images have no _anchor')
if kwargs.get('_method'):
raise ValueError('images have no _method')
# Remote URLs are encoded into the query.
parsed = urlparse(local_path)
if parsed.scheme or parsed.netloc:
if parsed.scheme not in ALLOWED_SCHEMES:
raise ValueError('scheme %r is not allowed' % parsed.scheme)
kwargs['url'] = local_path
local_path = '_' # Must be something.
# Local ones are not.
else:
abs_path = self.find_img(local_path)
if abs_path:
kwargs['version'] = encode_int(int(os.path.getmtime(abs_path)))
# Prep the cache
cache = kwargs.pop('cache', True)
if not cache:
kwargs['cache'] = ''
# Prep the transform.
transform = kwargs.get('transform')
if transform:
if isinstance(transform, basestring):
transform = re.split(r'[,;:_ ]', transform)
# This is a strange character, but we won't be using it and it
# doesn't escape.
kwargs['transform'] = '_'.join(map(str, transform))
# Sign the query.
public_kwargs = (
(LONG_TO_SHORT.get(k, k), v)
for k, v in kwargs.iteritems()
if not k.startswith('_')
)
query = urlencode(sorted(public_kwargs), True)
signer = Signer(current_app.secret_key)
sig = signer.get_signature('%s?%s' % (local_path, query))
url = '%s/%s?%s&s=%s' % (
current_app.config['IMAGES_URL'],
urlquote(local_path),
query,
sig,
)
if external:
url = '%s://%s%s/%s' % (
scheme or request.scheme,
request.host,
request.script_root,
url.lstrip('/')
)
return url
示例6: handle_request
# 需要导入模块: from itsdangerous import Signer [as 别名]
# 或者: from itsdangerous.Signer import get_signature [as 别名]
def handle_request(self, path):
query = dict(request.args.iteritems())
if current_app.secret_key != 'nokey' :
# Verify the signature.
old_sig = str(query.pop('s', None))
if not old_sig:
abort(404)
signer = Signer(current_app.secret_key)
new_sig = signer.get_signature('%s?%s' % (path, urlencode(sorted(query.iteritems()), True)))
if not constant_time_compare(old_sig, new_sig):
abort(404)
remote_url = query.get('u')
if remote_url:
# This is redundant for newly built URLs, but not for those which
# have already been generated and cached.
parsed = urlparse(remote_url)
if parsed.scheme not in ALLOWED_SCHEMES:
abort(404)
# Download the remote file.
makedirs(current_app.config['IMAGES_CACHE'])
path = os.path.join(
current_app.config['IMAGES_CACHE'],
hashlib.md5(remote_url).hexdigest() + os.path.splitext(remote_url)[1]
)
if not os.path.exists(path):
log.info('downloading %s' % remote_url)
tmp_path = path + '.tmp-' + str(os.getpid())
fh = open(tmp_path, 'wb')
fh.write(urlopen(remote_url).read())
fh.close()
call(['mv', tmp_path, path])
else:
path = self.find_img(path)
if not path:
abort(404) # Not found.
raw_mtime = os.path.getmtime(path)
mtime = datetime.datetime.utcfromtimestamp(raw_mtime)
# log.debug('last_modified: %r' % mtime)
# log.debug('if_modified_since: %r' % request.if_modified_since)
if request.if_modified_since and request.if_modified_since >= mtime:
return '', 304
mode = query.get('m')
background = query.get('b')
width = query.get('w')
width = int(width) if width else None
height = query.get('h')
height = int(height) if height else None
quality = query.get('q')
quality = int(quality) if quality else 75
format = query.get('f', '').lower() or os.path.splitext(path)[1][1:] or 'jpeg'
format = {'jpg' : 'jpeg'}.get(format, format)
has_version = 'v' in query
cache_key = hashlib.md5(repr((
path, mode, width, height, quality, format, background
))).hexdigest()
cache_dir = os.path.join(current_app.config['IMAGES_CACHE'], cache_key[:2])
cache_path = os.path.join(cache_dir, cache_key + '.' + format)
cache_mtime = os.path.getmtime(cache_path) if os.path.exists(cache_path) else None
if not cache_mtime or cache_mtime < raw_mtime:
log.info('resizing %r for %s' % (path, query))
img = image.open(path)
img = self.resize(img, width=width, height=height, mode=mode, background=background)
makedirs(cache_dir)
cache_file = open(cache_path, 'wb')
img.save(cache_file, format, quality=quality)
cache_file.close()
return send_file(cache_path,
mimetype='image/%s' % format,
cache_timeout=31536000 if has_version else current_app.config['IMAGES_MAX_AGE'],
)
示例7: generate_signature
# 需要导入模块: from itsdangerous import Signer [as 别名]
# 或者: from itsdangerous.Signer import get_signature [as 别名]
def generate_signature(signing_secret_key, signing_salt, fp_secret_key, fp_salt, client_ip, vm_ip, user_agent,
accept_language):
""" Generate test signatures.
Notes from @lenards:
1. Creating the signed value:
SIGNED_SERIALIZER = URLSafeTimedSerializer(
settings.WEB_DESKTOP['signing']['SECRET_KEY'],
salt=settings.WEB_DESKTOP['signing']['SALT'])
SIGNER = Signer(
settings.WEB_DESKTOP['fingerprint']['SECRET_KEY'],
salt=settings.WEB_DESKTOP['fingerprint']['SALT'])
client_ip = '127.0.0.1'
client_ip_fingerprint = SIGNER.get_signature(client_ip)
browser_fingerprint = SIGNER.get_signature(''.join([
request.META['HTTP_USER_AGENT'],
request.META['HTTP_ACCEPT'],
request.META['HTTP_ACCEPT_ENCODING'],
request.META['HTTP_ACCEPT_LANGUAGE']]))
sig = SIGNED_SERIALIZER.dumps([ip_address,
client_ip_fingerprint,
browser_fingerprint])
2. Test curl request:
curl 'https://api.atmo.dev/api/v1/maintenance' -H 'Origin: https://ui.atmo.dev' -H 'Accept-Encoding: gzip, deflate, sdch' -H 'Accept-Language: en-US,en;q=0.8' -H 'Authorization: Token fe5ce63617af95898fa6973774c64f81' -H 'Content-Type: application/json' -H 'Accept: application/json, text/javascript, */*; q=0.01' -H 'Referer: https://ui.atmo.dev/application/projects/3277/instances/25286' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36' -H 'Connection: keep-alive' --compressed --insecure
3. Should generate a redirect like:
https://kurtz.iplantcollaborative.org/?sig=WyIxMjguMTk2LjY0LjIxNCIsIll2OUtONXhZTGcxYzdzU2tYQ0trb2x6RnBRayIsIlZkS28yemhidVJpQ3Z6WDZmTnNJRUVWdWcydyJd.CfsDWA.1tUUGb1772CZPn5IlttHM82qiuA
4. Which contains values:
In [10]: sig = 'WyIxMjguMTk2LjY0LjIxNCIsIll2OUtONXhZTGcxYzdzU2tYQ0trb2x6RnBRayIsIlZkS28yemhidVJpQ3Z6WDZmTnNJRUVWdWcydyJd.CfsDWA.1tUUGb1772CZPn5IlttHM82qiuA'
In [11]: usts.loads(sig)
Out[11]:
[u'128.196.64.214',
u'Yv9KN5xYLg1c7sSkXCKkolzFpQk',
u'VdKo2zhbuRiCvzX6fNsIEEVug2w']
from flask import Flask, request
test_sig = generate_signature('secrets-things-that-arenot-so-secret',
'i-like-the-idea-of-a-salt',
'128.196.64.214',
request)
"""
usts = URLSafeTimedSerializer(
signing_secret_key,
salt=signing_salt)
signer = Signer(
fp_secret_key,
salt=fp_salt)
client_ip_fingerprint = signer.get_signature(client_ip)
logging.debug('client_ip: %s', client_ip)
logging.debug('client_ip_fingerprint: %s', client_ip_fingerprint)
browser_fingerprint_input = ''.join([
user_agent,
accept_language])
logging.debug('browser_fingerprint_input: %s', browser_fingerprint_input)
browser_fingerprint = signer.get_signature(browser_fingerprint_input)
logging.debug('browser_fingerprint: %s', browser_fingerprint)
sig = usts.dumps([vm_ip, client_ip_fingerprint, browser_fingerprint])
return sig
示例8: handle_request
# 需要导入模块: from itsdangerous import Signer [as 别名]
# 或者: from itsdangerous.Signer import get_signature [as 别名]
def handle_request(self, path):
# Verify the signature.
query = dict(iteritems(request.args))
old_sig = str(query.pop('s', None))
if not old_sig:
abort(404)
signer = Signer(current_app.secret_key)
new_sig = signer.get_signature('%s?%s' % (path, urlencode(sorted(iteritems(query)), True)))
if not constant_time_compare(str(old_sig), str(new_sig)):
log.warning("Signature mismatch: url's {} != expected {}".format(old_sig, new_sig))
abort(404)
# Expand kwargs.
query = dict((SHORT_TO_LONG.get(k, k), v) for k, v in iteritems(query))
remote_url = query.get('url')
if remote_url:
# This is redundant for newly built URLs, but not for those which
# have already been generated and cached.
parsed = urlparse(remote_url)
if parsed.scheme not in ALLOWED_SCHEMES:
abort(404)
# Download the remote file.
makedirs(current_app.config['IMAGES_CACHE'])
path = os.path.join(
current_app.config['IMAGES_CACHE'],
hashlib.md5(encode_str(remote_url)).hexdigest() + os.path.splitext(parsed.path)[1]
)
if not os.path.exists(path):
log.info('downloading %s' % remote_url)
tmp_path = path + '.tmp-' + str(os.getpid())
try:
remote_file = urlopen(remote_url).read()
except HTTPError as e:
# abort with remote error code (403 or 404 most times)
# log.debug('HTTP Error: %r' % e)
abort(e.code)
else:
fh = open(tmp_path, 'wb')
fh.write(remote_file)
fh.close()
call(['mv', tmp_path, path])
else:
path = self.find_img(path)
if not path:
abort(404) # Not found.
raw_mtime = os.path.getmtime(path)
mtime = datetime.datetime.utcfromtimestamp(raw_mtime).replace(microsecond=0)
# log.debug('last_modified: %r' % mtime)
# log.debug('if_modified_since: %r' % request.if_modified_since)
if request.if_modified_since and request.if_modified_since >= mtime:
return '', 304
mode = query.get('mode')
transform = query.get('transform')
transform = re.split(r'[;,_/ ]', transform) if transform else None
background = query.get('background')
width = query.get('width')
width = int(width) if width else None
height = query.get('height')
height = int(height) if height else None
quality = query.get('quality')
quality = int(quality) if quality else 75
format = (query.get('format', '') or os.path.splitext(path)[1][1:] or 'jpeg').lower()
format = {'jpg' : 'jpeg'}.get(format, format)
has_version = 'version' in query
use_cache = query.get('cache', True)
enlarge = query.get('enlarge', False)
sharpen = query.get('sharpen')
sharpen = re.split(r'[+:;,_/ ]', sharpen) if sharpen else None
if use_cache:
# The parts in this initial list were parameters cached in version 1.
# In order to avoid regenerating all images when a new feature is
# added, we append (feature_name, value) tuples to the end.
cache_key_parts = [path, mode, width, height, quality, format, background]
if transform:
cache_key_parts.append(('transform', transform))
if sharpen:
cache_key_parts.append(('sharpen', sharpen))
if enlarge:
cache_key_parts.append(('enlarge', enlarge))
cache_key = hashlib.md5(repr(tuple(cache_key_parts)).encode('utf-8')).hexdigest()
cache_dir = os.path.join(current_app.config['IMAGES_CACHE'], cache_key[:2])
cache_path = os.path.join(cache_dir, cache_key + '.' + format)
cache_mtime = os.path.getmtime(cache_path) if os.path.exists(cache_path) else None
mimetype = 'image/%s' % format
cache_timeout = 31536000 if has_version else current_app.config['IMAGES_MAX_AGE']
#.........这里部分代码省略.........
示例9: build_url
# 需要导入模块: from itsdangerous import Signer [as 别名]
# 或者: from itsdangerous.Signer import get_signature [as 别名]
def build_url(self, local_path, **kwargs):
# Make the path relative.
local_path = local_path.strip('/')
# We complain when we see non-normalized paths, as it is a good
# indicator that unsanitized data may be getting through.
# Mutating the scheme syntax to match is a little gross, but it works
# for today.
norm_path = os.path.normpath(local_path)
if local_path.replace('://', ':/') != norm_path or norm_path.startswith('../'):
raise ValueError('path is not normalized')
external = kwargs.pop('external', None) or kwargs.pop('_external', None)
scheme = kwargs.pop('scheme', None)
if scheme and not external:
raise ValueError('cannot specify scheme without external=True')
if kwargs.get('_anchor'):
raise ValueError('images have no _anchor')
if kwargs.get('_method'):
raise ValueError('images have no _method')
# Remote URLs are encoded into the query.
parsed = urlparse(local_path)
if parsed.scheme or parsed.netloc:
if parsed.scheme not in ALLOWED_SCHEMES:
raise ValueError('scheme %r is not allowed' % parsed.scheme)
kwargs['url'] = local_path
local_path = '_' # Must be something.
# Local ones are not.
else:
abs_path = self.find_img(local_path)
if abs_path:
kwargs['version'] = encode_int(int(os.path.getmtime(abs_path)))
# Prep the cache flag, which defaults to True.
cache = kwargs.pop('cache', True)
if not cache:
kwargs['cache'] = ''
# Prep the enlarge flag, which defaults to False.
enlarge = kwargs.pop('enlarge', False)
if enlarge:
kwargs['enlarge'] = '1'
# Prep the transform, which is a set of delimited strings.
transform = kwargs.get('transform')
if transform:
if isinstance(transform, string_types):
transform = re.split(r'[,;:_ ]', transform)
# We replace delimiters with underscores, and percent with p, since
# these won't need escaping.
kwargs['transform'] = '_'.join(str(x).replace('%', 'p') for x in transform)
# Sign the query.
# Collapse to a dict first so that if we accidentally have two of the
# same kwarg (e.g. used `hidpi_sharpen` and `usm` which both turn into `usm`).
public_kwargs = {
LONG_TO_SHORT.get(k, k): v
for k, v in iteritems(kwargs)
if v is not None and not k.startswith('_')
}
query = urlencode(sorted(iteritems(public_kwargs)), True)
signer = Signer(current_app.secret_key)
sig = signer.get_signature('%s?%s' % (local_path, query))
url = '%s/%s?%s&s=%s' % (
current_app.config['IMAGES_URL'],
urlquote(local_path, "/$-_.+!*'(),"),
query,
sig,
)
if external:
url = '%s://%s%s/%s' % (
scheme or request.scheme,
request.host,
request.script_root,
url.lstrip('/')
)
return url