【问题标题】:How to obtain the caller's IP address in Flask/Connexion?如何在 Flask/Connexion 中获取调用者的 IP 地址?
【发布时间】:2021-02-02 13:24:48
【问题描述】:

我正在使用 OpenAPI 3.0 规范 (swagger.yml) 并使用 Swagger Codegen 创建相应的 Python Flask 应用程序存根。这就是我运行应用程序以公开我的 Swagger API 的方式:

app = connexion.App(__name__, specification_dir='./swagger/')
app.app.json_encoder = encoder.JSONEncoder
app.add_api('swagger.yaml', arguments={'title': 'My Test API'})
# add CORS support to send Access-Control-Allow-Origin header
CORS(app.app)

到目前为止一切顺利。应用程序逻辑在由x-openapi-router-controller: swagger_server.controllers.user_controller 链接的生成的 Python 存根中处理。

但是,我现在需要访问应用程序本身中的 HTTP 请求特定信息,例如根据 HTTP_CLIENT_IP 地址

做出不同的反应

如何在我的控制器端点中获取该信息?

【问题讨论】:

标签: python flask http-headers swagger connexion


【解决方案1】:

使用 Flask 的 request 上下文。

例如,要获取 HTTP_CLIENT_IP,请使用:

from flask import request

http_client_ip = request.remote_addr

你可以阅读更多关于requesthere的信息。

【讨论】:

    【解决方案2】:

    附加了两个相关链接,解决了request header parameters 上的同一问题以及如何将connexion does not forward them 用于自定义控制器。我最终通过

    手动访问它们
    access_token = connexion.request.headers['access_token']
    

    【讨论】:

      猜你喜欢
      • 2010-09-12
      • 2011-04-19
      • 2011-04-15
      • 1970-01-01
      • 2010-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多