【问题标题】:Get IP address in Google App Engine + Python在 Google App Engine + Python 中获取 IP 地址
【发布时间】:2011-05-12 23:28:21
【问题描述】:

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

谢谢!

【问题讨论】:

    标签: python google-app-engine


    【解决方案1】:

    我根据教程一起拍了一个快速而肮脏的例子。它已经在我的本地 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()
    

    【讨论】:

    • 哇,太棒了。记录正常,但给出 500 服务器错误 iantest123.appspot.com
    • 我的错——我抄错了。效果很好!
    【解决方案2】:

    尝试:

    os.environ["REMOTE_ADDR"]
    

    或使用Request Class variable:

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

    【讨论】:

    • @pyfunc 在投反对票之前,请阅读人们如何使用 os.environ。第二部分在我的回答中,我正在回答 OP 提出的一个更广泛的问题,然后被删除。稍微放松一下,谢谢。
    • @pyfunc offsound 获得了接受的标记,这很有趣。我只为你得到了-1。这也很有趣。
    • @systemppuntoout - 我同意您的答案可能应该是公认的答案,因为它在技术上是第一个并且简洁地回答了 Ian 的问题。我实际上是在回答 Ian 在此之前发布的一个非常相似但更广泛的问题,并且在我发布答案之前显然已删除。然后过了一会儿我发现了这个新问题,所以仍然保存了代码,我把它贴在这里。
    • +1; OP 要求等效于 PHP 对环境的访问;不预设使用 webapp
    • 我在 appengine python 3.7 标准环境中使用 aiohttp,对我不起作用.. "File "/opt/python3.7/lib/python3.7/os.py",第 678 行,在 getitem raise KeyError(key) from None KeyError: 'REMOTE_ADDR"
    【解决方案3】:
    request.headers['X-AppEngine-User-IP']
    

    适合我,我使用 appengine python3.7 标准环境。

    【讨论】:

    【解决方案4】:
    猜你喜欢
    • 2023-04-04
    • 2012-06-24
    • 2013-06-17
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-01
    相关资源
    最近更新 更多