[Python] How to build a url with path parameters in Python security [closed]

Discussão em 'Python' iniciado por Stack, Fevereiro 6, 2025.

  1. Stack

    Stack Membro Participativo

    In Python, is there a commonly used library to build urls with path parameters, where some of those parameters might be user input or otherwise untrusted?

    Ideally, it would be some kind of url builder that also supports query parameters, or whatever else I might need down the road.

    For example, maybe I have a url template like this:

    url_template = "https://example.com/api/v1/user/{user_id}"


    And I want to be able to take that url template and fill in a user_id value, but with any special characters escaped.

    For example, if I had:

    url_template = "https://example.com/api/v1/user/{user_id}"
    user_id = "123/some-other-url?virus=veryyes"

    final_url = build_it(url_template, { "user_id": user_id })
    # final_url is "https://example.com/api/v1/user/123%2Fsome-other-url%3Fvirus%3Dveryyes"


    I am aware of the quote function in https://docs.python.org/3/library/urllib.parse.html#urllib.parse.quote but that seems too low level to use in practice.

    I also see a lot of suggestions to use urljoin from https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urljoin but that seems like a bad idea, as it allows query parameters and multiple path segments.

    The solution doesn't need to use a template like my example. I'd also be happy with a .append_single_path_segment() style api.

    Continue reading...

Compartilhe esta Página