티스토리 뷰

반응형

1. 가상환경 설정 및 장고 설치

#가상환경 설정
python3 -m venv venv
#가상환경 ON
source ./venv/bin/activate
#django 설치
pip install django
#프로젝트 설치
django-admin startproject batch .

디렉터리 구조

도커환경에 맞게 구현하기 위해 해당 디렉터리 구조를 변경하였다.

 

2. django settings.py 

#장고 프로젝트 내의 시간을 한국 시간으로 설정
LANGUAGE_CODE = 'ko'

TIME_ZONE = 'Asia/Seoul'

USE_I18N = True

USE_L10N = True

USE_TZ = True

 

 

# celery와 관련된 환경설정 
CELERY_BROKER_URL = 'redis://redis:6379/0'
CELERY_RESULT_BACKEND = 'redis://redis:6379/0'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'Asia/Seoul'
CELERY_ENABLE_UTC = False

 

3. worker.py 파일 생성(project 디렉터리 안에 존재)

 

from __future__ import absolute_import
import os
from celery import Celery
from celery.schedules import crontab

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "batch.settings") ## 우측의 batch는 독자의 프로젝트이름으로 대체

app = Celery('batch') #이 또한 독자의 프로젝트로 대체

app.config_from_object('django.conf:settings', namespace="CELERY") 
app.autodiscover_tasks()


@app.task(bind=True) # 잘 되고 있나 확인하기 위해 설정
def debug_task(self):
    print('Request: {0!r}'.format(self.request))


app.conf.beat_schedule = { ## 셀러리 비트로서 일정 시간마다 업무를 주어주도록 설정
    'crwal_update_searchtrend': {
        'task': 'Crawl.tasks.update_searchtrend',
        'schedule': crontab(minute=0, hour=0),
    },
    'crwal_update_news': {
        'task': 'Crawl.tasks.update_instagram',
        'schedule': crontab(minute=0,hour=0),
    },
    'crwal_update_insta': {
        'task': 'Crawl.tasks.update_news',
        'schedule': crontab(minute=0,hour=0),
    },
}

#crontab에 관한 설정은 이 분 글 참조 

https://wangin9.tistory.com/entry/django-celery

 

[django celery]테스크 주기 설정하기

Celery Beat Celery beat 는 스케줄러로써 규칙적인 간격으로 작업을 시작한다. 찾아보니 원하는 초,분,시간 단위로 설정할 수도 있고 일주일에 한번, 이런식으로도 crontab 등의 api를 이용해서 설정할

wangin9.tistory.com

3-1. beat_schedule 안의 task 설정

해당 task는 my_app.tasks.my_function 식으로 작성하면 된다.

 

 

4. 업무 할당(해당 파일 이름은 tasks.py로 해야한다.)

from celery import shared_task

@shared_task
def update_searchtrend():
    table = DynamoTable(NAVER_SEARCH_TABLENAME)
    update_search_keywords_data(table)

와 같이 "@shared_task" 어노테이션을 붙여준다.

 

 

5. django project dockerfile 작성 

FROM python:3.8

RUN apt-get -y update
RUN mkdir /srv/code
ADD . /srv/code

RUN chmod +x /srv/code/start_flower.sh

WORKDIR /srv/code
ADD requirements.txt /srv/code
RUN python3 -m pip install --upgrade pip
RUN pip install -r requirements.txt

작업 폴더를 /srv/code로 설정하였고, 나중에 flower를 작동시키기 위해 shell script에 권한을 부여하였다.

 

6. start_flower.sh 작성

#!/bin/sh

until timeout 10s celery -A batch inspect ping; do
    >&2 echo "Celery workers not available"
done

echo 'Starting flower'
celery flower -A batch --broker=redis://redis:6379/0

 

해당 celery가 완전히 작동하고 나서 flower가 작동하는 순서로 진행하였다.

 

 

7. __init__.py 작성 

from __future__ import absolute_import, unicode_literals

from .worker import app as celery_app

__all__ = ("celery_app",)

 

 

 

8. docker-compose.yml 작성

version: "3.3"

services:
  crawl:
    build: ./Batch
    container_name: data.crawl
    command: python manage.py runserver 0.0.0.0:8000
    ports:
    - "8000:8000"
    env_file:
      - .env

  worker:
    container_name: data.worker
    restart: always
    build: ./Batch
    command: celery -A batch worker --loglevel=DEBUG -P prefork
    env_file:
      - .env
    depends_on:
      - redis

  beat:
    build: ./Batch
    container_name: data.beat
    command: celery -A batch beat -l info
    depends_on:
      - redis
      - worker

  redis:
    container_name: data.broker
    image: redis:alpine
    ports:
    - "6379:6379"

  monitor:
    container_name: data.monitor
    build: ./Batch
    restart: on-failure
    ports:
      - "5555:5555"
    command: sh -c "/srv/code/start_flower.sh"
    env_file:
      - .env
    depends_on:
      - redis
      - worker
      - beat

 

 

반응형
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함