将sqlalchemy与ripozo集成,轻松创建sqlalchemy支持的超媒体/hateoas/restapi
ripozo-sqlalchem的Python项目详细描述
里波佐炼金术
这个包是一个ripozo扩展,它提供了一个集成 里波佐的炼金术。它为生成资源提供了方便的功能。 特别是,它专注于为crud类型的操作创建快捷方式。完全的 实现中提供的BaseManager类。 ripozo包装。
示例
这是一个创建ripozo管理器的最小示例 使用ripozo sqlalchemy并将它们与 资源。
首先我们需要建立我们的sqlalchemy模型。
fromripozoimportapimethod,ResourceBasefromsqlalchemyimportColumn,Integer,String,create_enginefromsqlalchemy.ext.declarativeimportdeclarative_base# Setup the database with sqlalchemyengine=create_engine('sqlite:///:memory:',echo=True)Base=declarative_base()# Declare your ORM modelclassPerson(Base):__tablename__='person'id=Column(Integer,primary_key=True)first_name=Column(String)last_name=Column(String)# Sync the models wiht the databaseBase.metadata.create_all()
现在我们可以进入ripozo sqlalchemy部分。
fromripozo_sqlalchemyimportAlchemyManager,ScopedSessionHandler# A session handler if responsible for getting# And handling a session after either a successful or unsuccessful requestsession_handler=ScopedSessionHandler(engine)# This is the code that is specific to ripozo-sqlalchemy# You give it the session, a SQLAlchemy Model, and the fields# You wish to serialize at a minimum.classPersonManager(AlchemyManager):model=Personfields=('id','first_name','last_name')# This is the ripozo specific part.# This creates a resource class that can be given# to a dispatcher (e.g. the flask-ripozo package's FlaskDispatcher)classPersonResource(ResourceBase):manager=PersonManager(session_handler)pks=['id']namespace='/api'# A retrieval method that will operate on the '/api/person/<id>' route# It retrieves the id, first_name, and last_name properties for the# resource as identified by the url parameter id.@apimethod(methods=['GET'])defget_person(cls,request):properties=cls.manager.retrieve(request.url_params)returncls(properties=properties)
轻松资源
或者,我们可以使用create_resource方法 将自动创建相应的管理器和资源 给经理。
fromripozoimportrestmixinsfromripozo_sqlalchemyimportScopedSessionHandler,create_resourcesession_handler=ScopedSessionHandler(engine)PersonResource=create_resource(Person,session_handler)
默认情况下,create_resource将为您提供完整的crud+l(create、retrieve、update、delete、list)。 尽管可以通过许多选项来创建资源,以精确地修改 资源类被构造。
创建资源类后,需要将其加载到调度程序中 与你的框架相对应。例如,在烧瓶里波佐
fromflaskimportFlaskfromflask_ripozoimportFlaskDispatcherfromripozo.adaptersimportSirenAdapter,HalAdapter# These are the potential formats to returnapp=Flask(__name__)dispatcher=FlaskDispatcher(app)dispatcher.register_adapters(SirenAdapter,HalAdapter)dispatcher.register_resources(PersonResource)app.run()