3

I saw a few other posts about this and understand what the problem is. However I'm struggling to write the code so it avoids the error:

from database import db_session
from database import init_db

database.py

engine = create_engine('sqlite:///'+full_path, convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()

def init_db():
    # import all modules here that might define models so that
    # they will be registered properly on the metadata.  Otherwise
    # you will have to import them first before calling init_db()
    import models
    Base.metadata.create_all(bind=engine)

flaskserver.py

@app.route('/process_email')
def process_email():
    init_db()
    email_address = request.args.get('email_address')
    print(email_address)
    email_date =  datetime.now().strftime('%Y-%m-%d')
    rec = db_session.query(EmailCampaign).filter(EmailCampaign.email == email_address).first()
    if rec.email_4 is not None:
        rec.email_4_respond = email_date
    elif rec.email_3 is not None:
        rec.email_3_respond = email_date
    elif rec.email_2 is not None:
        rec.email_2_respond = email_date
    elif rec.email_1 is not None:
        rec.email_1_resonded = email_date

    db_session.commit()
    return('done')

I randomly get

sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 9396 and this is thread id 13360.

as an erorr. I think I have to initialize the connection inside the process_email() function right? I've tried it outside the function but also get the same error.

Thanks.

11

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.