【问题标题】:Retrieve browser headers in Python在 Python 中检索浏览器标头
【发布时间】:2012-02-23 20:39:07
【问题描述】:

关于如何在 Python Tornado 中获取用户的当前浏览器标题信息,我目前正在画一个空白?例如,在 PHP 中,您可以简单地查看 $_SERVER 数据。 Tornado 的替代方案是什么?

注意:How do I get the client IP of a Tornado request? 和“请求”对我不起作用。

【问题讨论】:

    标签: python tornado


    【解决方案1】:

    这是一个基于我的服务器的 sn-p,我们从请求中检索一些标头数据:

    class api(tornado.web.RequestHandler):
        def initialize(self, *args, **kwargs):
            self.remote_ip = self.request.headers.get('X-Forwarded-For', self.request.headers.get('X-Real-Ip', self.request.remote_ip))
            self.using_ssl = (self.request.headers.get('X-Scheme', 'http') == 'https')
        def get(self):
            self.write("Hello " + ("s" if self.using_ssl else "") + " " + self.remote_ip)
    

    【讨论】:

    • 这里有一些背景值得注意。 @James 可能会发现 self.request.protocol 不准确的原因是某些服务器设置(例如处理 SSL 的 Amazon ELB、其他类型的服务器端代理)在将内容传递到您的服务器之前会更改协议和 IP。使用这些代理提供的 X-Forwarded-For 和其他标头,您可以计算出浏览器实际请求的内容。
    • 另外,你应该知道客户端可以自己设置“X-Forwarded-For”,导致你接受这个值作为他的IP。所以你应该只在有设置这个标题的设置时才使用它,而不是一般。
    【解决方案2】:

    您可以使用类似于tornado/httpserver.py 的逻辑,或者只使用xheaders=True 创建tornado.httpserver.HTTPServer()

    # Squid uses X-Forwarded-For, others use X-Real-Ip
    ip = self.headers.get("X-Forwarded-For", self.remote_ip)
    ip = ip.split(',')[-1].strip()
    ip = self.headers.get(
        "X-Real-Ip", ip)
    if netutil.is_valid_ip(ip):
        self.remote_ip = ip
    # AWS uses X-Forwarded-Proto
    proto = self.headers.get(
        "X-Scheme", self.headers.get("X-Forwarded-Proto", self.protocol))
    if proto in ("http", "https"):
        self.protocol = proto
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-01
      • 2016-02-04
      • 1970-01-01
      • 2010-12-13
      相关资源
      最近更新 更多