在Google App Engine + Python中获取IP地址

时间:2010-11-20 03:32:57

标签: python google-app-engine

我正在寻找Google App Engine和Python中等效的<?php $_SERVER['REMOTE_ADDR'] ?>

谢谢!

3 个答案:

答案 0 :(得分:30)

我根据教程打了一个快速而又脏的例子。它已在我当地的appengine sdk上测试过。您应该能够根据自己的需要进行调整:

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()

答案 1 :(得分:29)

尝试:

os.environ["REMOTE_ADDR"]

或使用Request Class variable

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

答案 2 :(得分:0)

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

对我有用,我使用了appengine python3.7标准环境。