I have a route in my Flask app that spawns a process (using multiprocessing.Process) to do some background work. That process needs to be able to write to the database.
__init__.py:
from flask_sqlalchemy import SQLAlchemy
from project.config import Config
db = SQLAlchemy()
# app factory
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)
return app
And this is the relevant code that illustrates that way i'm spawning the process and using the db connection:
def worker(row_id):
db_session = db.create_scoped_session()
# Do stuff with db_session here
db_session.close()
@app.route('/worker/<row_id>/start')
def start(row_id):
p = Process(target=worker, args=(row_id,))
p.start()
return redirect('/')
The problem is that sometimes (not always) i have errors like this one:
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) insufficient data in "D" message lost synchronization with server: got message type "a", length 1668573551
I assume that this is related to the fact that there is another process accessing the database (because if i don't use a separate process, everything works fine) but i honestly can't find a way of fixing it. As you can see on my code, i tried used create_scoped_session() method as an attempt to fix this but the problem is the same.
Any help?
start()you start running it, yes, but it doesn't block but goes to the background. Then your function proceeds to do the redirect, and thepobject goes out of scope and is deleted. Or does multiprocessing keep it alive, does the db ob succeed? In the doc they use join() to wait for the process to stop, ofc you can return from the api though and keep it running on the back by holding a reference to it if that's it. docs.python.org/3/library/…db_session = db.init_app(app)just like i do on __init__.py?appthere. The Flask app is for the http and url routing, not needed for running a db op. I think a new process needs a new db connection anyway, but you can connect with sqlalchemy and don't need flask for it. What you use fromflask_sqlalchemyis I guess some helper, I don't know it, but I think you can connect just with SQLAlchemy to do any normal db op.