na5tyk
na5tyk

Reputation: 43

How get param from URL after # in python

How can I get param from URL after #?

Example:

http://localhost/addAccount/#code=qwerty

I tried use url = request.path and url.spit('/') but it isn't working becasuse request.path don't read string after # in url.

Upvotes: 3

Views: 1847

Answers (3)

pal
pal

Reputation: 11

I had similar thing recently
So I came up with this simple snippet:

from urllib.parse import parse_qs, urlparse


url = "http://localhost/addAccount/#code=qwerty"
fragment = urlparse(url).fragment
value = parse_qs(fragment).get("code")
print(value.pop())  # querty

We had to have "pop" here, as parse_qs returns list by default

Upvotes: 0

ShmulikA
ShmulikA

Reputation: 3764

dont try to parse urls manually - use the stdlib urllib.parse.urlparse
function (urlparse.urlparse on python2):

from urllib.parse import urlparse  # from urlparse import urlparse on py2
scheme = urlparse('http://localhost/addAccount/#code=qwerty')
print(scheme.fragment)

prints out:

code=qwerty

Unfortunately you cannot get from the server-side the fragement of the url (data after the #). AFAIK all browsers wont send the fragement to the server (the fragement can be used only on client side code (e.g. javascript).

Quoting Wikipedia:

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. Instead, the agent waits for the server to send the resource, and then the agent processes the resource according to the document type and fragment value.[2]

Upvotes: 0

Daniel Garrido
Daniel Garrido

Reputation: 105

In a URL, what travels after # is known as hash. In an HTTP request that reaches a server (server side) this data does not travel to the server. Therefore, on the server side, it is not possible to retrieve it (web browsers do not send this data in the HTTP request).

However, on the client side it is possible. In Javascript you could do:

window. location. hash

Upvotes: 2

Related Questions