0

When data is written to a file in FastAPI like below, is this thread safe? Assuming that several requests are sent to the endpoint at the same time.

@app.post("/items/")
def add_item(item: str)
    with open('output.txt', 'w') as f:
            f.write(item + '\n')
    return item

And if not, what would be a good way to ensure that each item is written to the file.

Anne Maier
  • 299
  • 1
  • 8
  • https://github.com/tiangolo/fastapi/issues/876 – casper Feb 22 '22 at 09:44
  • 1
    Use locking if you want to avoid two processes recreating a file at the same time - or you can use the `append` mode instead of `write` (which truncates the file). Creating files by itself isn't thread safe, unless you implementing locking around the operations you want to perform. – MatsLindh Feb 22 '22 at 12:40
  • 1
    Best practices from Alex Martelli https://stackoverflow.com/a/2302427/13782669 – alex_noname Feb 22 '22 at 16:05

0 Answers0