当前位置: 首页>>代码示例>>Python>>正文


Python cgi.parse_qs方法代码示例

本文整理汇总了Python中cgi.parse_qs方法的典型用法代码示例。如果您正苦于以下问题:Python cgi.parse_qs方法的具体用法?Python cgi.parse_qs怎么用?Python cgi.parse_qs使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在cgi的用法示例。


在下文中一共展示了cgi.parse_qs方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: decode_task_payload

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import parse_qs [as 别名]
def decode_task_payload(task):
  """Decodes POST task payload.

  This can only decode POST payload for a normal task. For huge task,
  use model.HugeTask.decode_payload.

  Args:
    task: a dict representing a taskqueue task as documented in taskqueue_stub.

  Returns:
    parameter_name -> parameter_value dict. If multiple parameter values are
    present, then parameter_value will be a list.
  """
  if not task:
    return {}
  # taskqueue_stub base64 encodes body when it returns the task to us.
  body = base64.b64decode(task["body"])
  result = {}
  for (name, value) in cgi.parse_qs(body).items():
    if len(value) == 1:
      result[name] = value[0]
    else:
      result[name] = value
  return result 
开发者ID:elsigh,项目名称:browserscope,代码行数:26,代码来源:test_support.py

示例2: parse_qs_bytes

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import parse_qs [as 别名]
def parse_qs_bytes(qs, keep_blank_values=False, strict_parsing=False):
        """Parses a query string like urlparse.parse_qs, but returns the
        values as byte strings.

        Keys still become type str (interpreted as latin1 in python3!)
        because it's too painful to keep them as byte strings in
        python3 and in practice they're nearly always ascii anyway.
        """
        # This is gross, but python3 doesn't give us another way.
        # Latin1 is the universal donor of character encodings.
        result = parse_qs(qs, keep_blank_values, strict_parsing,
                          encoding='latin1', errors='strict')
        encoded = {}
        for k,v in result.iteritems():
            encoded[k] = [i.encode('latin1') for i in v]
        return encoded 
开发者ID:avelino,项目名称:bottle-auth,代码行数:18,代码来源:escape.py

示例3: _decode_payload

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import parse_qs [as 别名]
def _decode_payload(cls, body):
    compressed_payload_str = None
    if body.startswith(cls.PAYLOAD_KEY_PARAM):
      payload_key = body[len(cls.PAYLOAD_KEY_PARAM):]
      payload_entity = _HugeTaskPayload.get(payload_key)
      compressed_payload_str = payload_entity.payload
    elif body.startswith(cls.PAYLOAD_PARAM):
      compressed_payload_str = body[len(cls.PAYLOAD_PARAM):]

    if compressed_payload_str:
      payload_str = zlib.decompress(compressed_payload_str)
    else:
      payload_str = body

    result = {}
    for (name, value) in cgi.parse_qs(payload_str).items():
      if len(value) == 1:
        result[name] = value[0]
      else:
        result[name] = value
    return result 
开发者ID:singhj,项目名称:locality-sensitive-hashing,代码行数:23,代码来源:model.py

示例4: parse_query

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import parse_qs [as 别名]
def parse_query(self, query, defaults={'mode': 'main'}):
        '''
        Parse a query string as used in a URL or passed to your addon by XBMC.
        
        Example:
         
        >>> addon.parse_query('name=test&type=basic')
        {'mode': 'main', 'name': 'test', 'type': 'basic'} 
            
        Args:
            query (str): A query string.
            
        Kwargs:
            defaults (dict): A dictionary containing key/value pairs parsed 
            from the query string. If a key is repeated in the query string
            its value will be a list containing all of that keys values.  
        '''
        queries = cgi.parse_qs(query)
        q = defaults
        for key, value in queries.items():
            if len(value) == 1:
                q[key] = value[0]
            else:
                q[key] = value
        return q 
开发者ID:iwannabelikemike,项目名称:plugin.video.sparkle,代码行数:27,代码来源:addon.py

示例5: parse_qs

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import parse_qs [as 别名]
def parse_qs(qs, keep_blank_values=0, strict_parsing=0):
    """
    Like C{cgi.parse_qs}, but with support for parsing byte strings on Python 3.

    @type qs: C{bytes}
    """
    d = {}
    items = [s2 for s1 in qs.split(b"&") for s2 in s1.split(b";")]
    for item in items:
        try:
            k, v = item.split(b"=", 1)
        except ValueError:
            if strict_parsing:
                raise
            continue
        if v or keep_blank_values:
            k = unquote(k.replace(b"+", b" "))
            v = unquote(v.replace(b"+", b" "))
            if k in d:
                d[k].append(v)
            else:
                d[k] = [v]
    return d 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:25,代码来源:http.py

示例6: extend_access_token

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import parse_qs [as 别名]
def extend_access_token(self, app_id, app_secret):
        """
        Extends the expiration time of a valid OAuth access token. See
        <https://developers.facebook.com/roadmap/offline-access-removal/
        #extend_token>

        """
        args = {
            "client_id": app_id,
            "client_secret": app_secret,
            "grant_type": "fb_exchange_token",
            "fb_exchange_token": self.access_token,
        }
        response = urllib2.urlopen("https://graph.facebook.com/oauth/"
                                   "access_token?" +
                                   urllib.parse.urlencode(args)).read().decode('utf-8')
        query_str = parse_qs(response)
        if "access_token" in query_str:
            result = {"accesstoken": query_str["access_token"][0]}
            if "expires" in query_str:
                result["expire"] = query_str["expires"][0]
            return result
        else:
            response = json.loads(response)
            raise GraphAPIError(response) 
开发者ID:MicroPyramid,项目名称:django-simple-forum,代码行数:27,代码来源:facebook.py

示例7: get_access_token_from_code

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import parse_qs [as 别名]
def get_access_token_from_code(code, redirect_uri, app_id, app_secret):

    args = {
        "code": code,
        "redirect_uri": redirect_uri,
        "client_id": app_id,
        "client_secret": app_secret,
    }
    # We would use GraphAPI.request() here, except for that the fact
    # that the response is a key-value pair, and not JSON.
    response = urllib2.urlopen("https://graph.facebook.com/oauth/access_token" +
                              "?" + urllib.parse.urlencode(args)).read().decode('utf-8')
    query_str = parse_qs(response)
    if "access_token" in query_str:
        result = {"access_token": query_str["access_token"][0]}
        if "expires" in query_str:
            result["expires"] = query_str["expires"][0]
        return result
    else:
        jsonResponse = json.loads(str(response))
        # response = json.loads(response)
        encoding = response.info().get_content_charset('utf8')
        data = json.loads(response.read().decode(encoding))
        return data 
开发者ID:MicroPyramid,项目名称:django-simple-forum,代码行数:26,代码来源:facebook.py

示例8: get

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import parse_qs [as 别名]
def get(self, urlpath):
        if not urlpath.startswith(URLPATH_SEARCH_PREFIX):
            return streaminfo404()
        fakeurl = 'http://127.0.0.1' + urlpath
        o = urlparse.urlparse(fakeurl)
        qdict = cgi.parse_qs(o[4])
        if DEBUG:
            print >> sys.stderr, 'searchmap: qdict', qdict
        searchstr = qdict['q'][0]
        searchstr = searchstr.strip()
        collection = qdict['collection'][0]
        metafeedurl = qdict['metafeed'][0]
        print >> sys.stderr, '\nbg: search: Got search for', `searchstr`, 'in', collection
        self.id2hits.garbage_collect_timestamp_smaller(time.time() - HITS_TIMEOUT)
        if collection == 'metafeed':
            if not self.check_reload_metafeed(metafeedurl):
                return {'statuscode': 504,
                 'statusmsg': '504 MetaFeed server did not respond'}
            return self.process_search_metafeed(searchstr)
        else:
            return self.process_search_p2p(searchstr) 
开发者ID:alesnav,项目名称:p2ptv-pi,代码行数:23,代码来源:Search.py

示例9: test_copy_sheet_requires_login_for_anonymous_user

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import parse_qs [as 别名]
def test_copy_sheet_requires_login_for_anonymous_user(self):
        self.sheet.is_public = True
        worksheet = Worksheet()
        worksheet.a1.value = 'some-cell-content'
        self.sheet.jsonify_worksheet(worksheet)
        self.sheet.save()
        self.request.user = AnonymousUser()
        self.request.META['SERVER_NAME'] = 'servername'
        self.request.META['SERVER_PORT'] = '80'
        self.request.get_full_path = lambda: 'request-path'

        response = copy_sheet(self.request, self.user.username, self.sheet.id)

        self.assertTrue(isinstance(response, HttpResponseRedirect))

        redirect_url = urlparse(response['Location'])
        self.assertEquals(redirect_url.path, settings.LOGIN_URL)
        redirect_query_params = parse_qs(redirect_url.query)
        self.assertEquals(redirect_query_params['next'], ['request-path']) 
开发者ID:pythonanywhere,项目名称:dirigible-spreadsheet,代码行数:21,代码来源:test_views.py

示例10: parse_qs_bytes

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import parse_qs [as 别名]
def parse_qs_bytes(qs, keep_blank_values=False, strict_parsing=False):
        """Parses a query string like urlparse.parse_qs, but returns the
        values as byte strings.

        Keys still become type str (interpreted as latin1 in python3!)
        because it's too painful to keep them as byte strings in
        python3 and in practice they're nearly always ascii anyway.
        """
        # This is gross, but python3 doesn't give us another way.
        # Latin1 is the universal donor of character encodings.
        result = parse_qs(qs, keep_blank_values, strict_parsing,
                          encoding='latin1', errors='strict')
        encoded = {}
        for k, v in result.iteritems():
            encoded[k] = [i.encode('latin1') for i in v]
        return encoded 
开发者ID:omererdem,项目名称:honeything,代码行数:18,代码来源:escape.py

示例11: _on_request_body

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import parse_qs [as 别名]
def _on_request_body(self, data):
        self._request.body = data
        content_type = self._request.headers.get("Content-Type", "")
        if self._request.method == "POST":
            if content_type.startswith("application/x-www-form-urlencoded"):
                arguments = cgi.parse_qs(self._request.body)
                for name, values in arguments.iteritems():
                    values = [v for v in values if v]
                    if values:
                        self._request.arguments.setdefault(name, []).extend(
                            values)
            elif content_type.startswith("multipart/form-data"):
                if 'boundary=' in content_type:
                    boundary = content_type.split('boundary=',1)[1]
                    if boundary: self._parse_mime_body(boundary, data)
                else:
                    logging.warning("Invalid multipart/form-data")
        self.request_callback(self._request) 
开发者ID:omererdem,项目名称:honeything,代码行数:20,代码来源:httpserver.py

示例12: findBodyType

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import parse_qs [as 别名]
def findBodyType(request):
    bd_typ ="none"
    try:
        if request["body"]:
            try:
                json.loads(request["body"])
                bd_typ ="json"
            except:
                pass
            try:
                config = etree.XMLParser(remove_blank_text=True, resolve_entities=False)
                #Prevent Entity Expansion Attacks against the Framework
                etree.fromstring(request["body"],config)
                bd_typ ="xml"
            except:
                pass
            qs=parse_qs(request["body"])
            if qs:
                bd_typ="form"
        return bd_typ
    except:
        PrintException("[ERROR] Finding Request Body type") 
开发者ID:HackingLab,项目名称:MobileSF,代码行数:24,代码来源:views.py

示例13: parse_qs

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import parse_qs [as 别名]
def parse_qs(url_encoded_string, ignoreExceptions=True,encoding=DEFAULT_ENCODING):
	'''
	'''
	parsed_qs = None
	result = querystring(encoding=encoding)

	if url_encoded_string:
		try:
			parsed_qs = cgi.parse_qs(url_encoded_string,keep_blank_values=True,strict_parsing=False)
		except Exception:
			if not ignoreExceptions:
				raise 'Strange things found when parsing query string: "%s"' % url_encoded_string
		else:
			for p, v in parsed_qs.iteritems():
				if type(v) is not list:
					v = [v]
				result[p] = v

	return result 
开发者ID:imiyoo2010,项目名称:teye_scanner_for_book,代码行数:21,代码来源:URL.py

示例14: redirect_to_poem

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import parse_qs [as 别名]
def redirect_to_poem(environ, start_response):
    # We might have a POST body indicating the poem type; try to read it.

    # The environment variable CONTENT_LENGTH may be empty or missing
    try:
        request_body_size = int(environ.get('CONTENT_LENGTH', 0))
    except (ValueError):
        request_body_size = 0

    # Read and parse the HTTP request body which is passed by the WSGI server
    request_body = environ['wsgi.input'].read(request_body_size)
    poemtype = None
    qs = parse_qs(request_body)
    if qs:
        poemtype = qs.get('poemtype')[0]
    if poemtype != 'mushypoem':
        poemtype = 'poem'

    seed = os.urandom(8).encode('hex')

    start_response('302 Found', [
        ('Location', '/' + poemtype + '/' + seed)
    ])

    return [] 
开发者ID:schollz,项目名称:poetry-generator,代码行数:27,代码来源:poetrygenerator.py

示例15: do_POST

# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import parse_qs [as 别名]
def do_POST(s):
		length = int(s.headers['content-length'])
		postvars = cgi.parse_qs(s.rfile.read(length), keep_blank_values=1)

		logging.debug(postvars)

		try:					
			username     = postvars['u'][0]
			domain		 = postvars['d'][0]
			encTimestamp = postvars['t'][0]
		except:		
			s.send_response(500)
			s.end_headers()	
			return		

		cracker.enqueueJob(username, domain, encTimestamp, dcept.passwordHit)		

		s.send_response(200)
		s.end_headers() 
开发者ID:secureworks,项目名称:dcept,代码行数:21,代码来源:GenerationServer.py


注:本文中的cgi.parse_qs方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。