每日一句功能簡單實現

2021-08-23 14:11:23 字數 1256 閱讀 2386

每天自動獲取最新一條。

封裝了下**:

def get_today_word():

today = datetime.date.today()

word=word.objects.filter(add_time__year=today.year,

add_time__month=today.month,

add_time__day=today.day).first()

if word:

return (json.loads(word.content),today.weekday()+1)

else:

s = requests.session()

url = ""

data =

ret = s.post(url=url, data=data).content.decode('utf-8')

word.objects.create(content=ret)

return (json.loads(ret),today.weekday()+1)

返回格式是乙個元祖,第乙個引數是從韓少的one介面抓回來的json字串。

第二個引數是自己拼出的今天的星期。

建立了一張word資料表,把每天的資料儲存下來;另乙個好處是,只需要第一次去爬取,第二次開啟頁面,直接從資料庫獲取json資料就行了。

class word(models.model):

'''每日一句

'''content = models.textfield(verbose_name=u'json內容')

add_time = models.datetimefield(default=datetime.now, verbose_name="新增時間")

class meta:

verbose_name = "每日一句"

verbose_name_plural = verbose_name

def __str__(self):

return self.add_time.strftime('%y-%m-%d')

view中呼叫獲取:

word = get_today_word()
傳到template中只需要render對應的字段就行了。

每日一句} --- }

每日一句 2014 8 26

when life gets hard and you want to give up,remember that life is full of ups and downs,and without the downs,the ups would mean nothing 當生活很艱難,你想要放棄的...

每日一句 2014 9 1

people with goals succeed because they know where they re going 有目標的人能夠成功,因為他們知道他們要去哪 people with goals succeed because they know where they re going ...

190405每日一句

從未消失,從未遠離,你就在我的心裡。與成功相比,失敗的意義要深刻的多。喬治 克魯尼 演員 instructive n str kt v tem4 gre adj.有益的 教育性的 增長知識的 有啟發性的 英英釋義 something that is instructive gives useful ...