本文整理汇总了Python中urlparse.parse_qs方法的典型用法代码示例。如果您正苦于以下问题:Python urlparse.parse_qs方法的具体用法?Python urlparse.parse_qs怎么用?Python urlparse.parse_qs使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类urlparse
的用法示例。
在下文中一共展示了urlparse.parse_qs方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: totalCount
# 需要导入模块: import urlparse [as 别名]
# 或者: from urlparse import parse_qs [as 别名]
def totalCount(self):
if not self.__totalCount:
params = {} if self.__nextParams is None else self.__nextParams.copy()
# set per_page = 1 so the totalCount is just the number of pages
params.update({"per_page": 1})
headers, data = self.__requester.requestJsonAndCheck(
"GET",
self.__firstUrl,
parameters=params,
headers=self.__headers
)
if 'link' not in headers:
if data and "total_count" in data:
self.__totalCount = data["total_count"]
elif data:
self.__totalCount = len(data)
else:
self.__totalCount = 0
else:
links = self.__parseLinkHeader(headers)
lastUrl = links.get("last")
self.__totalCount = int(parse_qs(lastUrl)['page'][0])
return self.__totalCount
示例2: list_object
# 需要导入模块: import urlparse [as 别名]
# 或者: from urlparse import parse_qs [as 别名]
def list_object(object_name, token, parameters = {}):
"""
A generator that wraps make_api_call() to get all items of an object
"""
looping = True
parameters.update({'page': None})
while looping:
json = make_api_call(object_name, token, parameters)
logging.info('Intercom plugin - %s: results = %i' % (object_name, len(json.get(object_name))) )
for r in json.get(object_name):
yield r
next = json.get('pages', {}).get('next')
logging.info('Intercom plugin - %s: next = %s' % (object_name, next) )
if next is None:
looping = False
else:
# next contains an url, let's extract the url params
new_params = dict(urlparse.parse_qs(urlparse.urlparse(next).query))
parameters.update(new_params)
示例3: GET
# 需要导入模块: import urlparse [as 别名]
# 或者: from urlparse import parse_qs [as 别名]
def GET(self, rse):
"""
Get RSE usage information.
:param rse: the RSE name.
"""
header('Content-Type', 'application/x-json-stream')
source = None
if ctx.query:
params = parse_qs(ctx.query[1:])
if 'source' in params:
source = params['source'][0]
try:
for usage in list_rse_usage_history(rse=rse, issuer=ctx.env.get('issuer'), source=source):
yield render_json(**usage) + '\n'
except RSENotFound as error:
raise generate_http_error(404, 'RSENotFound', error.args[0])
except RucioException as error:
raise generate_http_error(500, error.__class__.__name__, error.args[0])
except Exception as error:
print(format_exc())
raise InternalError(error)
示例4: testRequestToken
# 需要导入模块: import urlparse [as 别名]
# 或者: from urlparse import parse_qs [as 别名]
def testRequestToken(self):
class MockResponse(object):
def __init__(self, code):
self.code = code.decode()
def read(self):
return ('{"refresh_token": "' + self.code + '456"}').encode()
def mock_urlopen(unused_url, param):
return MockResponse(urlparse.parse_qs(param)[b'code'][0])
# Choose urlopen function to mock based on Python version
if sys.version_info[0] < 3:
urlopen_lib = 'urllib2.urlopen'
else:
urlopen_lib = 'urllib.request.urlopen'
with mock.patch(urlopen_lib, new=mock_urlopen):
auth_code = '123'
refresh_token = ee.oauth.request_token(auth_code)
self.assertEqual('123456', refresh_token)
示例5: do_GET
# 需要导入模块: import urlparse [as 别名]
# 或者: from urlparse import parse_qs [as 别名]
def do_GET(self):
params = urlparse.parse_qs(urlparse.urlparse(self.path).query)
key = params.get('apikey')
if not key:
self.send_response(400)
return
self.server.key_queue.put(key[0])
self.send_response(200)
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'GET, OPTIONS')
self.send_header('Content-type', 'text/html')
self.end_headers()
page_content = ("""
<html>
<header>
<script>
window.location.replace("%s/cli_login?keystate=sent");
</script>
</header>
</html>
""" % (floyd.floyd_web_host)).encode('utf-8')
self.wfile.write(page_content)
示例6: send_request
# 需要导入模块: import urlparse [as 别名]
# 或者: from urlparse import parse_qs [as 别名]
def send_request(fields):
config = model.Config.get()
fields["VERSION"] = "113"
fields["USER"] = config.paypal_user
fields["PWD"] = config.paypal_password
fields["SIGNATURE"] = config.paypal_signature
form_data = urllib.urlencode(fields)
result = urlfetch.fetch(url=config.paypal_api_url, payload=form_data, method=urlfetch.POST,
headers={'Content-Type': 'application/x-www-form-urlencoded'})
result_map = urlparse.parse_qs(result.content)
if 'ACK' in result_map:
if result_map['ACK'][0] == "Success":
return (True, result_map)
logging.warning("Paypal returned an error:")
logging.warning(pprint.pformat(result_map))
return (False, result_map)
logging.warning("Could not contact Paypal:")
logging.warning(result.content)
return False, result.content
示例7: __init__
# 需要导入模块: import urlparse [as 别名]
# 或者: from urlparse import parse_qs [as 别名]
def __init__(self, url, handle):
"""The request objects contains all the arguments passed to the plugin via
the command line.
Args:
url (str): The complete plugin URL being requested. Since Kodi
typically passes the URL query string in a separate argument
from the base URL, they must be joined into a single string
before being provided.
handle (Union[int, str]): The handle associated with the current
request.
"""
self.url = url
#: The current request's handle, an integer.
self.handle = int(handle)
# urlparse doesn't like the 'plugin' scheme, so pass a protocol
# relative url, e.g. //plugin.video.helloxbmc/path
self.scheme, remainder = url.split(':', 1)
parts = urlparse.urlparse(remainder)
self.netloc, self.path, self.query_string = (
parts[1], parts[2], parts[4])
self.args = unpickle_args(urlparse.parse_qs(self.query_string))
示例8: filter_result
# 需要导入模块: import urlparse [as 别名]
# 或者: from urlparse import parse_qs [as 别名]
def filter_result(link):
try:
# Valid results are absolute URLs not pointing to a Google domain
# like images.google.com or googleusercontent.com
o = urlparse(link, 'http')
if o.netloc and 'google' not in o.netloc:
return link
# Decode hidden URLs.
if link.startswith('/url?'):
link = parse_qs(o.query)['q'][0]
# Valid results are absolute URLs not pointing to a Google domain
# like images.google.com or googleusercontent.com
o = urlparse(link, 'http')
if o.netloc and 'google' not in o.netloc:
return link
# Otherwise, or on error, return None.
except Exception:
pass
return None
# Shortcut to search images
# Beware, this does not return the image link.
示例9: do_POST
# 需要导入模块: import urlparse [as 别名]
# 或者: from urlparse import parse_qs [as 别名]
def do_POST(self):
if self.debug:
print "Received Request"
parsed_path = urlparse(unicode(self.path))
length = int(self.headers.getheader('content-length'))
field_data = self.rfile.read(length)
esc_string = "[[-*-]]"
field_data = field_data.replace(";",esc_string)
args = parse_qs(field_data)
self.user = "-"
self.retval = "-"
self.code = -1
if parsed_path.path == "/checkpwd":
message = ''
if 'u' in args and 'p' in args:
user = unquote(args['u'][0].replace(esc_string,";"))
self.user = user
password = unquote(args['p'][0].replace(esc_string,";")) #.decode('utf8')
(isGood,code,reason) = self.verifyPasswordGood(user.encode('utf8'),password.encode('utf8'),False)
message += u','.join(map(unicode,[isGood,code,reason]))
self.send_response(200)
self.end_headers()
self.wfile.write(message)
else:
self.send_response(301)
self.send_header('Location', 'https://www.youtube.com/watch?v=dQw4w9WgXcQ')
self.end_headers()
return
示例10: parse_qs
# 需要导入模块: import urlparse [as 别名]
# 或者: from urlparse import parse_qs [as 别名]
def parse_qs(qs, keep_blank_values=0, strict_parsing=0):
"""Parse a query given as a string argument."""
warn("cgi.parse_qs is deprecated, use urlparse.parse_qs instead",
PendingDeprecationWarning, 2)
return urlparse.parse_qs(qs, keep_blank_values, strict_parsing)
示例11: check_error
# 需要导入模块: import urlparse [as 别名]
# 或者: from urlparse import parse_qs [as 别名]
def check_error(response, expect_status=200):
"""
Youku error should return as json response, like:
HTTP 400
{
"error":{
"code":120010223,
"type":"UploadsException",
"description":"Expired upload token"
}
}
But error also maybe in response url params or response body.
Content-Type maybe application/json or text/plain.
Args:
expect_status: normally is 200 or 201
"""
json = None
try:
json = response.json()
except:
pass
if (response.status_code != expect_status or
response.status_code == 400 or
'error' in json):
if json:
error = json['error']
raise YoukuError(error.get('code', ''), error.get('type', ''),
error.get('description', ''), response.status_code)
else:
# try to parse error from body
error = parse_qs(response.text)
raise YoukuError(error.get('code', [None])[0],
error.get('type', [None])[0],
error.get('description', [None])[0],
response.status_code)
示例12: display_name
# 需要导入模块: import urlparse [as 别名]
# 或者: from urlparse import parse_qs [as 别名]
def display_name(magnet_uri):
import urlparse
from kmediatorrent.utils import first
magnet_args = urlparse.parse_qs(magnet_uri.replace("magnet:?", ""))
return first(magnet_args.get("dn", []))
示例13: get_file_name
# 需要导入模块: import urlparse [as 别名]
# 或者: from urlparse import parse_qs [as 别名]
def get_file_name(href):
import urlparse
if href.startswith("magnet:"):
magnet_args = urlparse.parse_qs(href.replace("magnet:?", "")) # I know about urlparse.urlsplit but this is faster
if magnet_args["dn"]:
return magnet_args["dn"][0]
else:
path = urlparse.urlsplit(href)[2]
filename = path.split("/")[-1]
return filename
示例14: __init__
# 需要导入模块: import urlparse [as 别名]
# 或者: from urlparse import parse_qs [as 别名]
def __init__(self, url, handle):
#: The entire request url.
self.url = url
#: The current request's handle, an integer.
self.handle = int(handle)
# urlparse doesn't like the 'plugin' scheme, so pass a protocol
# relative url, e.g. //plugin.video.helloxbmc/path
self.scheme, remainder = url.split(':', 1)
parts = urlparse.urlparse(remainder)
self.netloc, self.path, self.query_string = (
parts[1], parts[2], parts[4])
self.args = unpickle_args(parse_qs(self.query_string))
示例15: from_string
# 需要导入模块: import urlparse [as 别名]
# 或者: from urlparse import parse_qs [as 别名]
def from_string(s):
"""Deserializes a token from a string like one returned by
`to_string()`."""
if not len(s):
raise ValueError("Invalid parameter string.")
params = parse_qs(s, keep_blank_values=False)
if not len(params):
raise ValueError("Invalid parameter string.")
try:
key = params['oauth_token'][0]
except Exception:
raise ValueError("'oauth_token' not found in OAuth request.")
try:
secret = params['oauth_token_secret'][0]
except Exception:
raise ValueError("'oauth_token_secret' not found in "
"OAuth request.")
token = Token(key, secret)
try:
token.callback_confirmed = params['oauth_callback_confirmed'][0]
except KeyError:
pass # 1.0, no callback confirmed.
return token