0

I am working on a url redirector application, in Python. The idea of this application is simple: when a user performs an http request to a certain domain (e.g. to https://google.com), the app stops the request and performs another http request (e.g. to https://github.com), thereby redirecting the user to the second page.

Unfortunately, I have looked through SO and I haven't found any question that addresses this issue directly:

Admittedly, I only have some fabricated pseudocode to demonstrate what I wish to do, but it may prove useful:

import requests

original_site = "https://google.com"
redirect_site = "https://github.com"

def redirect_request():
    if requests.get(original_site) == True:
        requests.kill(request.original_site.id)
        requests.get(redirect_site)

I greatly appreciate any suggestions.

EDIT - Here is a clarification of what I mean:

The user runs my python script, which I will call foobar.py, as follows:

python foobar.py

Then the user opens their web browser, and enters the url https://google.com, and as the script is running, the user will not actually visit https://google.com, but be redirected to https://github.com

JS4137
  • 314
  • 2
  • 11
  • I don't understand the context here. If the user types google.com into their browser, how is your code going to "intercept" that request? Are you assuming they have installed some program of yours? – John Gordon Mar 02 '21 at 03:20
  • @JohnGordon That is correct, I am assuming that they are going to run the script from the command line e.g. `python myscript.py` and then opens their browser to type https://google.com – JS4137 Mar 02 '21 at 03:27
  • You probably want something like a browser plugin. Otherwise you can't make the browser do something like that. Or you can mess with the hosts file & do a DNS redirect there. – rdas Mar 02 '21 at 03:41
  • What about using selenium and injecting some javascript that does the redirect? Because I am trying to keep it just as a python script, not a browser plugin. – JS4137 Mar 02 '21 at 03:49

1 Answers1

1

One option is if you are trying to build a lightweight web app using python where you can mess with HTTP redirects, you can use Flask to accept a GET on a route and then simply do a redirect.

from flask import Flask, redirect
app = Flask(__name__)

@app.route('/')
def index():
    return redirect("https://www.google.com")

But to answer your question more directly, you don't "stop" the initial request. You simply find a way to handle it and serve back a response that you specify.

Sam Yi
  • 68
  • 8