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


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方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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


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