SQLAlchemy sessions error

前端 未结 3 931
无人共我
无人共我 2020-12-19 07:47

Background: Flask / Flask-SQLAlchemy / Flask-WTF, using declarative and scoped session

Simple POST operation:

@tas.route(\'/order_add\         


        
3条回答
  •  清酒与你
    2020-12-19 08:48

    That's weird. Why are you creating the engine and declarative base explicitly if you're using flask-sqlalchemy? That's likely where your problem is. It looks like you have two engines and sessions running concurrently, that's why you got the error.

    Instead of creating the engine explicitly, you should use just:

    from flask.ext.sqlalchemy import SQLAlchemy
    
    db = SQLAlchemy()
    

    And inside your app factory:

    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///fundmanager_devel.db'
    db.init_app(app) 
    

    Then your base declarative model is db.Model, your session is in db.session, and you should let flask request context manage session creation.

    Check the minimal application example in Flask-SQLAlchemy docs:

    http://pythonhosted.org/Flask-SQLAlchemy/quickstart.html#a-minimal-application

    This is how it's recommended by SQLAlchemy:

    Most web frameworks include infrastructure to establish a single Session, associated with the request, which is correctly constructed and torn down corresponding torn down at the end of a request. Such infrastructure pieces include products such as Flask-SQLAlchemy, for usage in conjunction with the Flask web framework, and Zope-SQLAlchemy, for usage in conjunction with the Pyramid and Zope frameworks. SQLAlchemy strongly recommends that these products be used as available.

    http://docs.sqlalchemy.org/en/rel_0_9/orm/session.html

提交回复
热议问题