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

Alex
  • 2,513
  • 5
  • 27
  • 42

7 Answers7

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")
jamesaharvey
  • 14,023
  • 15
  • 52
  • 63
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!

Alex
  • 2,513
  • 5
  • 27
  • 42
  • Yes, in general you want to use the tools provided by your framework and not manually parse URLs; this is a solved problem. – Wooble May 04 '10 at 12:50
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
0

Try this

import os
url = os.environ['HTTP_HOST']
Arty
  • 5,923
  • 9
  • 39
  • 44
  • 1
    this appears to ignore any query strings as it's only grabbing the host URL: ParseResult(scheme='localhost', netloc='', path='8080', params='', query='', fragment='') – Alex May 04 '10 at 11:13
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.

Community
  • 1
  • 1
Al-Noor Ladhani
  • 2,413
  • 1
  • 22
  • 14
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

embulldogs99
  • 840
  • 9
  • 9
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)
  • 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. – Sariq Shaikh Mar 08 '20 at 21:45