Python 如何在 Flask 中获取当前的基本 URI?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43062047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:28:14  来源:igfitidea点击:

How can i get current base URI in flask?

pythonpython-3.xurlflask

提问by Ravi Bhushan

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

在下面的代码中,我想将 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)

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. Thank You

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

回答by Neill Herbst

You can use the base_urlmethod on flask's requestfunction.

您可以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()

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

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

http://localhost:5000/foo

回答by MrLeeh

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)

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