0

I'm using flask for a web application, it was all going well till I had to deal with multiple requests( I am using threaded=true)

My problem is if I get two parallel requests then flask will create two threads and they will try to create a file with the same name (I have to use epoch time for file name)

Even if i put lock on the file as soon as the the lock is released the other thread will try to create a file with the same name (as both the threads will have the same name value

from flask import Flask
import time

app = Flask(__name__)

@app.route('/start', methods=['GET'])
    try:
        # how can i lock a flask's thread from accessing this part so that two threads can't have files with the same name
        name = str(int(time.time()))
        with open(name,'w') as FileObj:
            FileObj.write('Hey')
    except:
        abort(500)

    return "created a file"

def main():
    """
    Main entry point into program execution

    PARAMETERS: none
    """
    app.run(host='0.0.0.0',threaded=True)

main()

does the flask thread work with threading.Lock(), if i put a lock around the name will the both parallel threads have different values?

PS: i know i could use random name for the files and avoid this problem, but i kind of have to use epoch time that's a pain

Bad_Coder
  • 1,019
  • 1
  • 20
  • 38
  • 1
    Is there a reason you aren't using `tempfile.TemporaryFile`? Using epoch-time for filenames is racey -- if the destination location is `/tmp`, for instance, someone else with write access to the directory can predict your name and create a symlink in the destination location pointing to a file they'd like to have overwritten for which you have write access but they don't. Proper tempfile-creation mechanisms use `O_CREAT|O_EXCL` (so not just a random name, but also telling the OS not to let collisions happen if an attacker flooded the namespace, predicted the RNG, &c), and thereby avoid this. – Charles Duffy Dec 08 '16 at 18:32
  • 2
    ...and yes, `threading.Lock()` absolutely will work. Is there a reason you didn't try it before asking here? – Charles Duffy Dec 08 '16 at 18:35
  • Yeah i have to use epoch time as per the requirement. I'm new to flask, so i was not sure if it supports thread locking as it is unstable with multiple threads, will try that out...thanks :) – Bad_Coder Dec 08 '16 at 18:40
  • Frankly, I'd be chasing down who wrote that requirement and why. Having epoch time as part of your filename is saner than having it be the whole of the name. – Charles Duffy Dec 08 '16 at 19:00

0 Answers0