如何在现有的sqlalchemy模型中使用flask-sqlalchemy? [英] How to use flask-sqlalchemy with existing sqlalchemy model?

查看:110
本文介绍了如何在现有的sqlalchemy模型中使用flask-sqlalchemy?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过 flask-sqlalchemy或sqlalchemy ,它建议使用flask-sqlalchemy烧瓶。然而,我有一个基于sqlalchemy的declarative_base命令行脚本编写的现有模型,例如,

$ b $

来自sqlalchemy.ext.declarative的b

  import declarative_base 
Base = declarative_base()#create sqlalchemy基类

类Runner (Base):

我想仍然可以使用命令行有了这个模型的脚本,还想在模型周围构建一个web应用程序。

有没有一种方法来扩展现有的模型,以获得使用烧瓶的好处-sqlalchemy扩展?或者我应该自己推出自己的,并使用sqlalchemy的ScopedSession?

解决方案

目前,这是不是很好的支持,但不是不可能做的。请参阅Flask-SQLAlchemy问题清单上的这个问题,它承认当前的实现的延伸使得这种情况比他们认为的更令人头疼。希望这将在未来得到更好的支持(一旦确定了一个稳定的迁移路径和新的API)。

这个问题给出了下面的代码示例:

 从瓶子导入Flask 
从模型导入Base,User#您的非Flask-SQLAlchemy模型...
from flask_sqlalchemy import SQLAlchemy
$ b $ app = Flask(__ name__)
app.config ['SQLALCHEMY_DATABASE_URI'] ='sqlite:////tmp/test.db'
db = SQLAlchemy(

@ app.before_first_request
def setup():
#每次为demo创建数据库
Base.metadata.drop_all(bind = db.engine)
Base.metadata.create_all(bind = db.engine)
db.session.add(User('Bob Jones','bob@gmail.com'))
db.session。添加用户('Joe Quimby','eat@joes.com'))
db.session.commit()

@ app.route('/')
def root():
users = db.session.query(User).all()
return u< br>join([u{0}:{1})格式(用户。名字,user.email)用户在用户])

如果__name__ =='__main__':
app.run('127.0.0.1',5000)

这里有几点需要注意:

首先,失去了执行 User.query 的能力(因为用户是使用自己的声明性基础创建的),以及所有其他的东西,Flask-SQLAlchemy的 db.Model 给你(例如自动生成表名和方法的能力,如 first_or_404()第二,任何时候你需要做的事情都涉及到元数据(比如 Flask-SQLAlchemy / api.html#flask.ext.sqlalchemy.SQLAlchemy.drop_allrel =noreferrer> drop_all create_all ),你不能使用Flask-SQLAlchemy方法。您必须使用绑定到Flask-SQLAlchemy引擎的原始元数据。



我自己没有尝试过,所以我不确定是否还有其他的陷阱到这个方法。如果您发现任何情况,您可能需要参与该票。


I've read flask-sqlalchemy or sqlalchemy which recommends use of flask-sqlalchemy with flask. I want to follow this approach.

However, I have an existing model written for command line scripts which is based on sqlalchemy's declarative_base, e.g.,

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()   # create sqlalchemy Base class
              :
class Runner(Base):
    etc.

I want to still be able to use the command line scripts with this model, but also want to build a web application around the model.

Is there a way to extend the existing model, to gain the benefit of using the flask-sqlalchemy extension? Or should I just roll my own, and use sqlalchemy's ScopedSession?

解决方案

Currently, this is something that is not well supported, but not impossible to do. See this issue on the Flask-SQLAlchemy issue list, which admits that the current implementation of the extension makes this situation more of a headache than they think it should. Hopefully this will be better supported in the future (once a solid migration path and new API is determined).

That issue gives the following code sample:

from flask import Flask
from models import Base, User # Your non-Flask-SQLAlchemy models...
from flask_sqlalchemy import SQLAlchemy

app =  Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)

@app.before_first_request
def setup():
    # Recreate database each time for demo
    Base.metadata.drop_all(bind=db.engine)
    Base.metadata.create_all(bind=db.engine)
    db.session.add(User('Bob Jones', 'bob@gmail.com'))
    db.session.add(User('Joe Quimby', 'eat@joes.com'))
    db.session.commit()

@app.route('/')
def root():
    users = db.session.query(User).all()
    return u"<br>".join([u"{0}: {1}".format(user.name, user.email) for user in users])

if __name__ == '__main__':
    app.run('127.0.0.1', 5000) 

There are a few things to note here:

First, you lose the ability to do User.query (because User was created using its own declarative base), along with all of the other stuff that Flask-SQLAlchemy's db.Model gives you (such as the ability to auto-generate the table names and methods like first_or_404()).

Second, any time you need to do things that involve the metadata (such as drop_all or create_all), you cannot use the Flask-SQLAlchemy methods. You must use the original metadata, bound to the Flask-SQLAlchemy engine.

I haven't tried this myself, so I'm not sure if there are any other gotchas to this approach. You might want to participate in that ticket if you find any.

这篇关于如何在现有的sqlalchemy模型中使用flask-sqlalchemy?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆