Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get current base URI in flask? [duplicate]

In below code, i want to store URL in a variable to check error on which URL error occured.

@app.route('/flights', methods=['GET'])
def get_flight():
    flight_data= mongo.db.flight_details
    info = []
    for index in flight_data.find():
        info.append({'flight_name': index['flight_name'], 'flight_no': index['flight_no'], 'total_seat': index['total_seat'] })
    if request.headers['Accept'] == 'application/xml':
        template = render_template('data.xml', info=info)
        xml_response = make_response(template)
        xml_response.headers['Accept'] = 'application/xml'
        logger.info('sucessful got data')
        return xml_response
    elif request.headers['Accept'] == 'application/json':
        logger.info('sucessful got data')
        return jsonify(info)

Output:

* Restarting with stat
 * Debugger is active!
 * Debugger PIN: 165-678-508
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [28/Mar/2017 10:44:53] "GET /flights HTTP/1.1" 200 -

I want this message

"127.0.0.1 - - [28/Mar/2017 10:44:53] "GET /flights HTTP/1.1" 200 -"

should be stored in a variable or how can I get current URL that is executing?

like image 229
Ravi Bhushan Avatar asked Mar 28 '17 06:03

Ravi Bhushan


People also ask

How do I find the base URL of a Flask?

You can use the base_url method on flask's request function. 127.0. 0.1 - - [28/Mar/2017 10:44:53] "GET /flights HTTP/1.1" 200 -... if want to return whole thing , then what have i to do ? @RaviBhushan I'm not aware of any method to capture the standard output of the flask server.

How do I get query parameters in Flask?

Check if Query Parameters are Not None This can thankfully easily be done by getting an expected key and checking if it's present in the dictionary! Here - we extract the name and location from the parameter list. If none are present - you may wish to return all of the users, or none at all.

What is the default route request in Flask?

By default, a route only answers to GET requests. You can use the methods argument of the route() decorator to handle different HTTP methods. If GET is present, Flask automatically adds support for the HEAD method and handles HEAD requests according to the HTTP RFC.


2 Answers

Use flask.request.url to retrieve your requested url. Have a look at: http://flask.pocoo.org/docs/1.0/api/#flask.Request (or the v0.12 docs)

like image 80
MrLeeh Avatar answered Oct 06 '22 16:10

MrLeeh


You can use the base_url method on flask's request function.

from flask import Flask, request

app = Flask(__name__)

@app.route('/foo')
def index():
    return request.base_url
    

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

This returns the following if the app route is /foo:

http://localhost:5000/foo
like image 38
Neill Herbst Avatar answered Oct 06 '22 16:10

Neill Herbst