Remove old temporary files when user is logged out

我是研究僧i 提交于 2021-02-08 02:59:24

问题


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.

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?


回答1:


Clicking the log out button does the same thing as expiring the session, right?

There are two ways you can do this: 1) add code to the session expiration routine that cleans up the temporary files, and/or 2) write a cron script that checks for active sessions and cleans up the temporary files for inactive sessions.




回答2:


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.

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

Code looks like this:

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'])

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.



来源:https://stackoverflow.com/questions/30640968/remove-old-temporary-files-when-user-is-logged-out

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!