2010-11-20 42 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