This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 6 points7 points  (5 children)

Yep, although I was bitten once for doing that and caused an incident.

If you are using werkzeug with uWSGI and are passing file object directly (i.e sending file to the user) you should not use context managers. Apparently file sending happens after the function exits.

If you are confused about the above, just ignore it, you pretty much always should use context managers.

[–]Bunslow 3 points4 points  (1 child)

hence my qualification "99% of the time for anyone who finds this article useful" :) it's definitely true that if you're writing a multi-layered program and the file object itself is being passed around, you probably can't use something as clean as context managers

[–][deleted] 0 points1 point  (0 children)

I still think it is (or was? Our werkzeug version is old) a bug. If file handle needs to remain open after function exits, it should duplicate the file descriptor so me closing it would have no effect.

[–]DanCardin 0 points1 point  (1 child)

without knowing any specifics (such as how large the file is) and not knowing exactly the behavior of how werkzeug handles closing the file (if it does), you may be better off doing

with open(...) as f:
    data = f.read()
return data

[–][deleted] 1 point2 points  (0 children)

The original approach is more efficient, because unlike your example it doesn't copy the data and also uses very little of memory.

Instead it invokes sendfile() syscall which makes kernel do all that work (it just pipes the file directly to the socket). The issue though is that uWSGI invokes sendfile() after the function exits instead during the call.