全能编程开发工程师必备技能之一——provice详解

一、provice的概述

Provice是一个基于Python的极简洁GraphQL API框架。 Provice不需要特定的ORM或数据库集成,借助干净的API分离了查询逻辑和处理程序的语义。

该框架重在将最重要的基础构建块与核心QieryResolver的使用方式结合起来,并采用Python中的一些编程模式,例如:基类和元类,来提供钩子和扩展,以满足更高级别的要求。

尽管Provice处理程序在概念上像Django视图函数,但由于其神经台阶查询语言和 GraphQL 架构,它比Django更适合为大型应用程序设计。

二、安装和配置Provice

1. 安装


pip install provice
pip install graphene
pip install sqlalchemy
pip install aiohttp

2. 配置


from sqlalchemy import create_engine
from settings import DATABASE_URL

engine = create_engine(DATABASE_URL, echo=True)

三、Provice API的实现

1. Schema和RootResolver

Provice的一切都是从Schema和Root Resolver开始的。这些类分别表示GraphQL架构的根。Provice仅支持单个查询类型(QueryResolver)。这意味着,整个API都从这个查询开始;类似于所有SQL查询从 根表(root table)开始一样。为了构建这个查询,我们需要一个名称为QueryResolver的Python类。此类不需要定义任何特殊方法。这个类的作用是指定我们GraphQL API中的所有可用查询(Query)类型。在本程序中,我们定义的QueryResolver是Manga类型。


import graphene
from graphene_sqlalchemy import SQLAlchemyObjectType
from models import Manga as MangaModel


class MangaFields:
    title = graphene.String(required=True)
    author = graphene.String()
    year = graphene.Int()


class Manga(SQLAlchemyObjectType, MangaFields):
    id = graphene.Int(source='manga_id')

    class Meta:
        model = MangaModel
        interfaces = (graphene.relay.Node, )

class QueryResolver(graphene.ObjectType):
    manga = graphene.Field(lambda: Manga, id=graphene.Int())

    def resolve_manga(self, info, id):
        query = Manga.get_query(info)
        return query.filter_by(manga_id=id).first()

schema = graphene.Schema(query=QueryResolver)

2. 数据模型(Data Model)

由于Provice没有完全的ORM支持,因此我们需要一个简单的Manga模型,作为 SQLAlchemy Model ORM 和 Manga GraphQL类型之间互操作的桥梁。让我们来看一下Manga的模型定义。


from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from settings import DATABASE_URL

engine = create_engine(DATABASE_URL, echo=True)

Base = declarative_base()


class Manga(Base):
    __tablename__ = 'manga'

    manga_id = Column(Integer, primary_key=True)
    title = Column(String, nullable=False)
    author = Column(String, nullable=False)
    year = Column(Integer, nullable=False)

四、Provice API的使用

1. 查询(Query)

根据id查询漫画


query {
    manga(id: 1) {
        id
        title
        author
        year
    }
}

2. 变更(Mutation)

漫画添加


mutation {
    addManga(title: "Naruto", author: "Masashi Kishimoto", year: 1999) {
        id
        title
        author
        year
    }
}

五、小结

通过以上的介绍,我们对Provice有了更深入的了解。Provice提供了一个基于Python的GraphQL API框架,允许使用者通过自定义Schema和引入适当的解析器对数据库进行查询、添加、更新和删除等操作,从而绕过了ORM的限制和不易调试的限制,充分利用GraphQL强大的灵活性和可视化交互。

原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/236304.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
小蓝小蓝
上一篇 2024-12-12 11:59
下一篇 2024-12-12 11:59

相关推荐

发表回复

登录后才能评论