Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve browser headers in Python

Tags:

python

tornado

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.

like image 631
James Avatar asked Feb 23 '12 20:02

James


People also ask

How do I get the header from a website in Python?

Try response.info() method to get the headers.

How do you request a header in Python?

To add HTTP headers to a request, you can simply pass them in a dict to the headers parameter. Similarly, you can also send your own cookies to a server using a dict passed to the cookies parameter.

What is Python Useragent?

user_agents is a Python library that provides an easy way to identify/detect devices like mobile phones, tablets and their capabilities by parsing (browser/HTTP) user agent strings. The goal is to reliably detect whether: User agent is a mobile, tablet or PC based device.

How do you use Python requests to fake a browser visit Aka and generate user agent?

To use Python requests to fake a browser visit with a generated user agent,, we can use the fake_useragent library. Then we get the user agent string we want from the ua object. Next, we call requests. get to make a request to the url with the headers .


2 Answers

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)
like image 110
mattbornski Avatar answered Oct 13 '22 13:10

mattbornski


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
like image 26
John Laibach Avatar answered Oct 13 '22 15:10

John Laibach