Biniyam Asnake
Biniyam Asnake

Reputation: 77

Python-Requests, how to dynamically receive the url?

I have looked all over Stack Overflow but I have not found an answer to this question.

How can a python script dynamically receive a url based on a javascript function call?

For example, in this Stack Overflow question (Code reproduced below) how could I dynamically receive the url (which is hardcoded in this case) if the name of the python file was abc.py and I called xhttp = new XMLHttpRequest(); and then
xhttp.open("GET", "abc.py?token=123", true); in some html file with javascript?

from urllib.parse import urlparse
from urllib.parse import parse_qs
from urllib.parse import urlencode

url = 'http://example.com?param1=a&token=TOKEN_TO_REPLACE&param2=c'

o = urlparse(url)
query = parse_qs(o.query)
if query.get('token'):
    query['token'] = ['NEW_TOKEN', ]
    new_query = urlencode(query, doseq=True)
    url.split('?')[0] + '?' + new_query

>>> http://example.com?param2=c&param1=a&token=NEW_TOKEN

Upvotes: 0

Views: 1781

Answers (1)

johnII
johnII

Reputation: 1433

You need to use framework to do this, python script alone with no networking/socket functionality could not communicate with the front-end (js side), below is a simple backend to received your javascript request using bottle.py

Here is a simple implementation that receives a POST request from client and do the logic you need, updated url is returned to the calling code.

Note the request is POST and the data is json with the token and url

from bottle import post, run, request
import json

from urllib.parse import urlparse
from urllib.parse import parse_qs
from urllib.parse import urlencode


def replace_token(data):
    url = data['url']
    token = data['token']
    o = urlparse(url)
    query = parse_qs(o.query)
    if query.get('token'):
        query['token'] = [token]
        new_query = urlencode(query, doseq=True)
        return url.split('?')[0] + '?' + new_query



@post('/token')
def index():
    data = json.load(request.body)
    return replace_token(data)

run(host='localhost', port=8080, debug=True)

Then you can test it by simple using a curl

curl -X POST http://localhost:8080/token -d '{"token":"NEW_TOKEN", "url":"http://example.com?param1=a&token=TOKEN_TO_REPLACE&param2=c"}'

Upvotes: 1

Related Questions