如何在烧瓶中获得当前的基本URI?

时间:2017-03-28 06:25:18

标签: python python-3.x url flask

在下面的代码中,我想将URL存储在变量中,以检查发生URL错误的错误。

@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)

输出:  **

* 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 -

**

我希望此消息"127.0.0.1 - - [28/Mar/2017 10:44:53] "GET /flights HTTP/1.1" 200 -"应存储在变量中,或者如何获取正在执行的当前URL。 谢谢

2 个答案:

答案 0 :(得分:11)

您可以在烧瓶的base_url功能上使用request方法。

from flask import Flask, request

app = Flask(__name__)


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


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

如果应用路由为/foo,则返回以下内容:

http://localhost:5000/foo

答案 1 :(得分:1)

使用flask.request.url检索您请求的网址。请查看:http://flask.pocoo.org/docs/1.0/api/#flask.Request(或v0.12 docs