Ian McIntyre Silber
Ian McIntyre Silber

Reputation: 5663

Get IP address in Google App Engine + Python

I'm looking for the equivalent of <?php $_SERVER['REMOTE_ADDR'] ?> in Google App Engine and Python.

Thanks!

Upvotes: 27

Views: 15309

Answers (4)

xaphod
xaphod

Reputation: 6804

The official answer from Google is here:

https://cloud.google.com/appengine/docs/standard/python3/reference/request-response-headers

Upvotes: 0

user4985526
user4985526

Reputation:

request.headers['X-AppEngine-User-IP']

works for me, I use appengine python3.7 standard env.

Upvotes: 0

systempuntoout
systempuntoout

Reputation: 74064

Try with:

os.environ["REMOTE_ADDR"]

or with the Request Class variable:

class MyRequestHandler(webapp.RequestHandler):
    def get(self):
        ip = self.request.remote_addr

Upvotes: 29

Josh
Josh

Reputation: 2196

I slapped a quick and dirty example together based on the tutorial. It's been tested on my local appengine sdk. You should be able to adapt it to your needs:

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class Log(db.Model):
    access_time = db.DateTimeProperty(auto_now_add=True)
    ip_address = db.StringProperty()

class MainPage(webapp.RequestHandler):
    def get(self):

        # obtain ip address
        ip = self.request.remote_addr

        # create a new Log record
        log = Log()

        # assign ip address to the ip_address field
        log.ip_address = ip

        # no need to set access_time because 
        # of the auto_now_add=True setting defined in the Log model

        # save to the datastore
        log.put()

        # output 
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Logged your visit from ip address %s' % ip)

class LogPage(webapp.RequestHandler):
    def get(self):
        logs = Log.all()

        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Ip addresses: ')
        for log in logs:
            self.response.out.write(log.ip_address + ',')

application = webapp.WSGIApplication([('/', MainPage), ('/logs', LogPage)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

Upvotes: 30

Related Questions