25

How would i get the current URL with Python,

I need to grab the current URL so i can check it for query strings e.g

requested_url = "URL_HERE"

url = urlparse(requested_url)

if url[4]:
    params = dict([part.split('=') for part in url[4].split('&')])

also this is running in Google App Engine

7 Answers 7

53

Try this:

self.request.url

Also, if you just need the querystring, this will work:

self.request.query_string

And, lastly, if you know the querystring variable that you're looking for, you can do this:

self.request.get("name-of-querystring-variable")
Sign up to request clarification or add additional context in comments.

1 Comment

It shows this error: NameError: name 'self' is not defined
3

For anybody finding this via google,

i figured it out,

you can get the query strings on your current request using:

url_get = self.request.GET

which is a UnicodeMultiDict of your query strings!

1 Comment

Yes, in general you want to use the tools provided by your framework and not manually parse URLs; this is a solved problem.
2

I couldn't get the other answers to work, but here is what worked for me:

    url = os.environ['HTTP_HOST']
    uri = os.environ['REQUEST_URI']
    return url + uri

Comments

0

Try this

import os
url = os.environ['HTTP_HOST']

1 Comment

this appears to ignore any query strings as it's only grabbing the host URL: ParseResult(scheme='localhost', netloc='', path='8080', params='', query='', fragment='')
0

This is how I capture in Python 3 from CGI (A) URL, (B) GET parameters and (C) POST data:

=======================================================

import sys, os, io

CAPTURE URL

myDomainSelf = os.environ.get('SERVER_NAME')

myPathSelf = os.environ.get('PATH_INFO')

myURLSelf = myDomainSelf + myPathSelf

CAPTURE GET DATA

myQuerySelf = os.environ.get('QUERY_STRING')

CAPTURE POST DATA

myTotalBytesStr=(os.environ.get('HTTP_CONTENT_LENGTH'))

if (myTotalBytesStr == None):

myJSONStr = '{"error": {"value": true, "message": "No (post) data received"}}'

else:

myTotalBytes=int(os.environ.get('HTTP_CONTENT_LENGTH'))

myPostDataRaw = io.open(sys.stdin.fileno(),"rb").read(myTotalBytes)

myPostData = myPostDataRaw.decode("utf-8")

Write RAW to FILE

mySpy = "myURLSelf: [" + str(myURLSelf) + "]\n"

mySpy = mySpy + "myQuerySelf: [" + str(myQuerySelf) + "]\n"

mySpy = mySpy + "myPostData: [" + str(myPostData) + "]\n"

You need to define your own myPath here

myFilename = "spy.txt"

myFilePath = myPath + "\" + myFilename

myFile = open(myFilePath, "w")

myFile.write(mySpy)

myFile.close()

=======================================================

Here are some other useful CGI environment vars:

AUTH_TYPE

CONTENT_LENGTH

CONTENT_TYPE

GATEWAY_INTERFACE

PATH_INFO

PATH_TRANSLATED

QUERY_STRING

REMOTE_ADDR

REMOTE_HOST

REMOTE_IDENT

REMOTE_USER

REQUEST_METHOD

SCRIPT_NAME

SERVER_NAME

SERVER_PORT

SERVER_PROTOCOL

SERVER_SOFTWARE

============================================

I am using these methods running Python 3 on Windows Server with CGI via MIIS.

Hope this can help you.

Comments

0

requests module has 'url' attribute, that is changed url.
just try this:

import requests
current_url=requests.get("some url").url
print(current_url)

1 Comment

Hi Welcome to SO. Thank you for your answer but it doesn't really solve the problem. How this will help extract query string out of the URL which is the main question asked.
0

If your python script is server side:

You can use os

    import os
    url = os.environ
    print(url)

with that, you will see all the data os.environ gives you. It looks like your need the 'QUERY_STRING'. Like any JSON object, you can obtain the data like this.

    import os
    url = os.environ['QUERY_STRING']
    print(url)

And if you want a really elegant scalable solution you can use anywhere and always, you can save the variables into a dictionary (named vars here) like so:

    vars={}
    splits=os.environ['QUERY_STRING'].split('&')
    for x in splits:
        name,value=x.split('=')
        vars[name]=value

    print(vars)

If you are client side, then any of the other responses involving the get request will work

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.