本文整理汇总了Python中urllib.parse.parse_qsl方法的典型用法代码示例。如果您正苦于以下问题:Python parse.parse_qsl方法的具体用法?Python parse.parse_qsl怎么用?Python parse.parse_qsl使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类urllib.parse
的用法示例。
在下文中一共展示了parse.parse_qsl方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _authenticate
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qsl [as 别名]
def _authenticate(self, client, interactive=True):
if not client.is_registered():
self._register_client(client)
flask.session['destination'] = flask.request.url
flask.session['state'] = rndstr()
flask.session['nonce'] = rndstr()
# Use silent authentication for session refresh
# This will not show login prompt to the user
extra_auth_params = {}
if not interactive:
extra_auth_params['prompt'] = 'none'
login_url = client.authentication_request(flask.session['state'],
flask.session['nonce'],
extra_auth_params)
auth_params = dict(parse_qsl(login_url.split('?')[1]))
flask.session['fragment_encoded_response'] = AuthResponseHandler.expect_fragment_encoded_response(auth_params)
return redirect(login_url)
示例2: read
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qsl [as 别名]
def read(self):
try:
from PIL import Image
from pyzbar.pyzbar import decode
decoded_data = decode(Image.open(self.filename))
if path.isfile(self.filename):
remove(self.filename)
try:
url = urlparse(decoded_data[0].data.decode())
query_params = parse_qsl(url.query)
self._codes = dict(query_params)
return self._codes.get("secret")
except (KeyError, IndexError):
Logger.error("Invalid QR image")
return None
except ImportError:
from ..application import Application
Application.USE_QRSCANNER = False
QRReader.ZBAR_FOUND = False
示例3: GET
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qsl [as 别名]
def GET(self):
""" list all rucio accounts.
HTTP Success:
200 OK
HTTP Error:
401 Unauthorized
406 Not Acceptable
500 InternalError
:param Rucio-Account: Account identifier.
:param Rucio-Auth-Token: as an 32 character hex string.
:returns: A list containing all account names as dict.
"""
header('Content-Type', 'application/x-json-stream')
filter = {}
if ctx.query:
filter = dict(parse_qsl(ctx.query[1:]))
for account in list_accounts(filter=filter):
yield render_json(**account) + "\n"
示例4: urlparams
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qsl [as 别名]
def urlparams(url_, hash=None, **query):
"""Add a fragment and/or query paramaters to a URL.
New query params will be appended to exising parameters, except duplicate
names, which will be replaced.
"""
url = urlparse.urlparse(url_)
fragment = hash if hash is not None else url.fragment
# Use dict(parse_qsl) so we don't get lists of values.
query_dict = dict(urlparse.parse_qsl(url.query))
query_dict.update(query)
query_string = urlencode(
[(k, v) for k, v in query_dict.items() if v is not None])
new = urlparse.ParseResult(url.scheme, url.netloc, url.path, url.params,
query_string, fragment)
return new.geturl()
示例5: transform_url
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qsl [as 别名]
def transform_url(url, qparams=None, **kwargs):
""" Modify url
:param url: url to transform (can be relative)
:param qparams: additional query params to add to end of url
:param kwargs: pieces of URL to modify - e.g. netloc=localhost:8000
:return: Modified URL
.. versionadded:: 3.2.0
"""
if not url:
return url
link_parse = urlsplit(url)
if qparams:
current_query = dict(parse_qsl(link_parse.query))
current_query.update(qparams)
link_parse = link_parse._replace(query=urlencode(current_query))
return urlunsplit(link_parse._replace(**kwargs))
示例6: test_spa_get
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qsl [as 别名]
def test_spa_get(app, client):
"""
Test 'single-page-application' style redirects
This uses json only.
"""
with capture_flashes() as flashes:
with capture_passwordless_login_requests() as requests:
response = client.post(
"/login",
json=dict(email="matt@lp.com"),
headers={"Content-Type": "application/json"},
)
assert response.headers["Content-Type"] == "application/json"
token = requests[0]["login_token"]
response = client.get("/login/" + token)
assert response.status_code == 302
split = urlsplit(response.headers["Location"])
assert "localhost:8081" == split.netloc
assert "/login-redirect" == split.path
qparams = dict(parse_qsl(split.query))
assert qparams["email"] == "matt@lp.com"
assert len(flashes) == 0
示例7: test_spa_get
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qsl [as 别名]
def test_spa_get(app, client):
"""
Test 'single-page-application' style redirects
This uses json only.
"""
with capture_reset_password_requests() as requests:
response = client.post(
"/reset",
json=dict(email="joe@lp.com"),
headers={"Content-Type": "application/json"},
)
assert response.headers["Content-Type"] == "application/json"
assert "user" not in response.json["response"]
token = requests[0]["token"]
response = client.get("/reset/" + token)
assert response.status_code == 302
split = urlsplit(response.headers["Location"])
assert "localhost:8081" == split.netloc
assert "/reset-redirect" == split.path
qparams = dict(parse_qsl(split.query))
assert qparams["email"] == "joe@lp.com"
assert qparams["token"] == token
示例8: test_tf_link_spa
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qsl [as 别名]
def test_tf_link_spa(app, client, get_message):
# Verify two-factor required when using magic link and SPA
# This currently isn't supported and should redirect to an error.
with app.mail.record_messages() as outbox:
response = client.post(
"/us-signin/send-code",
data=dict(identity="matt@lp.com", chosen_method="email"),
follow_redirects=True,
)
assert response.status_code == 200
assert b"Sign In" in response.data
matcher = re.match(
r".*(http://[^\s*]*).*", outbox[0].body, re.IGNORECASE | re.DOTALL
)
magic_link = matcher.group(1)
response = client.get(magic_link, follow_redirects=False)
split = urlsplit(response.location)
assert "localhost:8081" == split.netloc
assert "/login-error" == split.path
qparams = dict(parse_qsl(split.query))
assert qparams["tf_required"] == "1"
assert qparams["email"] == "matt@lp.com"
示例9: test_spa_get
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qsl [as 别名]
def test_spa_get(app, client):
"""
Test 'single-page-application' style redirects
This uses json only.
"""
with capture_flashes() as flashes:
with capture_registrations() as registrations:
response = client.post(
"/register",
json=dict(email="dude@lp.com", password="awesome sunset"),
headers={"Content-Type": "application/json"},
)
assert response.headers["Content-Type"] == "application/json"
token = registrations[0]["confirm_token"]
response = client.get("/confirm/" + token)
assert response.status_code == 302
split = urlsplit(response.headers["Location"])
assert "localhost:8081" == split.netloc
assert "/confirm-redirect" == split.path
qparams = dict(parse_qsl(split.query))
assert qparams["email"] == "dude@lp.com"
# Arguably for json we shouldn't have any - this is buried in register_user
# but really shouldn't be.
assert len(flashes) == 1
示例10: _strip_signing_parameters
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qsl [as 别名]
def _strip_signing_parameters(self, url):
""" Duplicated Unsiged URLs from Django-Stroage
Method from: https://github.com/jschneier/django-storages/blob/master/storages/backends/s3boto3.py
Boto3 does not currently support generating URLs that are unsigned. Instead we
take the signed URLs and strip any querystring params related to signing and expiration.
Note that this may end up with URLs that are still invalid, especially if params are
passed in that only work with signed URLs, e.g. response header params.
The code attempts to strip all query parameters that match names of known parameters
from v2 and v4 signatures, regardless of the actual signature version used.
"""
split_url = urlsplit(url)
qs = parse_qsl(split_url.query, keep_blank_values=True)
blacklist = {
'x-amz-algorithm', 'x-amz-credential', 'x-amz-date',
'x-amz-expires', 'x-amz-signedheaders', 'x-amz-signature',
'x-amz-security-token', 'awsaccesskeyid', 'expires', 'signature',
}
filtered_qs = ((key, val) for key, val in qs if key.lower() not in blacklist)
# Note: Parameters that did not have a value in the original query string will have
# an '=' sign appended to it, e.g ?foo&bar becomes ?foo=&bar=
joined_qs = ('='.join(keyval) for keyval in filtered_qs)
split_url = split_url._replace(query="&".join(joined_qs))
return split_url.geturl()
示例11: parse_vcs_requirement
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qsl [as 别名]
def parse_vcs_requirement(req):
"""Parses VCS line to egg name, version etc.
"""
if '+' not in req:
return None
vcs, url = req.split('+', 1)
if vcs not in ('git', 'svn', 'hg'):
return None
parsed_url = urlparse(url)
parsed = dict(parse_qsl(parsed_url.fragment))
if 'egg' not in parsed:
return None
egg = parsed['egg'].rsplit('-', 1)
if len(egg) > 1:
try:
pkg_resources_parse_version(egg[1])
except pkg_resources._vendor.packaging.version.InvalidVersion:
return parsed['egg'].lower(), req, None
return egg[0].lower(), req, egg[1]
else:
return parsed['egg'].lower(), req, None
示例12: get_video_id_from_url
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qsl [as 别名]
def get_video_id_from_url(self, url, info):
"""
Get YouTube video ID from URL
"""
try:
path = info.path
domain = info.netloc
video_id = ""
if domain == "youtu.be":
video_id = path.split("/")[1]
else:
parsed = parse_qsl(info.query)
params = dict(parsed)
if "v" in params:
video_id = params["v"]
if video_id:
return video_id
else:
log.error("SpiffyTitles: error getting video id from %s" % (url))
except IndexError as e:
log.error(
"SpiffyTitles: error getting video id from %s (%s)" % (url, str(e))
)
示例13: _parse_from_uri
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qsl [as 别名]
def _parse_from_uri(self, uri: str):
uri_parts = urlparse(uri)
conn_type = uri_parts.scheme
if conn_type == 'postgresql':
conn_type = 'postgres'
elif '-' in conn_type:
conn_type = conn_type.replace('-', '_')
self.conn_type = conn_type
self.host = _parse_netloc_to_hostname(uri_parts)
quoted_schema = uri_parts.path[1:]
self.schema = unquote(quoted_schema) if quoted_schema else quoted_schema
self.login = unquote(uri_parts.username) \
if uri_parts.username else uri_parts.username
self.password = unquote(uri_parts.password) \
if uri_parts.password else uri_parts.password
self.port = uri_parts.port
if uri_parts.query:
self.extra = json.dumps(dict(parse_qsl(uri_parts.query, keep_blank_values=True)))
示例14: add_params
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qsl [as 别名]
def add_params(url, extra=None, remove=None):
"""Given a URL, add new query parameters by merging in the contents of the
`extra` dictionary.
:param url: (str)
:param extra: (dict)
:param remove: (list or set)
:returns: (str) URL including new parameters
"""
if not (extra or remove):
return url
parsed = parse.urlparse(url)._asdict()
params = parse.parse_qsl(parsed["query"])
if extra:
params += list(extra.items())
if remove:
params = [pair for pair in params if pair[0] not in remove]
parsed["query"] = parse.urlencode(params, doseq=True)
return parse.urlunparse(parse.ParseResult(**parsed))
示例15: attack
# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qsl [as 别名]
def attack(self, payload, url):
try:
# Current request parameters
params = dict(parse_qsl(urlsplit(url).query))
# Change the value of the parameters with the payload
tainted_params = {x: payload for x in params}
if len(tainted_params) > 0:
# Prepare the attack URL
attack_url = urlsplit(url).geturl() + urlencode(tainted_params)
self.output.debug("Testing: %s" % attack_url)
resp = self.request.send(
url=attack_url, method="GET", payload=None, headers=None
)
if self.errors(resp.text):
self.output.finding(
"That site is may be vulnerable to LDAP Injection at %s\nInjection: %s"
% (url, payload)
)
except Exception as e:
self.logger.error(e)
self.output.error("Error occured\nAborting this attack...\n")
self.output.debug("Traceback: %s" % e)
return