python - django-建议不要运行 crontab

标签 python django

我在设置中设置了 RECOMMENDS_TASK_CRONTAB = {'minute': '*/1'} ,所以这应该每 1 分钟重复一次。 它不起作用, 谁用过这个包https://djangopackages.org/packages/p/django-recommends/ 可以告诉我我做错了什么

这是我的模型

# models.py
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.utils.encoding import python_2_unicode_compatible


@python_2_unicode_compatible
class Product(models.Model):
    """A generic Product"""
    name = models.CharField(blank=True, max_length=100)
    sites = models.ManyToManyField(Site)

    def __str__(self):
        return self.name

    @models.permalink
    def get_absolute_url(self):
        return ('product_detail', [self.id])

    def sites_str(self):
        return ', '.join([s.name for s in self.sites.all()])
    sites_str.short_description = 'sites'


@python_2_unicode_compatible
class Vote(models.Model):
    """A Vote on a Product"""
    user = models.ForeignKey(User, related_name='votes')
    product = models.ForeignKey(Product)
    site = models.ForeignKey(Site)
    score = models.FloatField()

    def __str__(self):
        return "Vote"

这是我的推荐.py

# recommendations.py

from django.contrib.auth.models import User
from recommends.providers import RecommendationProvider
from recommends.providers import recommendation_registry

from .models import Product, Vote

class ProductRecommendationProvider(RecommendationProvider):
    def get_users(self):
        return User.objects.filter(is_active=True, votes__isnull=False).distinct()

    def get_items(self):
        return Product.objects.all()

    def get_ratings(self, obj):
        return Vote.objects.filter(product=obj)

    def get_rating_score(self, rating):
        return rating.score

    def get_rating_site(self, rating):
        return rating.site

    def get_rating_user(self, rating):
        return rating.user

    def get_rating_item(self, rating):
        return rating.product

recommendation_registry.register(Vote, [Product], ProductRecommendationProvider)

这是settings.py

    """
Django settings for smartTutor project.

Generated by 'django-admin startproject' using Django 1.10.5.

For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'qe+s3uemj302lc3ea-=54(6c9qxj2%ws2jq)(48=a__*bg+um_'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google',
    'bootstrapform',
    'el_pagination',
    'markdown_deux',
    'pagedown',
    'simpleblog',
    'myProfile',
    'chartkick',
    'quiz',
    'recommends',
    'recommends.storages.djangoorm',
    'myrec'

]
import chartkick
STATICFILES_DIRS = (
    chartkick.js(),
)


MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'smartTutor.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'template')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.request',

            ],
        },
    },
]

AUTHENTICATION_BACKENDS = (
    # Needed to login by username in Django admin, regardless of `allauth`
    'django.contrib.auth.backends.ModelBackend',
    # `allauth` specific authentication methods, such as login by e-mail
    'allauth.account.auth_backends.AuthenticationBackend',
)

WSGI_APPLICATION = 'smartTutor.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True




# Static files (CSS, JavaScript, Images)

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static_env' , 'static_root')
STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static_files') ]

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static_env' , 'media_root')
# https://docs.djangoproject.com/en/1.10/howto/static-files/

STATIC_URL = '/static/'
SITE_ID = 1

RECOMMENDS_TASK_CRONTAB = {'minute': '*/1'}

最佳答案

刚刚通过文档检查,我认为缺少某种类型的触发器(实际上,它应该由 Django Celery 配置,而不是由 Django Recommends 配置)。

简单的解决方案

使用 crontab,而不是 Django Celery。您的 crontab 应该调用命令 python manage.py recommends_precompute

如果您不知道如何创建 crontab,请查看 here .

然后,添加以下内容:* * * * * python/path/to/smartTutor/manage.py recommends_precompute(Django 的 crontab 示例 here)。

celery 溶液

如果你需要让它与 Celery 一起工作,我建议你查看 Celery TutorialCelery with Django .

警告(已解决)

您使用的是 Django 1.10,但它对我不起作用。我降级到 Django 1.9 进行测试(有关更多信息,我刚刚添加了一个 issue )。

已编辑

Django 1.10 的问题已解决。

关于python - django-建议不要运行 crontab,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43016787/

相关文章:

django - 使用 Django ModelForm 上传个人资料图片

python - 使用 Clang 绑定(bind)提取类型字符串

java - 远程系统事件通知库

python - 将 python 长整数放入内存,它们之间没有任何空格

Python:显示和计算两个整数的除数

python - 同一站点下的多个 Django 应用程序

django - 否定 Django 模板中的 bool 值

python - Django CSV 导入数据

python - 如何将 Dialogflow 与 Django (Python) 集成?

python - 错误 : Cursor' object has no attribute '_last_executed