我想将facebook Feed添加到我的网站(只有第一个最新的留言信息)。所以我创建了模型:
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响应,提取了我想要的所有数据但不知何故我的对象没有得到相应的保存。有什么想法吗?
这是调试日志:
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
答案 0 :(得分:0)
def save(self, *args, **kwargs):
queryset = FacebookFeed.objects.all()
if(queryset):
return
else:
#super(FacebookFeed, self).save()
super(FacebookFeed, self).save(*args, **kwargs)
我认为if(queryset)
总是True
如果它包含或不包含记录,要检查空查询集,请改用<{1}}