烧瓶将访问者ip打印到控制台或另存为JSON文件

时间:2018-08-09 10:19:42

标签: python flask

我有一个flask应用程序,我想在此获取访问者的IP地址,然后将其打印到控制台或将其保存到JSON文件中。

问题在于,每当尝试执行缩进错误时,都会出现意外错误。

@app.route('/')
def index():
    requester = request.remote_addr
    print(requester)
    return render_template('index.html')

我试图使请求者对象超出我的索引函数,但是这会导致另一个错误,例如:

RuntimeError: Working outside of request context.

This typically means that you attempted to use functionality that needed
an active HTTP request.  Consult the documentation on testing for
information about how to avoid this problem.

我该如何解决这个问题,以便获得一个保存用户IP地址的全局变量?

1 个答案:

答案 0 :(得分:0)

如果您提供了确切的“意外缩进”错误,那就更好了。如错误所示,您可能在某处有错误的缩进。也许混合制表符和空格?

下面的代码示例适用于我并打印远程地址。我正在使用Python 3.6和Flask 1.0.2。

from flask import Flask, request, render_template

app = Flask(__name__)


@app.route('/')
def index():
    requester = request.remote_addr
    print(requester)
    return render_template('index.html')


app.run()

是的,您只能在处理请求的部分代码中使用flask.request。为什么需要全局变量来保存访问者IP?您始终可以将requester变量传递给某个函数。

另一件事:使用remote_addr来访者IP时要小心。仅当您的客户直接联系您的flask应用程序时,此方法才有效。如果Flask应用位于Web服务器或负载均衡器(例如nginx,HAproxy或ELB)之后,则必须设置Web服务器以正确转发访问者IP。