🔍 Code Extractor

function parse_query_string

Maturity: 32

Extracts a specific query parameter value from a URL string, with compatibility for both Python 2 and Python 3.

File:
/tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/runtime/compat.py
Lines:
53 - 63
Complexity:
simple

Purpose

This function parses a URL to extract the value of a specific query string parameter. It handles the differences between Python 2's urlparse module and Python 3's urllib.parse module by checking the Python version and using the appropriate import. The function returns the first value of the specified query parameter key.

Source Code

def parse_query_string(url, key):
    if is_py2:
        import urlparse

        parsed_url = urlparse.urlparse(url)
        return urlparse.parse_qs(parsed_url.query)[key][0]
    else:
        from urllib.parse import parse_qs, urlparse

        parsed_url = urlparse(url)
        return parse_qs(parsed_url.query)[key][0]

Parameters

Name Type Default Kind
url - - positional_or_keyword
key - - positional_or_keyword

Parameter Details

url: A string containing the full URL to parse, including the query string (e.g., 'http://example.com/path?key1=value1&key2=value2'). Must be a valid URL format.

key: A string representing the query parameter name to extract from the URL. This should match exactly with a parameter name in the query string (case-sensitive).

Return Value

Returns a string containing the first value associated with the specified query parameter key. If the key has multiple values, only the first one is returned (index [0]). Will raise a KeyError if the key doesn't exist in the query string, or an IndexError if the key exists but has no values.

Dependencies

  • urlparse (Python 2 only)
  • urllib.parse (Python 3 only)

Required Imports

No imports needed at the call site - the function handles imports internally based on Python version

Conditional/Optional Imports

These imports are only needed under specific conditions:

import urlparse

Condition: Python 2 environment (when is_py2 is True)

Required (conditional)
from urllib.parse import parse_qs, urlparse

Condition: Python 3 environment (when is_py2 is False)

Required (conditional)

Usage Example

# Assuming is_py2 is defined in the module
# is_py2 = sys.version_info[0] == 2

url = 'https://example.com/search?query=python&page=1&sort=desc'

# Extract the 'query' parameter
query_value = parse_query_string(url, 'query')
print(query_value)  # Output: 'python'

# Extract the 'page' parameter
page_value = parse_query_string(url, 'page')
print(page_value)  # Output: '1'

# Note: Will raise KeyError if key doesn't exist
try:
    missing = parse_query_string(url, 'nonexistent')
except KeyError:
    print('Key not found in query string')

Best Practices

  • Always wrap calls in try-except blocks to handle KeyError when the query parameter doesn't exist
  • Be aware that this function only returns the first value if a parameter appears multiple times in the query string
  • Ensure the 'is_py2' variable is properly defined in the module scope before calling this function
  • Consider URL-decoding the returned value if it contains encoded characters
  • This function is primarily for legacy codebases supporting both Python 2 and 3; for Python 3-only code, use urllib.parse directly
  • The function assumes the query parameter has at least one value; it will raise IndexError if the key exists but has an empty list of values

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_absolute_url 45.7% similar

    Extracts the base URL (scheme + netloc) from a given URL by removing the path component.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/runtime/compat.py
  • function is_string_type 41.8% similar

    Checks if a given value is a string type, with compatibility for both Python 2 and Python 3.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/runtime/compat.py
  • function resolve_base_url 39.7% similar

    Extracts and returns the base URL (protocol and hostname) from a given URL string by removing path and query components.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/runtime/auth/providers/saml_token_provider.py
  • function evaluate_query 39.6% similar

    Executes a Cypher query against a Neo4j database session and returns the first value from a single result record.

    From: /tf/active/vicechatdev/offline_docstore_multi_vice.py
  • function run_query 36.1% similar

    Executes a Cypher query against a Neo4j database session and returns the result, with optional parameterization for safe query execution.

    From: /tf/active/vicechatdev/offline_docstore_multi_vice.py
← Back to Browse