0
我想將Facebook訂閱源添加到我的網站(僅限第一條最新的留言信息)。所以我創建了這個模型:未更新的模型字段
class FacebookFeed(models.Model):
checked = models.DateTimeField(name="Time Checked", auto_now_add=True)
message = models.TextField(name="Message", null=True)
author = models.CharField(name="Author", max_length=50)
date = models.DateTimeField(name="Post time", null=True)
def save(self, *args, **kwargs):
queryset = FacebookFeed.objects.all()
if(queryset):
return
else:
#super(FacebookFeed, self).save()
super(FacebookFeed, self).save(*args, **kwargs)
def check_time(self):
if self.checked:
now = datetime.utcnow()
diff = now - self.checked
if diff.seconds >= 3600:
return True
return False
我想每個整小時只執行一次feed更新,所以這就是check_time方法的作用。現在,我認爲正在使用的功能:
def getSocialFeed():
#facebook
fb = FacebookFeed.objects.all()
created = False
if not fb:
logging.debug('not fb')
f = FacebookFeed();
f.save()
created = True
fb = FacebookFeed.objects.all()[0]
if fb.check_time() or created:
logging.debug('check time true')
conn = httplib.HTTPSConnection("graph.facebook.com")
conn.request("GET", '/UserName/feed')
r = conn.getresponse()
jsonResult = r.read()
json = simplejson.loads(jsonResult)
json = json['data']
notAuthor = False
i = 0
if json:
logging.debug('json')
while notAuthor is not True:
logging.debug('while')
if json[i]['from']['name'] == 'UserName':
logging.debug('result %s' % (json[i]['from']['name'] == 'UserName'))
logging.debug('message: %s' % json[i]['message'])
date = json[i]['created_time'].replace('T', ' ')
logging.debug('date: %s' % date)
date = date[0:-5]
logging.debug('date2: %s' % date)
logging.debug('fb: %s' % fb)
fb.message = json[i]['message']
fb.date = datetime.strptime(date, "%Y-%m-%d %H:%M:%S")
fb.author = 'UserName'
try:
x = fb.save()
logging.debug('x: %s' % x)
notAuthor = True
logging.debug(fb.message)
logging.debug(notAuthor)
except Exception, e:
logging.debug('e: %s' % e)
else:
i+=1
f = FacebookFeed.objects.all()[0]
logging.debug('msg: %s' % f.message)
我已經得到了解析JSON響應,提取所有我想要的數據,但不知何故我的對象不corretcly保存。任何想法爲什麼?
這是調試日誌:
2011-05-27 14:15:24,671 DEBUG not fb
2011-05-27 14:15:24,681 DEBUG check time true
2011-05-27 14:15:26,607 DEBUG json
2011-05-27 14:15:26,607 DEBUG while
2011-05-27 14:15:26,607 DEBUG result True
2011-05-27 14:15:26,607 DEBUG message: sometext
2011-05-27 14:15:26,607 DEBUG date: 2011-05-26 14:42:36+0000
2011-05-27 14:15:26,607 DEBUG date2: 2011-05-26 14:42:36
2011-05-27 14:15:26,607 DEBUG fb: FacebookFeed object
2011-05-27 14:15:26,608 DEBUG x: None
2011-05-27 14:15:26,608 DEBUG sometext
2011-05-27 14:15:26,608 DEBUG True
2011-05-27 14:15:26,608 DEBUG msg: None
爲了使您的代碼更易於管理,你應該看看[get_or_create文檔](https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create)。 – LaundroMat 2011-05-27 13:15:13