14

I'm currently drawing a blank as how to get the current browser header information for a user in Python Tornado? For example, in PHP you'd simple view the $_SERVER data. What is Tornado's alternative?

Note: How do I get the client IP of a Tornado request? and the "request" does not work for me.

asked Feb 23, 2012 at 20:39

2 Answers 2

26

Here's a snippet based off of a server I have where we retrieve some header data from the request:

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)
answered Feb 23, 2012 at 22:39
Sign up to request clarification or add additional context in comments.

2 Comments

It's worth noting some background here. The reason @James might find self.request.protocol to be inaccurate is that some server setups (eg Amazon ELBs which handle SSL, other types of server-side proxies) change the protocol and IP before passing things onto your server. Using X-Forwarded-For and other headers provided by these proxies allows you to work out what the browser actually requested.
Also, you should know that the client can set "X-Forwarded-For" by himself, leading you to accept this value as his IP. So you should only use this if there is a setup that sets this header, not in general.
3

You can use logic similar to tornado/httpserver.py or just create tornado.httpserver.HTTPServer() with xheaders=True.

# 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
Alexis Tyler
9866 gold badges32 silver badges51 bronze badges
answered Dec 10, 2014 at 21:21

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.