将Flask和SQLAlchemy用于Python webapp,我的目标是创建一个系统,我可以在其中:
所有这些都将打包在一个单独的层中,在编写API时应允许简单的数据访问,验证和响应格式化,希望无需手动定义数据模型或模式,而不是已经存在的定义DB。这引出了我的问题:
我可以利用现有的框架来完成我想要完成的所有工作吗?我不希望有一个单独的库可以做任何事情,但我希望能够利用几个现有的框架。但是,我遇到了直接的冲突,特别是在第2步和第3步。我到目前为止尝试使用的堆栈如下:
我有第1步的解决方案:SQLAlchemy的反思。这允许我读取现有数据库中的表并将它们映射到SQLAlchemy模型。这很好用。
步骤2和3的组合是它变得模糊的地方 - 我正在尝试使用Flask-Marshmallow和Marshmallow-JsonAPI。 Flask-Marshmallow具有ModelSchema class,它允许您通过传递现有的SQLAlchemy模型来生成模式。我可以将它传递给我在步骤1中生成的SQLAlchemy模型,满足我对第2步的标准。至于Marshmallow-JsonAPI,它具有为您的模型定义模式的功能,它将自动创建符合JSONAPI的响应,满足我对第3步的标准。我可以单独地让每个框架都做我需要的。
不幸的是,由于我的模式必须继承Flask-Marshmallow和Marshmallow-JSONAPI中的Schema类,因此我遇到了问题。我的“虚拟”课程模型如下所示:
import flask
from marshmallow_jsonapi import Schema, fields
from sqlalchemy.ext.declarative import DeferredReflection
from flask_marshmallow import Marshmallow
from flask_sqlalchemy import SQLAlchemy
app = flask.Flask(__name__)
DB = SQLAlchemy()
DB.init_app(app)
MA = Marshmallow(app)
DeferredReflection.prepare(DB.get_engine(app))
class Dummy(DeferredReflection, DB.Model):
__tablename__ = "dummy" # This model will be reflected from the Dummy table
class DummySchema(MA.ModelSchema, Schema): # The problem line
class Meta:
model = Dummy # Create schema for the Dummy model
在尝试启动我的API时,我遇到了类似的奇怪错误:
api_1 | [2017-01-05 23:16:13,379] ERROR in app: Exception on /api/dummy [POST]
api_1 | Traceback (most recent call last):
api_1 | File "/usr/local/lib/python3.5/site-packages/flask/app.py", line 1612, in full_dispatch_request
api_1 | rv = self.dispatch_request()
api_1 | File "/usr/local/lib/python3.5/site-packages/flask/app.py", line 1598, in dispatch_request
api_1 | return self.view_functions[rule.endpoint](**req.view_args)
api_1 | File "/usr/local/lib/python3.5/site-packages/flask_restful/__init__.py", line 477, in wrapper
api_1 | resp = resource(*args, **kwargs)
api_1 | File "/usr/local/lib/python3.5/site-packages/flask/views.py", line 84, in view
api_1 | return self.dispatch_request(*args, **kwargs)
api_1 | File "/usr/local/lib/python3.5/site-packages/flask_restful/__init__.py", line 587, in dispatch_request
api_1 | resp = meth(*args, **kwargs)
api_1 | File "/dummyproj/api/src/dummyproj/api/v1/dummy_resource.py", line 34, in post
api_1 | dummy_schema = dummy.DummySchema()
api_1 | File "/usr/local/lib/python3.5/site-packages/marshmallow_sqlalchemy/schema.py", line 143, in __init__
api_1 | super(ModelSchema, self).__init__(*args, **kwargs)
api_1 | File "/usr/local/lib/python3.5/site-packages/marshmallow_jsonapi/schema.py", line 81, in __init__
api_1 | super(Schema, self).__init__(*args, **kwargs)
api_1 | File "/usr/local/lib/python3.5/site-packages/marshmallow/schema.py", line 358, in __init__
api_1 | self._update_fields(many=many)
api_1 | File "/usr/local/lib/python3.5/site-packages/marshmallow/schema.py", line 750, in _update_fields
api_1 | self.__set_field_attrs(ret)
api_1 | File "/usr/local/lib/python3.5/site-packages/marshmallow/schema.py", line 772, in __set_field_attrs
api_1 | self.on_bind_field(field_name, field_obj)
api_1 | File "/usr/local/lib/python3.5/site-packages/marshmallow_jsonapi/schema.py", line 164, in on_bind_field
api_1 | field_obj.load_from = self.inflect(field_name)
api_1 | File "/usr/local/lib/python3.5/site-packages/marshmallow_jsonapi/schema.py", line 190, in inflect
api_1 | return self.opts.inflect(text) if self.opts.inflect else text
api_1 | AttributeError: 'SchemaOpts' object has no attribute 'inflect'
似乎由于我的Schema类继承了两个不同的超类,因此会导致问题。我希望这两个marshmallow库非常兼容,但似乎确实存在issue。
所有这一切的结果是我不太确定下一步该尝试什么。我真的不期待Marshmallow框架的任何具体建议,更多的是试图展示我的思路。是否存在围绕此类设计的任何最佳实践,或者我是否试图立即解决太多问题?
(Python和SO都是新手 - 如果有任何不清楚的话,请道歉。)
答案 0 :(得分:0)
我已成功组合了棉花糖-jsonapi +棉花糖-sqlalchemy。这是魔术:
import marshmallow
import marshmallow_jsonapi
import marshmallow_jsonapi.flask
import marshmallow_sqlalchemy
import myapp.database as db
def make_jsonapi_schema_class(model_class):
class SchemaOpts(marshmallow_sqlalchemy.ModelSchemaOpts, marshmallow_jsonapi.SchemaOpts):
pass
class Schema(marshmallow_sqlalchemy.ModelSchema, marshmallow_jsonapi.flask.Schema):
OPTIONS_CLASS = SchemaOpts
@marshmallow.post_load
def make_instance(self, data):
# Return deserialized data as a dict, not a model instance
return data
# You can add default behavior here, for example
# id = fields.Str(dump_only=True)
# https://marshmallow-sqlalchemy.readthedocs.io/en/latest/recipes.html#automatically-generating-schemas-for-sqlalchemy-models
class Meta:
# Marshmallow-SQLAlchemy
model = model_class
sqla_session = db.session
# Marshmallow-JSONAPI
type_ = model_class.__name__.lower()
self_view = type_ + '_detail'
self_view_kwargs = {'id': '<id>'}
self_view_many = type_ + '_list'
schema_class = type(model_class.__name__ + 'Schema', (Schema,), {'Meta': Meta})
return schema_class
然后您致电
FooSchema = make_jsonapi_schema_class(Foo)
从您的SQLAlchemy声明性模型生成Marshmallow模式类。然后,如果您想对其进行自定义,则可以转而对该类进行子类化。
(要实现REST API,我使用Flask-REST-JSONAPI,它是在Flask + SQLAlchemy + marshmallow-jsonapi之上构建的。)