简体   繁体   中英

How to run Django background task only once

I am trying to crop images (thousands of images) on button click bellow is my code!

@background(schedule=5)
def initialize():

    allimages = []
    number = 0

    if not os.path.exists('thumbnails'):
        os.makedirs('thumbnails')

    path = '/Users/shoaibrafa/Data/*.jpg'

    for image in glob.glob(path):
        print(image,"=====",number)
        im = Image.open(image)
        im.thumbnail((512, 512), Image.ANTIALIAS)
        im.save("thumbnails/" + os.path.basename(image), "JPEG")
        number = number + 1

but I face two problems:

  1. when clicking the button from the template gives Object of type 'WSGIRequest' is not JSON serializable error!

  2. if I call the method initialize() directly when the page loads the background task starts cropping the images, but when the all images are cropped it starts again from beginning cropping the images and continues for ever. What I need is to crop the images and end the background task.

bellow is my template:

{% extends 'layout.html' %}
{% block title %} Login {% endblock %}

{% block content %}
    <a class="btn btn-primary" href="{% url 'home:init'%}">Initialize...</a>
{% endblock %}

thanks in advance

Why not write a command line script/tool - which you can run using cron job?

The script should have logic which images are done, which are pending or which are in crop-in-progress.

May - let Django display the status of this script: Running, Sleeping, Has done the job etc.

With Django background tasks, you can check if a task already exists before creating it so you don't create duplicates

from background_task.models import Task
if not Task.objects.filter(verbose_name="my_task_name").exists():
   tasks.my_task(verbose_name="my_task_name")

I explained here how to run tasks only once by checking if the task is already created: Django + background-tasks how to initialize

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM