【发布时间】:2016-03-26 17:43:39
【问题描述】:
我想在views.py文件中创建一个视图函数,它在特定的时间间隔内运行,而不依赖于请求对象,这在django中是可能的 我正在做一个使用 bs4、request 和 django 抓取网络数据的简单项目,到目前为止,我能够抓取数据并将其呈现给我的 django views.py。
从不同网站抓取的数据遵循以下格式
news_title = 'were-these-remote-wild-islands'
news_url = 'http://bbc.co.uk/travel/see-the-dark-side-of-climate-change'
我的视图函数有以下代码行
from .bbc import bbc_crawler
from .models import News
def collect_data(request):
'''
aggregrate all the news from each
news portal
'''
allnews = []
#return dict obj {'title':'climate change', 'url':'http://bbc.co.uk'}, {'title':'t', 'url':'http://url.com'}
allnews.append(bbc_crawler())
for news in allnews:
for eachnews,link in news.items():
#Problem is for every request the same data pushed to the database, need a solution to push the data after every 5 minutes, without depending on this function
News.objects.create(title=eachnews, url=link, source=source)
return render(request, 'news/index.html', {'allnews':allnews, 'source': source})
上面代码的问题是,上面的视图函数只有在我们访问指向这个 urls.py 文件中定义的视图函数的 url 时才会运行
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.news, name="index"),
]
当我刷新该 url 时,每次相同的重复数据都会存储在数据库中。
我想要每5分钟运行一次爬虫并将爬取的数据保存到数据库中的解决方案。
在views.py文件的哪里运行爬虫,这样我可以每5分钟保存一次数据,不重复数据,不依赖于请求对象。我想每5分钟将爬取的数据保存在django数据库中,
如何做到这一点,目前的问题是只有在我们刷新或请求页面时才保存数据。
我不依赖数据库中的请求对象来保存数据
【问题讨论】:
-
配置一个 celery 任务,从视图中调用它,然后在那里重复。
-
好的,我会尝试这样做
标签: python django django-models web-scraping django-views