Flask, by default, uses multiple threads to handle incoming requests. So the bpy.ops.wm.open_mainfile()
call is made from a different thread than the main thread. This is not supported in the bpy
module (nor when running Python scripts under regular Blender). All BPy calls need to be made from the same main thread.
Try running Flask in single-threaded mode, e.g.
#!/usr/bin/env python
from flask import Flask
import bpy
import threading
app = Flask(__name__)
print('main thread', threading.get_ident())
@app.route('/')
def hello():
print('handler thread', threading.get_ident())
bpy.context.scene.render.engine = 'CYCLES'
bpy.ops.wm.open_mainfile(filepath='test.blend')
return "Hello World!"
if __name__ == '__main__':
app.run(threaded=False)