本文整理匯總了Python中cgi.parse_qsl方法的典型用法代碼示例。如果您正苦於以下問題:Python cgi.parse_qsl方法的具體用法?Python cgi.parse_qsl怎麽用?Python cgi.parse_qsl使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類cgi
的用法示例。
在下文中一共展示了cgi.parse_qsl方法的14個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: parse_querystring
# 需要導入模塊: import cgi [as 別名]
# 或者: from cgi import parse_qsl [as 別名]
def parse_querystring(environ):
"""
Parses a query string into a list like ``[(name, value)]``.
Caches this value in case parse_querystring is called again
for the same request.
You can pass the result to ``dict()``, but be aware that keys that
appear multiple times will be lost (only the last value will be
preserved).
"""
source = environ.get('QUERY_STRING', '')
if not source:
return []
if 'paste.parsed_querystring' in environ:
parsed, check_source = environ['paste.parsed_querystring']
if check_source == source:
return parsed
parsed = cgi.parse_qsl(source, keep_blank_values=True,
strict_parsing=False)
environ['paste.parsed_querystring'] = (parsed, source)
return parsed
示例2: from_environ
# 需要導入模塊: import cgi [as 別名]
# 或者: from cgi import parse_qsl [as 別名]
def from_environ(cls, environ, with_query_string=True,
with_path_info=True, script_name=None,
path_info=None, querystring=None):
url = request.construct_url(
environ, with_query_string=False,
with_path_info=with_path_info, script_name=script_name,
path_info=path_info)
if with_query_string:
if querystring is None:
vars = request.parse_querystring(environ)
else:
vars = cgi.parse_qsl(
querystring,
keep_blank_values=True,
strict_parsing=False)
else:
vars = None
v = cls(url, vars=vars)
return v
示例3: _add_query_parameter
# 需要導入模塊: import cgi [as 別名]
# 或者: from cgi import parse_qsl [as 別名]
def _add_query_parameter(url, name, value):
"""Adds a query parameter to a url.
Replaces the current value if it already exists in the URL.
Args:
url: string, url to add the query parameter to.
name: string, query parameter name.
value: string, query parameter value.
Returns:
Updated query parameter. Does not update the url if value is None.
"""
if value is None:
return url
else:
parsed = list(urlparse.urlparse(url))
q = dict(parse_qsl(parsed[4]))
q[name] = value
parsed[4] = urllib.urlencode(q)
return urlparse.urlunparse(parsed)
示例4: do_GET
# 需要導入模塊: import cgi [as 別名]
# 或者: from cgi import parse_qsl [as 別名]
def do_GET(s):
"""Handle a GET request.
Parses the query parameters and prints a message
if the flow has completed. Note that we can't detect
if an error occurred.
"""
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()
query = s.path.split('?', 1)[-1]
query = dict(parse_qsl(query))
s.server.query_params = query
s.wfile.write("<html><head><title>Authentication Status</title></head>")
s.wfile.write("<body><p>The authentication flow has completed.</p>")
s.wfile.write("</body></html>")
示例5: do_GET
# 需要導入模塊: import cgi [as 別名]
# 或者: from cgi import parse_qsl [as 別名]
def do_GET(s):
"""Handle a GET request
Parses the query parameters and prints a message
if the flow has completed. Note that we can't detect
if an error occurred.
"""
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()
query = s.path.split('?', 1)[-1]
query = dict(parse_qsl(query))
s.server.query_params = query
s.wfile.write("<html><head><title>Authentication Status</title></head>")
s.wfile.write("<body><p>The authentication flow has completed.</p>")
s.wfile.write("</body></html>")
示例6: parse_backend_uri
# 需要導入模塊: import cgi [as 別名]
# 或者: from cgi import parse_qsl [as 別名]
def parse_backend_uri(backend_uri):
"""
Converts the "backend_uri" into a cache scheme ('db', 'memcached', etc), a
host and any extra params that are required for the backend. Returns a
(scheme, host, params) tuple.
"""
if backend_uri.find(':') == -1:
raise InvalidCacheBackendError("Backend URI must start with scheme://")
scheme, rest = backend_uri.split(':', 1)
if not rest.startswith('//'):
raise InvalidCacheBackendError("Backend URI must start with scheme://")
host = rest[2:]
qpos = rest.find('?')
if qpos != -1:
params = dict(parse_qsl(rest[qpos+1:]))
host = rest[2:qpos]
else:
params = {}
if host.endswith('/'):
host = host[:-1]
return scheme, host, params
示例7: get_video_id_from_url
# 需要導入模塊: import cgi [as 別名]
# 或者: from cgi 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 = cgi.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)))
示例8: decode_bookmark
# 需要導入模塊: import cgi [as 別名]
# 或者: from cgi import parse_qsl [as 別名]
def decode_bookmark(bookmark):
"""Decodes a string into a bookmark dictionary."""
return dict(parse_qsl(b64decode(bookmark)))
示例9: WebPagetest
# 需要導入模塊: import cgi [as 別名]
# 或者: from cgi import parse_qsl [as 別名]
def WebPagetest(request, key):
"""Sends an API request to run one's test page on WebPagetest.org."""
test = models.user_test.Test.get_mem(key)
if not test:
msg = 'No test was found with test_key %s.' % key
return http.HttpResponseServerError(msg)
current_user = users.get_current_user()
if (test.user.key().name() != current_user.user_id() and not
users.is_current_user_admin()):
return http.HttpResponse('You can\'t play with tests you don\'t own')
# Help users autorun their tests by adding autorun=1 to the test url.
test_url_parts = list(urlparse.urlparse(test.url))
test_url_query = dict(cgi.parse_qsl(test_url_parts[4]))
test_url_query.update({'autorun': '1'})
test_url_parts[4] = urllib.urlencode(test_url_query)
test_url = urlparse.urlunparse(test_url_parts)
# TODO(elsigh): callback url.
webpagetest_url = ('%s&url=%s¬ify=%s' %
(WEBPAGETEST_URL, test_url,
urllib.quote('elsigh@gmail.com')))
webpagetests = {}
# See http://goo.gl/EfK1r for WebPagetest instructions.
for location in WEBPAGETEST_LOCATIONS:
url = '%s&location=%s' % (webpagetest_url, location)
response = urlfetch.fetch(url)
json = simplejson.loads(response.content)
webpagetests[location] = json
params = {
'test': test,
'webpagetests': webpagetests
}
return util.Render(request, 'user_test_webpagetest.html', params)
示例10: parse_dict_querystring
# 需要導入模塊: import cgi [as 別名]
# 或者: from cgi import parse_qsl [as 別名]
def parse_dict_querystring(environ):
"""Parses a query string like parse_querystring, but returns a MultiDict
Caches this value in case parse_dict_querystring is called again
for the same request.
Example::
>>> environ = {'QUERY_STRING': 'day=Monday&user=fred&user=jane'}
>>> parsed = parse_dict_querystring(environ)
>>> parsed['day']
'Monday'
>>> parsed['user']
'fred'
>>> parsed.getall('user')
['fred', 'jane']
"""
source = environ.get('QUERY_STRING', '')
if not source:
return MultiDict()
if 'paste.parsed_dict_querystring' in environ:
parsed, check_source = environ['paste.parsed_dict_querystring']
if check_source == source:
return parsed
parsed = cgi.parse_qsl(source, keep_blank_values=True,
strict_parsing=False)
multi = MultiDict(parsed)
environ['paste.parsed_dict_querystring'] = (multi, source)
return multi
示例11: _gen_request
# 需要導入模塊: import cgi [as 別名]
# 或者: from cgi import parse_qsl [as 別名]
def _gen_request(self, method, url, params='', headers=None, extra_environ=None,
status=None, upload_files=None, expect_errors=False):
"""
Do a generic request.
"""
if headers is None:
headers = {}
if extra_environ is None:
extra_environ = {}
environ = self._make_environ()
# @@: Should this be all non-strings?
if isinstance(params, (list, tuple, dict)):
params = urllib.urlencode(params)
if hasattr(params, 'items'):
# Some other multi-dict like format
params = urllib.urlencode(params.items())
if upload_files:
params = cgi.parse_qsl(params, keep_blank_values=True)
content_type, params = self.encode_multipart(
params, upload_files)
environ['CONTENT_TYPE'] = content_type
elif params:
environ.setdefault('CONTENT_TYPE', 'application/x-www-form-urlencoded')
if '?' in url:
url, environ['QUERY_STRING'] = url.split('?', 1)
else:
environ['QUERY_STRING'] = ''
environ['CONTENT_LENGTH'] = str(len(params))
environ['REQUEST_METHOD'] = method
environ['wsgi.input'] = StringIO(params)
self._set_headers(headers, environ)
environ.update(extra_environ)
req = TestRequest(url, environ, expect_errors)
return self.do_request(req, status=status)
示例12: test_deprecated_parse_qsl
# 需要導入模塊: import cgi [as 別名]
# 或者: from cgi import parse_qsl [as 別名]
def test_deprecated_parse_qsl(self):
# this func is moved to urlparse, this is just a sanity check
with check_warnings(('cgi.parse_qsl is deprecated, use urlparse.'
'parse_qsl instead', PendingDeprecationWarning)):
self.assertEqual([('a', 'A1'), ('b', 'B2'), ('B', 'B3')],
cgi.parse_qsl('a=A1&b=B2&B=B3'))
示例13: _update_query_params
# 需要導入模塊: import cgi [as 別名]
# 或者: from cgi import parse_qsl [as 別名]
def _update_query_params(uri, params):
"""Updates a URI with new query parameters.
Args:
uri: string, A valid URI, with potential existing query parameters.
params: dict, A dictionary of query parameters.
Returns:
The same URI but with the new query parameters added.
"""
parts = list(urlparse.urlparse(uri))
query_params = dict(parse_qsl(parts[4])) # 4 is the index of the query part
query_params.update(params)
parts[4] = urllib.urlencode(query_params)
return urlparse.urlunparse(parts)
示例14: _parse_exchange_token_response
# 需要導入模塊: import cgi [as 別名]
# 或者: from cgi import parse_qsl [as 別名]
def _parse_exchange_token_response(content):
"""Parses response of an exchange token request.
Most providers return JSON but some (e.g. Facebook) return a
url-encoded string.
Args:
content: The body of a response
Returns:
Content as a dictionary object. Note that the dict could be empty,
i.e. {}. That basically indicates a failure.
"""
resp = {}
try:
resp = simplejson.loads(content)
except StandardError:
# different JSON libs raise different exceptions,
# so we just do a catch-all here
resp = dict(parse_qsl(content))
# some providers respond with 'expires', others with 'expires_in'
if resp and 'expires' in resp:
resp['expires_in'] = resp.pop('expires')
return resp