本文整理汇总了Python中urllib.parse.quote函数的典型用法代码示例。如果您正苦于以下问题:Python quote函数的具体用法?Python quote怎么用?Python quote使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了quote函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_api_filter_by_milestone__estimated_start_and_end
def test_api_filter_by_milestone__estimated_start_and_end(client, field_name):
user = f.UserFactory.create()
project = f.ProjectFactory.create(owner=user)
role = f.RoleFactory.create(project=project)
f.MembershipFactory.create(
project=project, user=user, role=role, is_admin=True
)
milestone = f.MilestoneFactory.create(project=project, owner=user)
assert hasattr(milestone, field_name)
date = getattr(milestone, field_name)
before = (date - timedelta(days=1)).isoformat()
after = (date + timedelta(days=1)).isoformat()
client.login(milestone.owner)
expections = {
field_name + "__gte=" + quote(before): 1,
field_name + "__gte=" + quote(after): 0,
field_name + "__lte=" + quote(before): 0,
field_name + "__lte=" + quote(after): 1
}
for param, expection in expections.items():
url = reverse("milestones-list") + "?" + param
response = client.get(url)
number_of_milestones = len(response.data)
assert response.status_code == 200
assert number_of_milestones == expection, param
if number_of_milestones > 0:
assert response.data[0]["slug"] == milestone.slug
示例2: renderClusterHtml
def renderClusterHtml(clust,width,height,scopeFile=None):
html = ''
scopeHtml = getScopeHtml(scopeFile)
header = '''
<HTML>
<title>Web Application Catalog</title>
<BODY>
<h1>Web Application Catalog</h1>
'''
if(scopeHtml is not None):
header = header+scopeHtml
header = header + '''
<script type="text/javascript" src="popup.js"></script>
<LINK href="style.css" rel="stylesheet" type="text/css">
<h3>Catalog:</h3>
'''
html = html+'<table border="1">'
for cluster,siteList in clust.iteritems():
html=html+'<TR>'
screenshotName = quote(siteList[0][0:-4], safe='')
html=html+'<TR><TD><img src="'+screenshotName+'png" width='+str(width)+' height='+str(height)+'/></TD></TR>'
for site in siteList:
screenshotName = quote(site[0:-5], safe='')
html=html+'<TD onmouseout="clearPopup()" onmouseover="popUp(event,\''+screenshotName+'.png\');"><a href="'+unquote(unquote(screenshotName[4:]).decode("utf-8")).decode("utf-8")+'">'+unquote(unquote(screenshotName[4:]).decode("utf-8")).decode("utf-8")+'</a></TD>'
html=html+'</TR>'
html=html+'</table>'
footer = '</BODY></HTML>'
return [header,html,footer]
示例3: amz_cano_querystring
def amz_cano_querystring(qs):
"""
Parse and format querystring as per AWS4 auth requirements.
Perform percent quoting as needed.
qs -- querystring
"""
safe_qs_amz_chars = '&=+'
safe_qs_unresvd = '-_.~'
# If Python 2, switch to working entirely in str
# as quote() has problems with Unicode
if PY2:
qs = qs.encode('utf-8')
safe_qs_amz_chars = safe_qs_amz_chars.encode()
safe_qs_unresvd = safe_qs_unresvd.encode()
qs = unquote(qs)
space = b' ' if PY2 else ' '
qs = qs.split(space)[0]
qs = quote(qs, safe=safe_qs_amz_chars)
qs_items = {}
for name, vals in parse_qs(qs, keep_blank_values=True).items():
name = quote(name, safe=safe_qs_unresvd)
vals = [quote(val, safe=safe_qs_unresvd) for val in vals]
qs_items[name] = vals
qs_strings = []
for name, vals in qs_items.items():
for val in vals:
qs_strings.append('='.join([name, val]))
qs = '&'.join(sorted(qs_strings))
if PY2:
qs = unicode(qs)
return qs
示例4: _list_dir
def _list_dir(self, path):
"""
Show a directory listing.
"""
entries = os.listdir(path)
dir_entries = [[[
'..',
quote(os.path.normpath(os.path.join(path, '..')), safe='')
]]]
for name in entries:
if name.startswith('.'):
# skip invisible files/directories
continue
fullname = os.path.join(path, name)
displayname = linkname = name
# Append / for directories or @ for symbolic links
if os.path.isdir(fullname):
displayname += '/'
if os.path.islink(fullname):
displayname += '@'
dir_entries.append(
[[displayname, quote(os.path.join(path, linkname), safe='')]])
self.render(
'dir.html', dir_name=path, dir_entries=dir_entries)
示例5: user_agent_username
def user_agent_username(username=None):
"""
Reduce username to a representation permitted in HTTP headers.
To achieve that, this function:
1) replaces spaces (' ') with '_'
2) encodes the username as 'utf-8' and if the username is not ASCII
3) URL encodes the username if it is not ASCII, or contains '%'
"""
if not username:
return ''
username = username.replace(' ', '_') # Avoid spaces or %20.
try:
username.encode('ascii') # just test, but not actually use it
except UnicodeEncodeError:
pass
else:
# % is legal in the default $wgLegalTitleChars
# This is so that ops know the real pywikibot will not
# allow a useragent in the username to allow through a hand-coded
# percent-encoded value.
if '%' in username:
return quote(username)
else:
return username
username = quote(username.encode('utf-8'))
return username
示例6: upload
def upload(recipe, result, server, key=None):
'''upload build'''
branch = result.pop('branch', 'unknown')
# FIXME: use urljoin
request = Request('{}/build/{}/{}/{}'.format(
server, quote(recipe['name']), quote(branch),
quote('{} {}'.format(sys.platform, platform.machine()))))
request.add_header('Content-Type', 'application/json')
if key is not None:
request.add_header('Authorization', key)
try:
urlopen(request, json.dumps(result).encode('UTF-8'))
except HTTPError as exc:
logging.error("The server couldn't fulfill the request.")
logging.error('Error code: %s', exc.code)
if exc.code == 400:
logging.error("Client is broken, wrong syntax given to server")
elif exc.code == 401:
logging.error("Wrong key provided for project.")
logging.error("%s", exc.read())
return False
except URLError as exc:
logging.error('Failed to reach a server.')
logging.error('Reason: %s', exc.reason)
return False
return True
示例7: redirect
def redirect(self, url, permanent=False, anchor=""):
"""Cause a redirection without raising an error
- accepts full URL (eg http://whatever...) or URI (eg /versere/Account/2/view)
- retains anchor and messages
"""
if type(url) == bytes:
url = str(url, 'utf8')
url = str(url).strip(
) #safety first - defend against unicode, which will break both http and string matching
# print "REDIRECT:",url
if not url.startswith('http'):
url = "http://%s%s" % (self.get_host(), url)
# print "REDIRECT full url:",url or "no url", " == anchor: ", anchor or "no anchor"
if '#' in url:
url, anchor = url.rsplit('#', 1)
ats = self.error and ['error=%s' % quote(self.error)] or []
if self.warning:
ats.append('warning=%s' % quote(self.warning))
if self.message:
ats.append('message=%s' % quote(self.message))
q = url.find('?') > -1 and "&" or "?"
ats = ats and (q + '&'.join(ats)) or ""
url = '%s%s%s%s' % (url, ats, anchor and '#' or '', anchor)
# do the redirect
self.request.setResponseCode(permanent and 301 or 302, None)
if type(url) != bytes:
url = bytes(bytearray(url, 'utf8'))
self.request.setHeader('Location', url)
return " " #return a True blank string, to indicate we have a page result
示例8: test_filter_within
def test_filter_within(self):
golden_gate_park_json = """{"type": "MultiPolygon", "coordinates": [[[[-122.511067, 37.771276], [-122.510037, 37.766391], [-122.510037, 37.763813], [-122.456822, 37.765848], [-122.452960, 37.766459], [-122.454848, 37.773990], [-122.475362, 37.773040], [-122.511067, 37.771276]]]]}"""
# Get points
connection = self.get_connection()
connection.request('GET', '/api/v1/geonotes/?points__within=%s' % quote(golden_gate_park_json), headers={'Accept': 'application/json'})
response = connection.getresponse()
connection.close()
self.assertEqual(response.status, 200)
data = json.loads(response.read().decode('utf-8'))
# We get back the points inside Golden Gate park!
self.assertEqual(data['objects'][0]['content'], "Wooo two points inside Golden Gate park")
self.assertEqual(data['objects'][0]['points']['type'], 'MultiPoint')
self.assertAlmostEqual(data['objects'][0]['points']['coordinates'][0][0], -122.475233, places=5)
self.assertAlmostEqual(data['objects'][0]['points']['coordinates'][0][1], 37.768616, places=5)
self.assertAlmostEqual(data['objects'][0]['points']['coordinates'][1][0], -122.470416, places=5)
self.assertAlmostEqual(data['objects'][0]['points']['coordinates'][1][1], 37.767381, places=5)
# Get lines
connection = self.get_connection()
connection.request('GET', '/api/v1/geonotes/?lines__within=%s' % quote(golden_gate_park_json), headers={'Accept': 'application/json'})
response = connection.getresponse()
connection.close()
self.assertEqual(response.status, 200)
data = json.loads(response.read().decode('utf-8'))
# We get back the line inside Golden Gate park!
self.assertEqual(data['objects'][0]['content'], "A path inside Golden Gate Park! Huzzah!")
self.assertEqual(data['objects'][0]['lines']['type'], 'MultiLineString')
self.assertAlmostEqual(data['objects'][0]['lines']['coordinates'][0][0][0], -122.504544, places=5)
self.assertAlmostEqual(data['objects'][0]['lines']['coordinates'][0][0][1], 37.767002, places=5)
self.assertAlmostEqual(data['objects'][0]['lines']['coordinates'][0][1][0], -122.499995, places=5)
self.assertAlmostEqual(data['objects'][0]['lines']['coordinates'][0][1][1], 37.768223, places=5)
示例9: sites_linking_in
def sites_linking_in(self, urls, count=MAX_SITES_LINKING_IN_COUNT, start=0):
if count > self.MAX_SITES_LINKING_IN_COUNT:
raise RuntimeError("Maximum SitesLinkingIn result count is %s." % self.MAX_SITES_LINKING_IN_COUNT)
params = { "Action": "SitesLinkingIn" }
if not isinstance(urls, (list, tuple)):
params.update({
"Url": quote(urls),
"ResponseGroup": "SitesLinkingIn",
"Count": count,
"Start": start,
})
else:
if len(urls) > self.MAX_BATCH_REQUESTS:
raise RuntimeError("Maximum number of batch URLs is %s." % self.MAX_BATCH_REQUESTS)
params.update({
"SitesLinkingIn.Shared.ResponseGroup": "SitesLinkingIn",
"SitesLinkingIn.Shared.Count": count,
"SitesLinkingIn.Shared.Start": start,
})
for i, url in enumerate(urls):
params.update({"SitesLinkingIn.%d.Url" % (i + 1): quote(url)})
return self.request(params)
示例10: calc_signature
def calc_signature(self, args):
split = urlsplit(args['url'])
path = split.path
if len(path) == 0:
path = '/'
string_to_sign = '%s\n%s\n%s\n' % (args['method'],
split.netloc,
path)
lhmac = hmac.new(self.credentials.secret_key.encode('utf-8'),
digestmod=sha256)
args['params']['SignatureMethod'] = 'HmacSHA256'
if self.credentials.token:
args['params']['SecurityToken'] = self.credentials.token
sorted_params = sorted(args['params'])
pairs = []
for key in sorted_params:
value = args['params'][key]
pairs.append(quote(key, safe='') + '=' +
quote(value, safe='-_~'))
qs = '&'.join(pairs)
string_to_sign += qs
logger.debug('string_to_sign')
logger.debug(string_to_sign)
lhmac.update(string_to_sign.encode('utf-8'))
b64 = base64.b64encode(lhmac.digest()).strip().decode('utf-8')
return (qs, b64)
示例11: test_x_delete_name
def test_x_delete_name(self):
method = 'test_delete_name'
rv = self.app.post('/api/roles', content_type='application/json', data=self.new_role_body)
url = '/api/roles/name/{}?session_id=test'.format(quote(self.new_role.theName))
rv = self.app.delete(url)
if (sys.version_info > (3,)):
responseData = rv.data.decode('utf-8')
else:
responseData = rv.data
self.logger.debug('[%s] Response data: %s', method, responseData)
json_resp = json_deserialize(responseData)
self.assertIsNotNone(json_resp, 'No results after deserialization')
message = json_resp.get('message', None)
self.assertIsNotNone(message, 'No message returned')
self.logger.info('[%s] Message: %s\n', method, message)
rv = self.app.post('/api/roles', content_type='application/json', data=self.new_role_body)
url = '/api/roles/name/Test2'
upd_role = self.new_role
upd_role.theName = 'Test2'
upd_role_dict = self.new_role_dict
upd_role_dict['object'] = upd_role
upd_role_body = jsonpickle.encode(upd_role_dict)
rv = self.app.put(url, content_type='application/json', data=upd_role_body)
url = '/api/roles/name/Test2?session_id=test'.format(quote(self.new_role.theName))
rv = self.app.delete(url)
示例12: _oauth10a_signature
def _oauth10a_signature(consumer_token,
method, url, parameters={}, token=None):
"""Calculates the HMAC-SHA1 OAuth 1.0a signature for the given request.
See http://oauth.net/core/1.0a/#signing_process
"""
parts = urlparse.urlparse(url)
scheme, netloc, path = parts[:3]
normalized_url = scheme.lower() + "://" + netloc.lower() + path
base_elems = []
base_elems.append(method.upper())
base_elems.append(normalized_url)
base_elems.append("&".join("%s=%s" % (k, _oauth_escape(str(v)))
for k, v in sorted(parameters.items())))
base_string = "&".join(_oauth_escape(e) for e in base_elems)
key_elems = [escape.utf8(
urllib_parse.quote(consumer_token["secret"], safe='~'))]
key_elems.append(escape.utf8(
urllib_parse.quote(token["secret"], safe='~') if token else ""))
key = "&".join(key_elems)
hash = hmac.new(key, escape.utf8(base_string), hashlib.sha1)
return binascii.b2a_base64(hash.digest())[:-1]
示例13: __make_query_filter
def __make_query_filter(self, filters):
if isinstance(filters, list):
formated_filter = "&filter=".join(quote(f) for f in filters)
else:
formated_filter = quote(filters)
return "&filter=" + formated_filter
示例14: get
def get(self):
data = {'is_debug': config('DEBUG')}
urls = []
session = Session()
try:
pages = session.query(StaticPageModel)\
.filter_by(is_active=True)\
.order_by(StaticPageModel.id.asc()).all()
sections = session.query(CatalogSectionModel)\
.filter_by(is_active=True)\
.order_by(CatalogSectionModel.id.asc()).all()
items = session.query(CatalogItemModel)\
.filter_by(is_active=True)\
.order_by(CatalogItemModel.id.asc()).all()
except Exception as e:
session.close()
print('SiteMapRoute.get(): cannot get data from DB:\n',\
e, file=sys.stderr)
raise e
session.close()
for page in [x.item for x in pages]:
if '404' in page['alias']:
continue
urls.append({
'alias': quote(page['alias'], encoding='utf-8'),
'lastmod': page['last_change']
})
for section in [x.item for x in sections]:
url = '/catalog/{0}.html'.format(section['alias'])
url = quote(url, encoding='utf-8')
urls.append({
'alias': url,
'lastmod': section['last_change']
})
for item in [x.item for x in items]:
section_alias = None
for section in [x.item for x in sections]:
if section['id'] == item['section_id']:
section_alias = section['alias']
if section_alias is None:
e = Exception('SiteMapRoute: '+\
'cannot find section for element #%d' % item['id'])
print(e, file=sys.stderr)
continue
url = '/catalog/{0}/{1}.html'.format(section_alias, item['alias'])
url = quote(url, encoding='utf-8')
urls.append({
'alias': url,
'lastmod': section['last_change']
})
data.update({'urls': tuple(urls)})
self.set_header('Content-Type', 'text/xml; charset="utf-8"')
return self.render('client/sitemap.jade', **data)
示例15: __init__
def __init__(self, name, pusher):
self.pusher = pusher
self.name = str(name)
if not channel_name_re.match(self.name):
raise NameError("Invalid channel id: %s" % self.name)
self.path = '/apps/%s/channels/%s/events' % (self.pusher.app_id, quote(self.name))
self.users_path = '/apps/%s/channels/%s/users' % (self.pusher.app_id, quote(self.name))