日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

Python的Flask項(xiàng)目中獲取請(qǐng)求用戶(hù)IP地址?addr問(wèn)題_python

作者:彳亍261 ? 更新時(shí)間: 2023-02-09 編程語(yǔ)言

Python Flask項(xiàng)目中獲取請(qǐng)求用戶(hù)IP地址 addr

服務(wù)器直接部署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中啟動(dòng)Flask

這種情況下, 按照上面的代碼只能獲取到本服務(wù)器地址。需要使用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可以做點(diǎn)什么

Flask獲取用戶(hù)的ip,查詢(xún)用戶(hù)的登錄次數(shù),并且封ip

Python flask (request 請(qǐng)求)

注意參數(shù)是采用 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)

測(cè)試

http://127.0.0.1:5000/send/imgaddress?user=172.28.6.1&userdebug=172.28.6.0

同局域網(wǎng)跨電腦訪(fǎng)問(wèn)

可以注意到上面使用的 ip 是 127.0.0.1,那么使用本機(jī)電腦ip如何設(shè)置呢?

修改如下:

if __name__ == "__main__":
?? ?app.run(host="0.0.0.0", debug=False)

允許跨組訪(fǎng)問(wèn)

app = Flask(__name__)

改為:

from flask_cors import CORS
app = Flask(__name__)
CORS(app, supports_credentials=True)

總結(jié)

原文鏈接:https://blog.csdn.net/chichu261/article/details/102865692

欄目分類(lèi)
最近更新