6

Is there a way for Flask to accept a full URL as a URL parameter?

I am aware that <path:something> accepts paths with slashes. However I need to accept everything including a query string after ?, and path doesn't capture that.

http://example.com/someurl.com?andother?yetanother

I want to capture someurl.com?andother?yetanother. I don't know ahead of time what query args, if any, will be supplied. I'd like to avoid having to rebuild the query string from request.args.

3
  • 1
    The general form for those is "query parameters", and you can use request.args to get at those. However, I'd expect those to be valid query parameters; normally, you'd see http://example.com?foo=bar&baz=quux. What is it that you're trying to accomplish? Commented Sep 28, 2015 at 4:23
  • Restructure your URI to accept a single query parameter that will catch the entire value. http://someapi/?full_param="someurl.com?blah?blah?blah". Commented Sep 28, 2015 at 13:49
  • What I am doing is a test of a URL response from various locations. Unfortunately some URLs I am testing require me to pass the variable in order to get proper response. However I do not know ahead of time what this variable is, and therefore I can't preplan for it. Commented Sep 28, 2015 at 14:27

2 Answers 2

3

the path pattern will let you capture more complicated route patterns like URLs:

@app.route('/catch/<path:foo>')
def catch(foo):
    print(foo)
    return foo

The data past the ? indicate it's a query parameter, so they won't be included in that patter. You can either access that part form request.query_string or build it back up from the request.args as mentioned in the comments.

Sign up to request clarification or add additional context in comments.

Comments

3

Due to the way routing works, you will not be able to capture the query string as part of the path. Use <path:path> in the rule to capture arbitrary paths. Then access request.url to get the full URL that was accessed, including the query string. request.url always includes a ? even if there was no query string. It's valid, but you can strip that off if you don't want it.

@app.route("/<path:path>")
def index(path=None):
    return request.url.rstrip("?")

For example, accessing http://127.0.0.1:5000/hello?world would return http://127.0.0.1:5000/hello?world.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.