簡體   English   中英

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

[英]Get IP address in Google App Engine + Python

我正在尋找相當於Google App Engine和Python中的<?php $_SERVER['REMOTE_ADDR'] ?>

謝謝!

我根據教程打了一個快速而又臟的例子。 它已在我當地的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()

試試:

os.environ["REMOTE_ADDR"]

或者使用Request Class變量

class MyRequestHandler(webapp.RequestHandler):
    def get(self):
        ip = self.request.remote_addr
request.headers['X-AppEngine-User-IP']

適合我,我使用appengine python3.7標准環境。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM