简体   繁体   English

如何在不使用睡眠 function 的情况下每 N 次执行一次 X?

[英]How to do X every N time without using the sleep function?

I want to make a simple python program to generate a captcha for a flask website.我想制作一个简单的 python 程序来为 flask 网站生成验证码。 I can generate the image, but if I save it in for eg in /images/captcha_{id}.png ,then I would have tons of old Captchas as the website gets used.我可以生成图像,但如果我将其保存在例如/images/captcha_{id}.png中,那么随着网站的使用,我将拥有大量的旧验证码。

I've tried to create a script that uses the sleep function to remove the old captchas every N time, but the problem is then, that I disable all the activity in the website for the N time.我尝试创建一个脚本,该脚本使用睡眠 function 每 N 次删除旧的验证码,但问题是,我禁用了网站中的所有活动 N 次。

The Captcha system is the following:验证码系统如下:

import secrets, string
from PIL import Image, ImageFont, ImageDraw

def gen_captcha(id):
    alpha = string.ascii_letters + string.digits
    captcha = "".join(secrets.choice(alpha) for i in range(8))

    img = Image.new("RGBA", (200,100), (3, 115, 252))
    font = ImageFont.truetype("arial.ttf",20)
    w,h = font.getsize(captcha)
    draw = ImageDraw.Draw(img)
    draw.text((50,50), captcha, font=font, fill=(255, 239, 0))

    img.save("captcha_{}.png".format(str(id))

    return captcha

The flask app basically requests an input and displays the captcha based on the given id, and then says if req_captcha == captcha: return "You solved the captcha" it also gives an error if you don't solve it. flask 应用程序基本上请求输入并根据给定的 id 显示验证码,然后说if req_captcha == captcha: return "You solved the captcha"如果你不解决它也会给出错误。

What I would like to know, is if I can make a little script that runs as a background process that deletes my old captchas.我想知道的是,我是否可以制作一个作为后台进程运行的小脚本,以删除我的旧验证码。

I think what you're looking for is a cron job .我认为您正在寻找的是cron 工作 Set one up to run a bash script that cleans up yesterdays captchas.设置一个运行 bash 脚本来清理昨天的验证码。

One of the possible approaches would be to use either the multiprocessing or threading modules available in Python.一种可能的方法是使用 Python 中可用的multiprocessingthreading模块。 They're both quite similar in terms of API.它们在 API 方面非常相似。 I will base my answer on the multiprocessing approach, but you can yourself evaluate if the threaded approach suits your needs more.我的答案将基于多处理方法,但您可以自己评估线程方法是否更适合您的需求。 You can refer to this question as an example.你可以参考这个问题作为例子。 Here's a sample implementation:这是一个示例实现:

import os
import time
from multiprocessing import Process

def remove_old_captchas():
    if os.fork() != 0:
        return
    print('Running process to remove captchas every 5 seconds ...')
    while True:
        time.sleep(5)
        print("... Captcha removed")

if __name__ == '__main__':
    p = Process(target=remove_old_captchas)
    p.daemon = True
    p.start()
    p.join()
    print('Main code running as well ...')
    while True:
        time.sleep(1)
        print("... Request served")

In the output of that you can see the captchas being removed in a regular time interval:在 output 中,您可以看到验证码以固定的时间间隔被删除:

Running process to remove captchas every 5 seconds ...
Main code running as well ...
... Request served
... Request served
... Request served
... Request served
... Captcha removed
... Request served
... Request served
... Request served
... Request served
... Request served
... Captcha removed
... Request served
... Request served
... Request served

In terms of design I would probably still go with a cron job like mentioned in another answer, but you asked about running a background task, so that would one possible answer.在设计方面,我可能仍然会使用 go 和另一个答案中提到的 cron 作业,但是您询问了运行后台任务,所以这是一个可能的答案。 You may also like the subprocess module.您可能还喜欢subprocess模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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