2010-11-20 44 views

回答

27

我一起打了基于教程一个快速和肮脏的例子。它已经在我的本地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() 
+0

哇,真棒。日志不错,但给出了一个500服务器错误http://iantest123.appspot.com/ – 2010-11-20 04:00:05

+0

我不好 - 我错误地复制它。很棒! – 2010-11-20 04:02:33

28

尝试:

os.environ["REMOTE_ADDR"] 

或与Request Class variable

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

@pyfunc信不信由你,它没有错。 – systempuntoout 2010-11-20 03:37:45

+0

@pyfunc在downvoting之前,阅读人们如何使用os.environ。第二部分是在我的回答中,我回答了OP提出的更广泛的问题,然后被删除。放松一下,谢谢。 – systempuntoout 2010-11-20 03:44:06

+0

@pyfunc它是我答案的一部分,所以根本不需要编辑。 – systempuntoout 2010-11-20 03:49:35