So I am making a flask app to build team configurations using a backtracker. Everything on the backend is fine but I am having trouble serving the content. This is not a production thing, just a script for me and my friends. I capture stdOut into a StringIO() object. I then write that to a file and serve the file to the browser. The issue is that somewhere, the buffer is not being cleared and I get repeat data on each request.
EDIT: I capture STDOUT so I can keep the original implementation of the backtracker. IE: Running the backtracker outputs to the terminal, running the app will run the behavior below. Is this good design principles?
@app.route('/<solutions>', methods=['GET'])
def getTeams(solutions=1):
f = open("tmp.txt", "w")
solutions = int(solutions)
old_stdout = sys.stdout
old_stdout.flush()
sys.stdout = mystdout = StringIO()
teams.main(solutions)
sys.stdout = old_stdout
f.write(mystdout.getvalue())
f.close()
mystdout.seek(0)
mystdout.truncate(0)
return send_file("tmp.txt")
It works fine, the file clears every run, but the outputs to the webpage are as follows: First Response
Starting backtracker...
Printing 1 solutions...
TEAM 1 TEAM 2
------- ---------------------- -------------------
TOP Name: BilyBobLongSlong Name: auzzi29
MID Name: balberry13 Name: ZeSwagerWagon
JUNLGE Name: Lemme Dunk First Name: MackAttack599
ADC Name: RINK Name: sptfire128
SUPPORT Name: JCKing Name: rohan72699
Second Response:
Starting backtracker...
Printing 1 solutions...
TEAM 1 TEAM 2
------- ---------------------- -------------------
TOP Name: BilyBobLongSlong Name: auzzi29
MID Name: balberry13 Name: ZeSwagerWagon
JUNLGE Name: Lemme Dunk First Name: MackAttack599
ADC Name: RINK Name: sptfire128
SUPPORT Name: JCKing Name: rohan72699
TEAM 1 TEAM 2
------- ---------------------- -------------------
TOP Name: BilyBobLongSlong Name: ZeSwagerWagon
MID Name: auzzi29 Name: MackAttack599
JUNLGE Name: balberry13 Name: JCKing
ADC Name: sptfire128 Name: RINK
SUPPORT Name: Lemme Dunk First Name: rohan72699
and every response it just stacks more on. I don't quite know why the StringIO() will not clear as I seek it to 0 and truncate it every run of the code... Am very confused. Thanks!
Update: I have checked the docs on StringIO and it is supposed to behave as a file. So I'm lost. I also print() what is in StringIO to the command line to outrule the possibility of some weird interaction with the temporary file and as suspected, printing out StringIO is the same un-truncated output.
Could this be some kind of bug? I don't understand where the output could be persisting.... hmmm....