2016-11-17 5 views
2

안녕하세요 stackoverflow 커뮤니티, 웹 사이트를 긁어 모으고 데이터베이스 (MOVIE) 모델의 일부로 저장해야하는 cron 작업을 예약하는 데 문제가 있습니다. 문제는 Procfile을 실행하기 전에 모델이로드 된 것 같습니다. 백그라운드에서 내부적으로 실행되고 긁힌 정보를 데이터베이스에 저장하는 cron 작업을 어떻게 작성해야합니까? 여기 내 코드는 다음과 같습니다문제 장고 프로젝트에 apscheduler를 사용하여 Procfile (Heroku)에서 Cron 작업 정의

Procfile :

web: python manage.py runserver 0.0.0.0:$PORT 
    scheduler: python cinemas/scheduler.py 

scheduler.py :

# More code above 
from cinemas.models import Movie 
from apscheduler.schedulers.blocking import BlockingScheduler 
sched = BlockingScheduler() 

@sched.scheduled_job('cron', day_of_week='mon-fri', hour=0, minutes=26)  
def get_movies_playing_now(): 
    global url_movies_playing_now 
    Movie.objects.all().delete() 
    while(url_movies_playing_now): 
    title = [] 
    description = [] 
    #Create BeatifulSoup Object with url link 
    s = requests.get(url_movies_playing_now, headers=headers) 
    soup = bs4.BeautifulSoup(s.text, "html.parser") 
    movies = soup.find_all('ul', class_='w462')[0] 

    #Find Movie's title 
    for movie_title in movies.find_all('h3'): 
     title.append(movie_title.text) 
    #Find Movie's description 
    for movie_description in soup.find_all('ul', 
              class_='w462')[0].find_all('p'): 
     description.append(movie_description.text.replace(" [More]",".")) 

    for t, d in zip(title, description): 
     m = Movie(movie_title=t, movie_description=d) 
     m.save() 

    #Go to the next page to find more movies 
    paging = soup.find(class_='pagenating').find_all('a', class_=lambda x: 
                 x != "inactive") 
    href = "" 
    for p in paging: 
     if "next" in p.text.lower(): 
      href = p['href'] 
    url_movies_playing_now = href 

sched.start() 
# More code below 

from django.db import models 

영화관/models.py : 이것은 내가 무엇입니까 오류가

#Create your models here. 

class Movie(models.Model): 
    movie_title = models.CharField(max_length=200) 
    movie_description = models.CharField(max_length=20200) 

작업이 실행되었습니다.

2016-11-17T17 : 57 : 06.074914 + 00 : 00 app [scheduler.1] : 추적 (가장 최근 통화 마지막) : 2016-11-17T17 : 57 : 06.074931 + 00 : 00 app [scheduler. 1] : 파일 "cinemas/scheduler.py", 2 행 2016-11-17T17 : 57 : 06.075058 + 00 : 00 app [scheduler.1] : import cineplex 2016-11-17T17 : 57 : 06.075060+ 00:00 app [scheduler.1] : 파일 "/app/cinemas/cineplex.py", 줄 1, 2016-11-17T17 : 57 : 06.075173 + 00 : 00 app [scheduler.1] : from cinemas. 모델 가져 오기 동영상 2016-11-17T17 : 57 : 06.075196 + 00 : 00 app [scheduler.1] : 파일 "/app/cinemas/models.py", 줄 5, 2016-11-17T17 : 57 : 06.075295 +00 : 00 앱 [scheduler.1] : 클래스 동영상 (models.Model) : 2016-11-17T17 : 57 : 06.075297 + 00 : 00 app [scheduler.1] : 파일 " /app/.heroku/python/lib/python3.5/site-packages/base.py ", 줄 105, 2016-11-17T17 : 57 : 06.075414 + 00 : 00 app [scheduler.1] : app_config = apps.get_containing_app_config (module) 2016-11-17T17 : 57 : 06.075440 + 00 : 00 app [scheduler.1] : 파일 "/app/.heroku/python/lib/python3. 5/site-packages/django/apps/registry.py ", 237 줄, get_containing_app_config 2016-11-17T17 : 57 : 06.075585 + 00 : 00 app [scheduler.1] : self.check_apps_ready() 2016-11 -17T17 : 57 : 06.075586 + 00 : 00 app [scheduler.1] : 파일 "/app/.heroku/python/lib/python3.5/site-packages/django/apps/registry.py", 124 줄 애플 리케이션이 아직로드되지 않았습니다. " 2016-11-17T17 : 57 : 06.075726 + 00 : 00 app [sch eduler.1] : django.core.exceptions.AppRegistryNotReady : 앱이 아직로드되지 않았습니다.

모델 개체를 포함하지 않으면 Cron 작업이 정상적으로 작동합니다. Model 객체를 사용하여 매일이 작업을 실패없이 실행해야합니까?

감사

그냥 장고 패키지, 모델 등을 가져올 수 있기 때문이다

답변

2

; Django 내부는 manage.py에서 트리거 된 초기화가 필요합니다. 직접 시도하고 재 작성하지 말고 항상 웹 관리가 아닌 명령을 사용자 지정 관리 명령으로 작성합니다 (https://docs.djangoproject.com/en/1.10/howto/custom-management-commands/ 참조). 앱이 cinemas 경우 예를 들어, 다음과 같습니다

  • ./cinemas/management/commands/scheduler.py을 만듭니다. 해당 파일에서
  • , 서브 클래스 django.core.management.base.BaseCommand는 그 클래스에서
  • , handle()를 오버라이드 (즉, 서브 클래스는 Command를 호출해야합니다).당신이
  • sched.start() 당신의 Procfile 다음 데 도움이 scheduler: python manage.py scheduler

희망을 가질 것이다 전화 할 위치를 귀하의 경우에는, 그입니다.

+0

고마워요! 이것은 나를 위해 작동 :) –

0

당신은 장고 문서 it says

당신이 장고의 구성 요소를 사용하는 경우 "독립에 sceduler.py

import django 
django.setup() 

의 맨 위에 다음 줄을 추가로 문제를 해결할 수 "- 예를 들어 일부 장고 템플릿을로드하고 렌더링하는 Python 스크립트를 작성하거나 ORM을 사용하여 데이터를 가져 오는 경우 - 설정을 구성하는 것 외에 하나 더 필요한 단계가 있습니다.

DJANGO_SETTINGS_MODULE을 설정하거나 configure()를 호출 한 후 django.setup()을 호출하여 설정을로드하고 Django의 응용 프로그램 레지스트리를 채워야합니다. 예를 들어 :

import django 
from django.conf import settings 
from myapp import myapp_defaults 

settings.configure(default_settings=myapp_defaults, DEBUG=True) 
django.setup() 

# Now this script or any imported module can use any part of Django it needs. 
from myapp import models 

나는 설정 변수가 나의 스케줄러에 추가하지 않은으로 DJANGO_SETTINGS_MODULE을 설정합니다.