FastAPI(starlette)获得客户端真实IP [英] FastAPI (starlette) get client real IP

查看:1000
本文介绍了FastAPI(starlette)获得客户端真实IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在FastAPI上有一个API,当他请求我的页面时,我需要获取客户端的真实IP地址.

I have an API on FastAPI and i need to get the client real IP address when he request my page.

我很愿意使用starlette请求.但是它返回我的服务器IP,而不是客户端远程IP.

I'm ty to use starlette Request. But it returns my server IP, not client remote IP.

我的代码:

@app.post('/my-endpoint')
async def my_endpoint(stats: Stats, request: Request):
    ip = request.client.host
    print(ip)
    return {'status': 1, 'message': 'ok'}

我做错了什么?如何获取真实IP(例如在Flask request.remote_addr中)?

What i'm doing wrong? How to get real IP (like in Flask request.remote_addr)?

推荐答案

request.client 应该可以工作,除非您在代理服务器(例如nginx)后面运行,请使用uvicorn的--proxy-headers 标志接受这些传入的标头,并确保代理转发它们.

request.client should work, unless you're running behind a proxy (e.g. nginx) in that case use uvicorn's --proxy-headers flag to accept these incoming headers and make sure the proxy forwards them.

这篇关于FastAPI(starlette)获得客户端真实IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆