Skip to content

Commit

Permalink
添加celery支持
Browse files Browse the repository at this point in the history
  • Loading branch information
kagxin committed Aug 2, 2019
1 parent c769b7f commit 13ea24f
Show file tree
Hide file tree
Showing 20 changed files with 175 additions and 12 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# pycharm IDE
.idea/

# celerybeat.pid
celerybeat-schedule
*.pid
# vscode IDE
.vscode/

Expand Down
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,17 @@ class DefaultResultsSetPagination(PageNumberPagination):
python manage.py runscript sayhello
```

### celery
*celery worker*
```bash
celery -A settings worker -l info
```
*celery beat*

```bash
celery -A settings beat -l info
```

## 使用docker启动工程

* build 镜像,并启动
Expand Down
Empty file added apps/schedule/__init__.py
Empty file.
3 changes: 3 additions & 0 deletions apps/schedule/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
5 changes: 5 additions & 0 deletions apps/schedule/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.apps import AppConfig


class ScheduleConfig(AppConfig):
name = 'schedule'
Empty file.
3 changes: 3 additions & 0 deletions apps/schedule/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.db import models

# Create your models here.
12 changes: 12 additions & 0 deletions apps/schedule/tasks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import logging
from settings import celery_app

log = logging.getLogger('scripts')


@celery_app.task()
def add(a, b):
c = a + b
print('{}'.format(c))
log.info('{}'.format(c))
return c
3 changes: 3 additions & 0 deletions apps/schedule/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
11 changes: 11 additions & 0 deletions apps/schedule/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from apps.schedule.views import *

router = DefaultRouter()
router.register('task', CreateScheduleTask, basename='task')


urlpatterns = [
path('', include(router.urls)),
]
51 changes: 51 additions & 0 deletions apps/schedule/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
from apps.utils.view.viewsets import ModelViewSet
from django_celery_beat.models import CrontabSchedule, PeriodicTask
from rest_framework import serializers


class CrontabScheduleSerializer(serializers.ModelSerializer):

def create(self, validated_data):
schedule, _ = CrontabSchedule.objects.get_or_create(**validated_data)
return schedule

class Meta:
model = CrontabSchedule
exclude = ['timezone', ]


class CreateScheduleTask(ModelViewSet):
permission_classes = ()
authentication_classes = ()
serializer_class = CrontabScheduleSerializer
queryset = CrontabSchedule.objects.all()

def perform_create(self, serializer):
"""
生成一个新的定时任务就是新建一条PeriodicTask记录,
修改settings timezone 重新执行
>>> from django_celery_beat.models import PeriodicTasks
>>> PeriodicTasks.changed()
参考文档 https://django-celery-beat.readthedocs.io/en/latest/
:param serializer:
:return:
"""
schedule = serializer.save()
import uuid
PeriodicTask.objects.create(
crontab=schedule,
name=uuid.uuid1().__str__(),
task='apps.schedule.tasks.add',
)


"""
post
{
"minute": "*",
"hour": 3,
"day_of_week": "*",
"day_of_month": "*",
"month_of_year": "*"
}
"""
2 changes: 1 addition & 1 deletion apps/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from django.conf import settings

urlpatterns = [
path('admin', admin.site.urls),
path('admin/', admin.site.urls),
path('api/v1/', include('apps.v1_urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \
+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
3 changes: 2 additions & 1 deletion apps/v1_urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@

urlpatterns = [
path('demo/', include('apps.demo.urls')),
path('account/', include('apps.account.urls'))
path('account/', include('apps.account.urls')),
path('schedule/', include('apps.schedule.urls'))
]
4 changes: 3 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,6 @@ djangorestframework-filters==1.0.0.dev0
ipython==7.6.1
Pillow==6.1.0
django-aliyun-oss2-storage==0.1.5
django-extensions==2.2.1
django-extensions==2.2.1
celery==4.3.0
django-celery-beat==1.5.0
5 changes: 5 additions & 0 deletions settings/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from __future__ import absolute_import, unicode_literals

# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import celery_app
17 changes: 17 additions & 0 deletions settings/celery.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.settings')

celery_app = Celery('django-project-template')

# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
# should have a `CELERY_` prefix.
celery_app.config_from_object('django.conf:settings', namespace='CELERY')

# Load task modules from all registered Django app configs.
celery_app.autodiscover_tasks()
12 changes: 10 additions & 2 deletions settings/local.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,15 @@
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://{}:6379/1".format(redis_host),
"LOCATION": "redis://{}/1".format(redis_host),
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"PASSWORD": ""
}
},
"token": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/2",
"LOCATION": "redis://{}/2".format(redis_host),
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"PASSWORD": "",
Expand Down Expand Up @@ -60,3 +60,11 @@
# DEFAULT_FILE_STORAGE = 'aliyun_oss2_storage.backends.AliyunMediaStorage'
# staticfile将自动上传
# STATICFILES_STORAGE = 'aliyun_oss2_storage.backends.AliyunStaticStorage'

# ==================
# = celery
# ==================
CELERY_BROKER_URL = 'redis://{}/1'.format(redis_host)
CELERY_RESULT_BACKEND = 'redis://{}/1'.format(redis_host)


12 changes: 10 additions & 2 deletions settings/production.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,15 @@
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://{}:6379/1".format(redis_host),
"LOCATION": "redis://{}/1".format(redis_host),
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"PASSWORD": ""
}
},
"token": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/2",
"LOCATION": "redis://{}/2".format(redis_host),
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"PASSWORD": "",
Expand Down Expand Up @@ -60,3 +60,11 @@
# DEFAULT_FILE_STORAGE = 'aliyun_oss2_storage.backends.AliyunMediaStorage'
# staticfile将自动上传
# STATICFILES_STORAGE = 'aliyun_oss2_storage.backends.AliyunStaticStorage'

# ==================
# = celery
# ==================
CELERY_BROKER_URL = 'redis://{}/1'.format(redis_host)
CELERY_RESULT_BACKEND = 'redis://{}/1'.format(redis_host)


17 changes: 15 additions & 2 deletions settings/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,13 @@
'rest_framework',
'rest_framework_filters',
'corsheaders',
'django_extensions'
'django_extensions',
'django_celery_beat',
]

LOCAL_APPS = [
'apps.account',
'apps.schedule',
'apps.demo'
]

Expand Down Expand Up @@ -294,7 +296,18 @@
STATICFILES_DIRS = (
# os.path.join(BASE_DIR, "apps/static"),
)

# ==================
# = celery
# ==================
CELERY_BROKER_URL = 'redis://127.0.0.1:6379/1'
CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/1'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_ENABLE_UTC = False
DJANGO_CELERY_BEAT_TZ_AWARE = True
CELERY_TIMEZONE = TIME_ZONE
CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler'

# ==================
# = Configurations from other file
Expand Down
12 changes: 10 additions & 2 deletions settings/staging.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,15 @@
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://{}:6379/1".format(redis_host),
"LOCATION": "redis://{}/1".format(redis_host),
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"PASSWORD": ""
}
},
"token": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/2",
"LOCATION": "redis://{}/2".format(redis_host),
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"PASSWORD": "",
Expand Down Expand Up @@ -60,3 +60,11 @@
# DEFAULT_FILE_STORAGE = 'aliyun_oss2_storage.backends.AliyunMediaStorage'
# staticfile将自动上传
# STATICFILES_STORAGE = 'aliyun_oss2_storage.backends.AliyunStaticStorage'

# ==================
# = celery
# ==================
CELERY_BROKER_URL = 'redis://{}/1'.format(redis_host)
CELERY_RESULT_BACKEND = 'redis://{}/1'.format(redis_host)


0 comments on commit 13ea24f

Please sign in to comment.