Python的Flask项目中获取请求用户IP地址 addr问题
彳亍261 人气:0Python 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可以做点什么
Python flask (request 请求)
注意参数是采用 request.values.get 获取
#!/usr/bin/python # -*- coding: UTF-8 -*- from flask import Flask, jsonify, abort, request app = Flask(__name__) result = [ { "code":"001", "desc":"success", "data":1 } ] @app.route('/') def hello_world(): return 'Hello World!' @app.route('/send/imgaddress', methods=['POST']) def create_task(): getdata = request.data.decode('utf-8') userImg = '' userdebugImg = '' userImg = request.values.get('user') userdebugImg = request.values.get('userdebug') print('userImg:', userImg) print('userdebugImg:', userdebugImg) result[0]["code"] = '001' return jsonify({'result': result}) if __name__ == "__main__": app.run(debug=True)
测试
http://127.0.0.1:5000/send/imgaddress?user=172.28.6.1&userdebug=172.28.6.0
同局域网跨电脑访问
可以注意到上面使用的 ip 是 127.0.0.1,那么使用本机电脑ip如何设置呢?
修改如下:
if __name__ == "__main__": app.run(host="0.0.0.0", debug=False)
允许跨组访问
app = Flask(__name__)
改为:
from flask_cors import CORS app = Flask(__name__) CORS(app, supports_credentials=True)
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
加载全部内容