Home > Software engineering >  Flask - Take URL in Route?
Flask - Take URL in Route?

Time:07-28

I have a question about Flask.

I want to use one endpoint to handle requests.

To do so, I need to take url in router like:

@app.route("/<url>", methods=['GET','POST'])
def home(url):
    base_url = "https://www.virustotal.com/"
    my_url = base_url   url

For example, I will sent request to my Flask app as " localhost:5000/api/v3/files/samehashvalue " and it will combine it with virustotal url.

my_url will something like = virustotal.com/api/v3/files/samehashvalue

How can I pass /api/v3... to my router? Without using parameters like ?url=...

CodePudding user response:

I'd suggest reading redirects from the Flask docs as well as url building.

With your specific example you can obtain the url from the route and pass it into your Flask function. It's then just a case of using redirect and an f string to redirect to that new url.

# http://localhost:5000/test redirects to 
# https://www.virustotal.com/api/v3/files/test


from flask import Flask, redirect

app = Flask(__name__)

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def url_redirector(path):
    return redirect(f'https://www.virustotal.com/api/v3/files/{path}')

if __name__ == '__main__':
    app.run(debug=True)

CodePudding user response:

I am not sure if this is correct, but I assume that you can specify the path in @app.route if it is a fixed path. For example:

@app.route("/api/v3/files", methods=['GET','POST'])
def home(url):
    base_url = "https://www.virustotal.com/api/v3/files/"

Then the hash value only can be passed as a parameter.

Please let me know if I misunderstood your question and I will edit this answer.

  • Related