Python 烧瓶 sqlalchemy 或 sqlalchemy

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14343740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:08:05  来源:igfitidea点击:

flask-sqlalchemy or sqlalchemy

pythonflasksqlalchemyflask-sqlalchemy

提问by Amin

I am new in both flask and sqlalchemy, I just start working on a flask app, and I am using sqlalchemy for now. I was wondering if there is any significant benefit I can get from using flask-sqlalchemy vs sqlalchemy. I could not find enough motivations in http://packages.python.org/Flask-SQLAlchemy/index.htmlor maybe I did not understand the value!! I would appreciate your clarifications.

我是flask和sqlalchemy的新手,我刚刚开始开发flask应用程序,现在我正在使用sqlalchemy。我想知道使用 Flask-sqlalchemy 与 sqlalchemy 是否有任何显着的好处。我在http://packages.python.org/Flask-SQLAlchemy/index.html 中找不到足够的动机,或者我不明白它的价值!!我将不胜感激您的澄清。

回答by schlamar

The SQLAlchemy documentation clearly states that you should use Flask-SQLAlchemy (especially if you don't understand its benefits!):

SQLAlchemy 文档明确指出您应该使用 Flask-SQLAlchemy(尤其是当您不了解它的好处时!):

[...] products such as Flask-SQLAlchemy [...] SQLAlchemy strongly recommends that these products be used as available.

[...] Flask-SQLAlchemy 等产品 [...] SQLAlchemy 强烈建议使用这些产品。

This quote and a detailed motivation you can find in the second question of the Session FAQ.

您可以在会话常见问题解答的第二个问题中找到此引用和详细动机。

回答by MOCKBA

To be honest, I don't see any benefits. IMHO, Flask-SQLAlchemy creates an additional layer you don't really need. In our case we have a fairly complex Flask application with multiple databases/connections (master-slave) using both ORM and Core where, among other things, we need to control our sessions / DB transactions (e.g. dryrun vs commit modes). Flask-SQLAlchemy adds some additional functionality such as automatic destruction of the session assuming some things for you which is very often not what you need.

老实说,我看不出有什么好处。恕我直言,Flask-SQLAlchemy 创建了一个您并不真正需要的附加层。在我们的例子中,我们有一个相当复杂的 Flask 应用程序,其中包含多个数据库/连接(主从),使用 ORM 和 Core,其中,我们需要控制我们的会话/数据库事务(例如,dryrun 与提交模式)。Flask-SQLAlchemy 添加了一些额外的功能,例如自动销毁会话,为您假设一些通常不是您需要的东西。

回答by Mike Waites

as @schlamar suggests Flask-SqlAlchemy is defo a good thing. Id just like to add some extra context to the point made there.

正如@schlamar 所暗示的,Flask-SqlAlchemy 是一件好事。我只是想为那里提出的观点添加一些额外的上下文。

Dont feel like your are choosing one over the other. For example lets say we want to grab all records from a table using a model using Flask-Sqlalchemy. It as simple as

不要觉得你在选择一个而不是另一个。例如,假设我们想使用 Flask-Sqlalchemy 的模型从表中获取所有记录。就这么简单

Model.query.all()

For a lot of the simple cases Flask-Sqlalchemy is gonna be totally fine. The extra point that i would like to make is, if Flask-Sqlalchemy is not gonna do what you want then theres no reason you can't use SqlAlchemy directly.

对于很多简单的情况,Flask-Sqlalchemy 完全没问题。我想补充的一点是,如果 Flask-Sqlalchemy 不会做你想做的事,那么你没有理由不能直接使用 SqlAlchemy。

from myapp.database import db

num_foo = db.session.query(func.count(OtherModel.id)).filter(is_deleted=False).as_scalar()

db.session.query(Model.id, num_foo.label('num_foo')).order_by('num_foo').all()

As you can see we can easily jump from one to the other with no trouble and in the second example we are in fact using the Flask-Sqlalchemy defined models.

如您所见,我们可以轻松地从一个跳转到另一个,并且在第二个示例中我们实际上使用的是 Flask-Sqlalchemy 定义的模型。

回答by 2-complex

Here is an example of a benefit flask-sqlalchemy gives you over plain sqlalchemy.

这是flask-sqlalchemy 为您提供优于普通sqlalchemy 的一个示例。

Suppose you're using flask_user.

假设您正在使用flask_user。

flask_user automates creation and authentication of user objects, so it needs to access your database. The class UserManager does this by calling through to something called an "adapter" which abstracts the database calls. You provide an adapter in the UserManager constructor, and the adapter must implement these functions:

flask_user 自动创建和验证用户对象,因此它需要访问您的数据库。UserManager 类通过调用抽象数据库调用的称为“适配器”的东西来完成此操作。您在 UserManager 构造函数中提供了一个适配器,该适配器必须实现以下功能:

class MyAdapter(DBAdapter):
    def get_object(self, ObjectClass, id):
        """ Retrieve one object specified by the primary key 'pk' """
        pass

    def find_all_objects(self, ObjectClass, **kwargs):
         """ Retrieve all objects matching the case sensitive filters in 'kwargs'. """
        pass


    def find_first_object(self, ObjectClass, **kwargs):
        """ Retrieve the first object matching the case sensitive filters in 'kwargs'. """
        pass

    def ifind_first_object(self, ObjectClass, **kwargs):
        """ Retrieve the first object matching the case insensitive filters in 'kwargs'. """
        pass

    def add_object(self, ObjectClass, **kwargs):
        """ Add an object of class 'ObjectClass' with fields and values specified in '**kwargs'. """
        pass

    def update_object(self, object, **kwargs):
        """ Update object 'object' with the fields and values specified in '**kwargs'. """
        pass

    def delete_object(self, object):
        """ Delete object 'object'. """
        pass

    def commit(self):
        pass

If you're using flask-sqlalchemy, you can use the built-in SQLAlchemyAdapter. If you're using sqlalchemy (not-flask-sqlalchemy) you might make different assumptions about the way in which objects are saved to the database (like the names of the tables) so you'll have to write your own adapter class.

如果您使用的是flask-sqlalchemy,则可以使用内置的SQLAlchemyAdapter。如果您使用 sqlalchemy (not-flask-sqlalchemy),您可能会对将对象保存到数据库的方式(例如表的名称)做出不同的假设,因此您必须编写自己的适配器类。

回答by Boris Serebrov

The main feature of the Flask-SQLAlchemyis proper integration with Flask application - it creates and configures engine, connection and session and configures it to work with the Flask app.

的主要功能Flask-SQLAlchemy是与 Flask 应用程序的正确集成 - 它创建和配置引擎、连接和会话,并将其配置为与 Flask 应用程序一起使用。

This setup is quite complex as we need to create the scoped sessionand properly handle it according to the Flask application request/response life-cycle.

这个设置非常复杂,因为我们需要创建作用域会话并根据 Flask 应用程序请求/响应生命周期正确处理它。

In the ideal world that would be the only feature of Flask-SQLAlchemy, but actually it adds few more things. Here is a good blog post with the overview of them: Demystifying Flask-SQLAlchemy.

在理想的世界中,这将是 的唯一特征Flask-SQLAlchemy,但实际上它增加了更多的东西。这是一篇很好的博客文章,概述了它们:Demystifying Flask-SQLAlchemy

When I first worked with Flask and SQLAlchemy, I didn't like this overhead . I went over and extracted the session management code from the extension. This approach works, although I discovered that it is quite difficult to do this integration properly.

当我第一次使用 Flask 和 SQLAlchemy 时,我不喜欢这种开销。我过去从扩展中提取会话管理代码。这种方法有效,尽管我发现正确地进行这种集成非常困难。

So the easier approach (which is used in another project I am working on) is to just drop the Flask-SQLAlchemyin and don't use any of additional features it provides. You will have the db.sessionand you can use it as if it was pure SQLAlchemysetup.

因此,更简单的方法(在我正在从事的另一个项目中使用)是直接Flask-SQLAlchemy加入并且不使用它提供的任何附加功能。您将拥有db.session并且可以像使用纯SQLAlchemy设置一样使用它。

回答by Kimmo Hintikka

Flask-SQLAlchemy gives you a number of nice extra's you would else end up implementing yourself using SQLAlchemy.

Flask-SQLAlchemy 为您提供了许多不错的额外功能,否则您最终会使用 SQLAlchemy 实现自己。

Positive sides on using Flask-SQLAlchemy

使用 Flask-SQLAlchemy 的积极方面



  1. Flask_SQLAlchemy handles session configuration, setup and teardown for you.
  2. Gives you declarative base model that makes querying and pagination easier
  3. Backend specific settings.Flask-SQLAlchemy scans installed libs for Unicode support and if fails automatically uses SQLAlchemy Unicode.
  4. Has a method called apply_driver_hacksthat automatically sets sane defaults to thigs like MySQL pool-size
  5. Has nice build in methods create_all() and drop_all() for creating and dropping all tables. Useful for testing and in python command line if you did something stupid
  6. It gives you get_or_404()instead of get() and find_or_404() instead of find() Code example at > http://flask-sqlalchemy.pocoo.org/2.1/queries/
  1. Flask_SQLAlchemy 为您处理会话配置、设置和拆卸。
  2. 为您提供声明式基本模型,使查询和分页更容易
  3. 后端特定设置。Flask-SQLAlchemy 扫描已安装的库以获取 Unicode 支持,如果失败会自动使用 SQLAlchemy Unicode。
  4. 有一个方法apply_driver_hacks可以自动将合理的默认值设置为像 MySQL pool-size 这样的 thigs
  5. 有很好的内置方法 create_all() 和 drop_all() 用于创建和删除所有表。如果您做了一些愚蠢的事情,则对于测试和在 python 命令行中很有用
  6. 它为您提供 get_or_404() 而不是 get() 和 find_or_404() 而不是 find() > http://flask-sqlalchemy.pocoo.org/2.1/queries/的代码示例

Automatically set table names. Flask-SQLAlchemy automatically sets your table names converting your ClassName> class_namethis can be overridden by setting __tablename__class List item

自动设置表名。Flask-SQLAlchemy 自动设置你的表名转换你的ClassName>class_name这可以通过设置__tablename__类列表项来覆盖

Negative sides on using Flask-SQLAlchemy

使用 Flask-SQLAlchemy 的负面影响



  1. Using Flask-SQLAlchemy will make add additional difficulties to for migrating from Flask to let's say Pyramid if you ever need to. This is mainly due to the custom declarative base model on Flask_SQLAchemy.
  2. Using Flask-SQLAlchemy you risk using a package with a much smaller community than SQLAlchemy itself, which I cannot easily drop from active development any time soon.
  3. Some nice extras Flask-SQLAlchemy has can make you confused if you do not know they are there.
  1. 如果您需要,使用 Flask-SQLAlchemy 会给从 Flask 迁移到 Pyramid 增加额外的困难。这主要是由于 Flask_SQLAchemy 上的自定义声明性基础模型。
  2. 使用 Flask-SQLAlchemy,你可能会冒险使用社区比 SQLAlchemy 本身小得多的包,我不能轻易地在短期内放弃积极的开发。
  3. 如果您不知道 Flask-SQLAlchemy 的一些不错的附加功能,它们可能会让您感到困惑。