Python parse.parse_qs方法代码示例

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

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

示例1: headless_authorize

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qs [as 别名]
def headless_authorize(self):
        """
        Authorize without a display using only TTY.
        """
        url, _ = self.oauth.authorize_token_url(redirect_uri=self.redirect_uri)
        # Ask the user to open this url on a system with browser
        print('\n-------------------------------------------------------------------------')
        print('\t\tOpen the below URL in your browser\n')
        print(url)
        print('\n-------------------------------------------------------------------------\n')
        print('NOTE: After authenticating on Fitbit website, you will redirected to a URL which ')
        print('throws an ERROR. This is expected! Just copy the full redirected here.\n')
        redirected_url = input('Full redirected URL: ')
        params = urlparse.parse_qs(urlparse.urlparse(redirected_url).query)
        print(params['code'][0])
        self.authenticate_code(code=params['code'][0]) 
开发者ID:praveendath92,项目名称:fitbit-googlefit,代码行数:18,代码来源:auth_fitbit.py


示例2: totalCount

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse 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 
开发者ID:danielecook,项目名称:gist-alfred,代码行数:25,代码来源:PaginatedList.py


示例3: parse_code_from_url

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qs [as 别名]
def parse_code_from_url(url: str) -> str:
    """
    Parse an URL for parameter 'code'.
    Returns
    -------
    str
        value of 'code'
    Raises
    ------
    KeyError
        if 'code' is not available or has multiple values
    """
    query = urlparse(url).query
    code = parse_qs(query).get('code', None)
    if code is None:
        raise KeyError('Parameter `code` not available!')
    elif len(code) > 1:
        raise KeyError('Multiple values for `code`!')
    return code[0] 
开发者ID:felix-hilden,项目名称:tekore,代码行数:25,代码来源:util.py


示例4: urlparams

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qs [as 别名]
def urlparams(url, fragment=None, **kwargs):
    """
    Add a fragment and/or query parameters to a URL.
    Existing query string parameters are preserved, unless they conflict
    with the new parameters, in which case they're overridden.
    """
    parsed = urlparse(url)
    query = dict(parse_qs(parsed.query), **kwargs)
    return urlunparse(
        (
            parsed.scheme,
            parsed.netloc,
            parsed.path,
            parsed.params,
            urlencode(query, doseq=True),
            fragment if fragment is not None else parsed.fragment,
        )
    ) 
开发者ID:mozilla,项目名称:normandy,代码行数:21,代码来源:utils.py


示例5: test_it_cachebusts_x5u

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qs [as 别名]
def test_it_cachebusts_x5u(self, settings):
        signature = SignatureFactory()
        # If none, do not cache bust
        settings.AUTOGRAPH_X5U_CACHE_BUST = None
        serializer = SignatureSerializer(instance=signature)
        url_parts = list(urlparse.urlparse(serializer.data["x5u"]))
        query = urlparse.parse_qs(url_parts[4])
        assert "cachebust" not in query
        # If set, cachebust using the value
        settings.AUTOGRAPH_X5U_CACHE_BUST = "new"
        serializer = SignatureSerializer(instance=signature)
        url_parts = list(urlparse.urlparse(serializer.data["x5u"]))
        query = urlparse.parse_qs(url_parts[4])
        assert "cachebust" in query
        assert len(query["cachebust"]) == 1
        assert query["cachebust"][0] == "new" 
开发者ID:mozilla,项目名称:normandy,代码行数:20,代码来源:test_serializers.py


示例6: get_video_id

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qs [as 别名]
def get_video_id(url):
    parsed_url = urlparse(url)
    if parsed_url.netloc == "youtu.be":
        video_id = parsed_url.path[1:]
        if len(video_id) != 11:
            video_id = None
    else:
        parsed_query = parse_qs(parsed_url.query)
        try:
            video_id = parsed_query["v"]
            if type(video_id) == type(list()):  # TODO: Use isinstance()
                video_id = video_id[0]
        except KeyError:
            video_id = None
    return video_id 
开发者ID:MKLab-ITI,项目名称:news-popularity-prediction,代码行数:18,代码来源:social_context.py


示例7: GET

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse 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) 
开发者ID:rucio,项目名称:rucio,代码行数:25,代码来源:rse.py


示例8: testRequestToken

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse 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) 
开发者ID:mortcanty,项目名称:earthengine,代码行数:25,代码来源:oauth_test.py


示例9: get_method

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qs [as 别名]
def get_method(self):
		bsObj=BeautifulSoup(self.body,"html.parser")
		links=bsObj.find_all("a",href=True)
		for a in links:
			url=a["href"]
			if url.startswith("http://") is False or url.startswith("https://") is False or url.startswith("mailto:") is False:
				base=urljoin(self.url,a["href"])
				query=urlparse(base).query
				if query != "":
					Log.warning("Found link with query: "+G+query+N+" Maybe a vuln XSS point")
					
					query_payload=query.replace(query[query.find("=")+1:len(query)],self.payload,1)
					test=base.replace(query,query_payload,1)
					
					query_all=base.replace(query,urlencode({x: self.payload for x in parse_qs(query)}))
					
					Log.info("Query (GET) : "+test)
					Log.info("Query (GET) : "+query_all)
					
					_respon=self.session.get(test)
					if self.payload in _respon.text or self.payload in self.session.get(query_all).text:
						Log.high("Detected XSS (GET) at "+_respon.url)
					else:
						Log.info("This page is safe from XSS (GET) attack but not 100% yet...") 
开发者ID:menkrep1337,项目名称:XSSCon,代码行数:26,代码来源:core.py


示例10: get_agents

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qs [as 别名]
def get_agents(self, count=1000, name="", listening=""):
        agents = []
        url = f"{self.url}/agents"
        params = {'count': count, 'name': name, 'listening': listening}
        while True:
            response = self._call_api("GET", url, params=params)
            agents = agents + response.get('value', [])
            try:
                # Only retrieve start parameter from next url href since API does NOT include name and listening
                # parameters even if included in original request so the next href can't be used blindly
                query_params = parse_qs(urlparse(response['links']['next']['href']).query)
                # Add or overwrite start parameter for next request
                params['start'] = query_params['start']
            except KeyError:
                # Return current list of agents when there are no more links to follow
                return agents 
开发者ID:rapid7,项目名称:insightconnect-plugins,代码行数:21,代码来源:api.py


示例11: do_GET

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse 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) 
开发者ID:floydhub,项目名称:floyd-cli,代码行数:27,代码来源:login.py


示例12: filter_result

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse 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. 
开发者ID:the-robot,项目名称:sqliv,代码行数:29,代码来源:google.py


示例13: compare_query

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qs [as 别名]
def compare_query(url_org, url_compare):
    param_org = parse.parse_qs(parse.urlparse(url_org).query, True)
    param_compare = parse.parse_qs(parse.urlparse(url_compare).query, True)
    for key, value in param_org.items():
        if not (key in param_compare):
            return False
        if value[0].strip():
            if not param_compare[key] == value:
                return False
    return True 
开发者ID:Meituan-Dianping,项目名称:lyrebird-api-coverage,代码行数:12,代码来源:url_compare.py


示例14: prepare_query_filters

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qs [as 别名]
def prepare_query_filters(query):
    filters = {'labels': {}, 'fields': {}}
    if query:
        # set based regex - does not support only field
        labelRegex = re.compile('^(?P<label>.*) (?P<matcher>notin|in)\s?\((?P<values>.*)\)$')
        queries = parse_qs(query)
        if 'labelSelector' in queries:
            for items in queries['labelSelector']:
                # split on , but not inside ()
                r = re.compile(r'(?:[^,(]|\([^)]*\))+')
                for item in r.findall(items):
                    if '=' in item:
                        # equal based requirement
                        key, value = item.split('=')
                        filters['labels'][key] = value
                    else:
                        # set based requirement
                        matches = labelRegex.match(item)
                        if matches is None:
                            continue
                        # split and strip spaces
                        values = [x.strip() for x in matches.group('values').split(',')]
                        key = matches.group('label') + '__' + matches.group('matcher')
                        filters['labels'][key] = values
        if 'fieldSelector' in queries:
            for items in queries['fieldSelector']:
                for item in items.split(','):
                    key, value = item.split('=')
                    filters['fields'][key] = value
    return filters 
开发者ID:deis,项目名称:controller,代码行数:36,代码来源:mock.py


示例15: read_request_data

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qs [as 别名]
def read_request_data(self):  # type: () -> Dict[str, str]
        assert self.headers['Content-Type'] == 'application/x-www-form-urlencoded'
        content = self.read_request_body()
        data_lists = parse_qs(
            content,
            # Strict options:
            keep_blank_values=True,
            strict_parsing=True,
            errors='strict',
        )
        # Flatten the listed values.
        data_flat = {k: v for (k, [v]) in data_lists.items()}
        return data_flat 
开发者ID:PiDelport,项目名称:django-payfast,代码行数:16,代码来源:itn_helpers.py


示例16: _load_form_data

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qs [as 别名]
def _load_form_data(self) -> None:
        raw_data: bytes = await self.get_data(raw=True)
        self._form = MultiDict()
        self._files = MultiDict()
        content_header = self.content_type
        if content_header is None:
            return
        content_type, parameters = parse_header(content_header)
        if content_type == "application/x-www-form-urlencoded":
            try:
                data = raw_data.decode(parameters.get("charset", "utf-8"))
            except UnicodeDecodeError:
                from ..exceptions import BadRequest  # noqa Avoiding circular import
                raise BadRequest()
            for key, values in parse_qs(data, keep_blank_values=True).items():
                for value in values:
                    self._form.add(key, value)
        elif content_type == "multipart/form-data":
            field_storage = FieldStorage(
                io.BytesIO(raw_data),
                headers={name.lower(): value for name, value in self.headers.items()},
                environ={"REQUEST_METHOD": "POST"},
                limit=len(raw_data),
            )
            for key in field_storage:  # type: ignore
                field_storage_key = field_storage[key]
                if isinstance(field_storage_key, list):
                    for item in field_storage_key:
                        self._load_field_storage(key, item)
                else:
                    self._load_field_storage(key, field_storage_key) 
开发者ID:pgjones,项目名称:quart,代码行数:34,代码来源:request.py


示例17: do_GET

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qs [as 别名]
def do_GET(self):
        params = parse_qs(urlparse(self.path).query)
        self._set_headers()
        # {'text': ['I looove iparser!']}
        titles = ['HanLP是面向生产环境的自然语言处理工具包。',
                  '上海华安工业(集团)公司董事长谭旭光和秘书张晚霞来到美国纽约现代艺术博物馆参观。',
                  # '词法分析包括中文分词、词性标注和命名实体识别。',
                  # '本页面词法分析采用的是感知机算法。',
                  '剑桥分析公司多位高管对卧底记者说,他们确保了唐纳德·特朗普在总统大选中获胜。',
                  '收件人在万博·齐都国际绿茵花园(东门)A8栋,靠近泰山护理职业学院。',
                  # '双桥街道双桥社区劳动和社会保障工作站地址是扬州市四望亭路293号双桥村4楼。',
                  '他在浙江金华出生,他的名字叫金华。',
                  '总统普京与特朗普通电话讨论美国太空探索技术公司。',
                  '云南丽江多措并举推进“河长制”取得实效',
                  '微软公司於1975年由比爾·蓋茲和保羅·艾倫創立,18年啟動以智慧雲端、前端為導向的大改組。',
                  '北京大学计算语言学研究所和富士通研究开发中心有限公司,得到了人民日报社新闻信息中心的语料库。',
                  # '可以自由设置句法分析模块中的分词算法。',
                  # '敬请注意本页面不接受过长的句子。',
                  # '徐先生还具体帮助他确定了把画雄鹰、松鼠和麻雀作为主攻目标。',
                  '萨哈夫说,伊拉克将同联合国销毁伊拉克大规模杀伤性武器特别委员会继续保持合作。',
                  '中央人民政府驻澳门特别行政区联络办公室的张朝阳说商品和服务是三原县鲁桥食品厂的主营业务。']
        sentence = random.choice(titles)
        if SENTENCE in params:
            s = params[SENTENCE]
            if len(s):
                sentence = s[0].strip()
        punctuation = re.compile('[。!?!?]')
        sentence = sentence[:len(punctuation.split(sentence)[0]) + 1]
        sentence = sentence.replace(' ', '')
        MAX_LENGTH = 50
        if len(sentence) > MAX_LENGTH:
            sentence = '请输入{}字以内的句子'.format(MAX_LENGTH)
        ann = '词法分析可视化仅支持 HanLP 1.6.2及以上版本'
        if lexical_analyzer:
            ann = lexical_analyzer.analyze(sentence).translateCompoundWordLabels().toStandoff(True).__str__()
        conll = HanLP.parseDependency(sentence).__str__()
        self.write(TEMPLATE.replace('{SENTENCE}', sentence).replace('{CONLL}', quote(conll))
                   .replace('{HANLP_GOOGLE_UA}', HANLP_GOOGLE_UA, 1)
                   .replace('{ANN}', quote(ann))
                   ) 
开发者ID:hankcs,项目名称:pyhanlp,代码行数:42,代码来源:server.py


示例18: _parse

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qs [as 别名]
def _parse(application_endpoint: str) -> Tuple[str, str, str]:
        url, valid = LuisApplication._try_parse_url(application_endpoint)
        if not valid:
            raise ValueError(
                f"{application_endpoint} is not a valid LUIS application endpoint."
            )
        segments = PurePosixPath(unquote(url.path)).parts
        application_id = segments[-1] if segments else None
        qs_parsed_result = parse_qs(url.query)
        endpoint_key = qs_parsed_result.get("subscription-key", [None])[0]
        parts_for_base_url = url.scheme, url.netloc, "", None, None, None
        endpoint = urlunparse(parts_for_base_url)
        return (application_id, endpoint_key, endpoint) 
开发者ID:microsoft,项目名称:botbuilder-python,代码行数:17,代码来源:luis_application.py


示例19: check_error

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse 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) 
开发者ID:hanguokai,项目名称:youku,代码行数:40,代码来源:util.py


示例20: new_websocket_client

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qs [as 别名]
def new_websocket_client(self):
        """Called after a new WebSocket connection has been established."""
        # Reopen the eventlet hub to make sure we don't share an epoll
        # fd with parent and/or siblings, which would be bad
        from eventlet import hubs
        hubs.use_hub()
        # The zun expected behavior is to have token
        # passed to the method GET of the request
        parse = urlparse.urlparse(self.path)
        if parse.scheme not in ('http', 'https'):
            # From a bug in urlparse in Python < 2.7.4 we cannot support
            # special schemes (cf: https://bugs.python.org/issue9374)
            if sys.version_info < (2, 7, 4):
                raise exception.ZunException(
                    _("We do not support scheme '%s' under Python < 2.7.4, "
                      "please use http or https") % parse.scheme)
        query = parse.query
        token = urlparse.parse_qs(query).get("token", [""]).pop()
        uuid = urlparse.parse_qs(query).get("uuid", [""]).pop()
        exec_id = urlparse.parse_qs(query).get("exec_id", [""]).pop()
        ctx = context.get_admin_context(all_projects=True)
        if uuidutils.is_uuid_like(uuid):
            container = objects.Container.get_by_uuid(ctx, uuid)
        else:
            container = objects.Container.get_by_name(ctx, uuid)
        if exec_id:
            self._new_exec_client(container, token, uuid, exec_id)
        else:
            self._new_websocket_client(container, token, uuid) 
开发者ID:openstack,项目名称:zun,代码行数:36,代码来源:websocketproxy.py


示例21: test_get_allocation_candidates_not_found

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qs [as 别名]
def test_get_allocation_candidates_not_found(self):
        # Ensure _get_resource_provider() just returns None when the placement
        # API doesn't find a resource provider matching a UUID
        resp_mock = mock.Mock(status_code=404)
        self.ks_adap_mock.get.return_value = resp_mock
        expected_path = '/allocation_candidates'
        expected_query = {'resources': ['MEMORY_MB:1024'],
                          'limit': ['100']}
        # Make sure we're also honoring the configured limit
        CONF.set_override('max_placement_results', 100, group='scheduler')
        resources = scheduler_utils.ResourceRequest.from_extra_specs(
            {'resources:MEMORY_MB': '1024'})
        res = self.client.get_allocation_candidates(self.context, resources)
        self.ks_adap_mock.get.assert_called_once_with(
            mock.ANY, microversion='1.31', endpoint_filter=mock.ANY,
            logger=mock.ANY,
            headers={'X-Openstack-Request-Id': self.context.global_id})
        url = self.ks_adap_mock.get.call_args[0][0]
        split_url = parse.urlsplit(url)
        query = parse.parse_qs(split_url.query)
        self.assertEqual(expected_path, split_url.path)
        self.assertEqual(expected_query, query)
        self.assertIsNone(res[0]) 
开发者ID:openstack,项目名称:zun,代码行数:29,代码来源:test_report.py


示例22: get_id_from_external_url

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qs [as 别名]
def get_id_from_external_url(url: str) -> str:
        return parse_qs(urlparse(url).query)["v"][0] 
开发者ID:raveberry,项目名称:raveberry,代码行数:4,代码来源:youtube.py


示例23: get_x5u

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qs [as 别名]
def get_x5u(self, signature):
        x5u = signature.x5u
        # Add cachebust parameter to x5u URL.
        if x5u is not None and settings.AUTOGRAPH_X5U_CACHE_BUST is not None:
            url_parts = list(urlparse.urlparse(x5u))
            query = urlparse.parse_qs(url_parts[4])
            query["cachebust"] = settings.AUTOGRAPH_X5U_CACHE_BUST
            url_parts[4] = urlencode(query)
            return urlparse.urlunparse(url_parts)
        return x5u 
开发者ID:mozilla,项目名称:normandy,代码行数:14,代码来源:serializers.py


示例24: _parse_verification_url

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qs [as 别名]
def _parse_verification_url(url, verification_field_names):
    parsed_url = urlparse(url)
    query = parse_qs(parsed_url.query, strict_parsing=True)
    for key, values in query.items():
        if not values:
            raise ValueError("no values for '{key}".format(key=key))
        if len(values) > 1:
            raise ValueError("multiple values for '{key}'".format(key=key))
    verification_data = {key: values[0] for key, values in query.items()}
    return parsed_url.path, verification_data 
开发者ID:apragacz,项目名称:django-rest-registration,代码行数:14,代码来源:verification.py


示例25: _parse_verification_url

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qs [as 别名]
def _parse_verification_url(self, url, verification_field_names):
        parsed_url = urlparse(url)
        query = parse_qs(parsed_url.query, strict_parsing=True)
        for key, values in query.items():
            if not values:
                raise ValueError("no values for '{key}".format(key=key))
            if len(values) > 1:
                raise ValueError("multiple values for '{key}'".format(key=key))
        verification_data = {key: values[0] for key, values in query.items()}
        return parsed_url.path, verification_data 
开发者ID:apragacz,项目名称:django-rest-registration,代码行数:14,代码来源:base.py


示例26: args

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qs [as 别名]
def args(self):
        return MultiParams(parse_qs(qs=self.query_string)) 
开发者ID:simonw,项目名称:datasette,代码行数:4,代码来源:asgi.py


示例27: parse_host_param

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qs [as 别名]
def parse_host_param(request):
    host = None
    if request.META.get('QUERY_STRING', ''):
        param = urlparse.parse_qs(request.META.get('QUERY_STRING'))
        values = param.get('host')
        if values:
            host = next(iter(values), None)
    return host 
开发者ID:openstack,项目名称:trove-dashboard,代码行数:10,代码来源:tables.py


示例28: test_can_redirect_the_user_to_the_authorization_server_to_be_authenticated

# 需要导入模块: from urllib import parse [as 别名]
# 或者: from urllib.parse import parse_qs [as 别名]
def test_can_redirect_the_user_to_the_authorization_server_to_be_authenticated(self, client):
        url = reverse('oidc_auth_request')
        response = client.get(url, follow=False)
        assert response.status_code == 302
        assert response.url.startswith('http://example.com/a/authorize')
        parsed_parameters = parse_qs(urlparse(response.url).query)
        assert parsed_parameters['response_type'] == ['code', ]
        assert parsed_parameters['scope'] == ['openid email', ]
        assert parsed_parameters['client_id'] == ['DUMMY_CLIENT_ID', ]
        assert parsed_parameters['redirect_uri'] == ['http://testserver/oidc/auth/cb/', ]
        assert parsed_parameters['state']
        assert parsed_parameters['nonce'] 
开发者ID:impak-finance,项目名称:django-oidc-rp,代码行数:14,代码来源:test_views.py



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