Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Get URL fragment identifier with Flask

Tags:

python

flask

My Flask program receives the following request with some data after the #:

https://som.thing.com/callback#data1=XXX&data2=YYY&data3=...

And I need to read the data1 parameter, but this doesn't seem to work:

@app.route("/callback")
def get_data():
    data = request.args.get("data1")
    print(data)
like image 492
ntbt Avatar asked Jan 27 '23 02:01

ntbt


1 Answers

The hash of the URL (everything after the #) is never sent to the server, the browser will strip it away, keeping that part of the URL completely client-side. According to Wikipedia:

The fragment identifier functions differently to the rest of the URI: its processing is exclusively client-side with no participation from the web server, [...]. When an agent (such as a Web browser) requests a web resource from a Web server, the agent sends the URI to the server, but does not send the fragment.

This means there's no way to retrieve it on the backend, no matter which framework you use, as none of them will ever receive that piece of data.

You need to use query parameters instead, so your URL should look like this:

https://foo.com/bar?data1=ABC&data2=XYZ

And in this case, you will be able to access them using request.args:

from flask import request

@app.route('/bar')
def bar():
    page = request.args.get('data1', default = '', type = str)
    filter = request.args.get('data2', default = 0, type = int)
like image 100
Danziger Avatar answered Feb 14 '23 01:02

Danziger