Python的Flask项目中获取请求用户IP地址 addr

服务器直接部署Flask

import logging
from flask import Flask, render_template, request

# Initialize the Flask application
app = Flask(__name__)

# Default route, print user's IP
@app.route('/')
def index():
	 ip = request.remote_addr
	 logging.debug(ip)
	 return render_template('index.html', user_ip=ip)


if __name__ == '__main__':
	 app.run(host="0.0.0.0", port=80)

Docker中Nginx代理Gunicorn中启动Flask

这种情况下, 按照上面的代码只能获取到本服务器地址。需要使用werkzeug.middleware.proxy_fix

import logging
from flask import Flask, render_template, request
from werkzeug.middleware.proxy_fix import ProxyFix

# Initialize the Flask application
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app, num_proxies=1)


# Default route, print user's IP
@app.route('/')
def index():
	 ip = request.remote_addr
	 logging.debug(ip)
	 return render_template('index.html', user_ip=ip)

查到IP可以做点什么

Flask获取用户的ip,查询用户的登录次数,并且封ip

你可能感兴趣的:(Python,解决方案,Flask,ip,flask,请求地址,docker,flask,ip,nginx,flask,addr)