用户注销后删除旧的临时文件 [英] Remove old temporary files when user is logged out

查看:54
本文介绍了用户注销后删除旧的临时文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个视图,该视图接受登录的用户输入,然后运行一个函数来生成报告.结果在HTML页面中返回.我也将报告呈现为PDF.

I have a view that takes logged in user input then runs a function to produce a report. The result is returned in an HTML page. I render the report to PDF as well.

我使用函数中的内容创建PDF,并将其保存在服务器上的某个文件夹中.我不想让服务器每次运行都充满文件,所以我为每个用户登录时创建一个临时文件夹(在tmpfs中),并在会话中保存路径,这不是永久的.

I create a PDF with the content from my function and save it in some folder on the server. I don't want to have my server filled with files from every run, so I create a temporary folder (in tmpfs) for each user when they log in and save the path in their session, which is not permanent.

session['temp_path'] = '/dev/shm/<random_uuid>/'

用户可以通过单击注销按钮注销,否则他们的会话可能会过期.注销用户的临时文件夹后如何删除?

The user may log out by clicking a log out button, or their session might expire. How can I remove the user's temporary folder after they are logged out?

推荐答案

如果有人对此问题感兴趣,我可以用另一种方法解决.我不检查用户是否注销或分别创建任何cron脚本.

If someone is interested in this question I solved it another way. I do not check if the user logs out or create any cron script respectively.

我创建了一个对象,该对象为每个创建的pdf运行计数线程.经过一段时间后,将删除pdf.

I created an Object that runs a counting thread for every pdf created. After elapsed time, pdf is deleted.

代码如下:

class TimeSet(set):
    def add(self, item, timeout):
        set.add(self, item)
        t = threading.Thread(target=timeout_set_remove, args=(self, item, timeout))
        t.start()

def timeout_set_remove(my_set, item, timeout):
    time.sleep(timeout)
    os.remove(str(item))
    my_set.remove(item)

在我的烧瓶应用程序中,我像这样使用它:

In my flask app I use it like this:

set = TimeSet()
set.add(os.path.abspath(os.path.join(src_path, pdf_name)), app.config['PDF_PERSISTENCE'])

其中 pdf_name 是创建的pdf的名称, src_path 是文件的路径.持续时间在我的配置文件中定义.

where pdf_name is the name of created pdf, src_path is the path to the file. The persistence time is defined in my config file.

这篇关于用户注销后删除旧的临时文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆