【Python GraphiQL】

基本查询

运行后访问:http://127.0.0.1:5000/grapql

import graphene
from flask import Flask
from flask_graphql import GraphQLView


# 基本查询
class Query(graphene.ObjectType):
    """
        注册查询使用对象
    """
    # 常规数据类型
    ID_ = graphene.ID()
    #  name 为重命名, default_value 默认值, 必传 required
    person = graphene.String(name="people", sex=graphene.String(default_value="男"), desc=graphene.String(required=True))
    age = graphene.Int(age=graphene.Int())
    height = graphene.NonNull(graphene.Float)  # 返回的数据不能为空
    dail = graphene.Boolean(required=True)  # 返回的数据不能为空
    birth_list = graphene.List(graphene.NonNull(graphene.Date))  # 返回的列表中的时间数据不能为空
    birth_Time = graphene.Time()
    birth_DateTime = graphene.DateTime()
    birth_Decimal = graphene.Decimal()
    json_ = graphene.JSONString()


def resolve_person(self, info, sex, desc):
    """
    resolve_person: 固定格式 resolve_+对象名
    sex, desc: 查询参数
    """
    return f"这个人:sex:{sex},desc:{desc}"


app = Flask(__name__)
schema = graphene.Schema(query=Query)
app.add_url_rule("/grapql", view_func=GraphQLView.as_view('grapql', schema=schema, graphiql=True))

if __name__ == '__main__':
    app.run(debug=True)

自定义数据类型

在这里插入图片描述

import graphene
from flask import Flask
from flask_graphql import GraphQLView


class Phone(graphene.ObjectType):
    """
    自定义手机数据类型
    """
    title = graphene.String()
    color = graphene.String()


class Query(graphene.ObjectType):
    """
        注册查询使用对象
    """
    # 自定义的类型
    phone = graphene.Field(Phone)
    phones = graphene.List(Phone)


    def resolve_phone(self, info):
        """
        """
        return Phone(title="华为", color="白色")


    def resolve_phones(self, info):
        """
        """
        return [
            Phone(title="华为A", color="白色A"),
            Phone(title="华为B", color="白色B"),
        ]


app = Flask(__name__)
schema = graphene.Schema(query=Query)
app.add_url_rule("/grapql", view_func=GraphQLView.as_view('grapql', schema=schema, graphiql=True))

if __name__ == '__main__':
    app.run(debug=True)

接口使用

class Animal(graphene.Interface):
    id = ID(required=True)
    name = String(required=True)
    
class Tiger(graphene.ObjectType):
    class Meta:# 继承Animal属性
        interfaces = (Animal,)
	# 特有属性
    run = String()

class Bird(graphene.ObjectType):
    class Meta:class Meta:# 继承Animal属性
        interfaces = (Animal,)
        
	# 特有属性
    flay = String()

class Query(graphene.ObjectType):
 	animal = graphene.Field(Animal, type_=Int(required=True))
    def resolve_animal(self, info, type_):
        print(type_)
        if type_ == 1:
            return Tiger(id=1, name="tiger", run="跑")
        if type_ == 2:
            return Bird(id=2, name="bird", flay="飞")

枚举使用

class Role(graphene.Enum):
    AA = 1
    BB = 2
    CC = 3
    
class Query(graphene.ObjectType):
    animal = graphene.Field(Animal,role = Role())
    def resolve_animal(self,info,role):
    if role == Role.AA :
    ...

GraphQL查询

# select name from table1 t1 left join table2 t2 on t1.id == t2.id ;
{
  hero {
    name
    friends {
      name
    }
  }
}


# select name from table1 where id = '??';
{
  human(id:"1002"){
    name
    appearsIn
  }
}


# select name as n1 name as n2 from table1
{
  h1: human(id:"1002"){
    name
  }
  h2: human(id:"1003"){
    name
  }
}

# 字段复用
{
  h1: human(id:"1002"){
    ...heroFields
  }
  h2: human(id:"1003"){
  	...heroFields
  }
}

fragment heroFields on Character{
    id
    name
    friends {
      id
      name
    }
}

# 设置查询名称
query queryHero{
  h1: human(id:"1002"){
    ...heroFields
  }
  h2: human(id:"1003"){
  	...heroFields
  }
}

# 接口子类专属属性查询
{animal(type_:1) {
  id,
  name,
  ... on Mouse{
    run
  }
  ... on Bird{
    fly
  }
}}

# 参数输入

query queryHero($id:String!){
  h1: human(id:$id){
    name
    id
  }
}

{
  "id": "1002"
}

数据修改

phone_list = []

class Phone(graphene.ObjectType):
    """
    自定义手机数据类型
    """
    title = String()
    color = String()


class AddPhone(graphene.Mutation):
    # 返回给给前端字段,加载手机的所有属性
    phone = Field(Phone)

    # 可修改的字段,前端传递的参数定义
    class Arguments:
        title = String()
        color = String()

    # 接收前端传入的参数
    def mutate(self, info, title, color):
        phone = Phone(title=title, color=color)
        phone_list.append(phone)
        return AddPhone(phone=phone)


class Mutation(ObjectType):
    """
    修改数据
    """
    # 提供给前端的对象
    add_phone = AddPhone().Field()
    
schema = Schema(query=Query, mutation=Mutation) # mutation=Mutation

SqlAlchemy的结合使用

import graphene
from flask import Flask
from flask_graphql import GraphQLView
from sqlalchemy import create_engine, Column, String, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.orm import sessionmaker
from urllib.parse import quote
from graphene_sqlalchemy import SQLAlchemyObjectType, SQLAlchemyConnectionField

DB = "mysql"
DRIVER = "pymysql"  # mysqldb
USER = "root"
PASSWORD = quote("xyit@XU0010")  # 转换特殊字符
HOST = "192.168.0.116"
PORT = "3306"
DBNAME = "FlaskDB"
DB_URL = f"{DB}+{DRIVER}://{USER}:{PASSWORD}@{HOST}:{PORT}/{DBNAME}"
engine = create_engine(DB_URL)
db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()


class PersonMode(Base):
    __tablename__ = 't_person'
    # 在这个ORM模型中创建一些属性,来跟表中的字段进行一一映射。
    # 这些属性必须是sqlalchemy给我们提供好的数据类型
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(50))
    age = Column(Integer)
    country = Column(String(50))


class Person(SQLAlchemyObjectType): # SQLAlchemyObjectType
    class Meta:
        model = PersonMode
        interfaces = (graphene.relay.Node,)


class Query(graphene.ObjectType):
    """查询"""
    people = graphene.Field(Person, id=graphene.String(required=True))
    persons = graphene.List(Person)

    node = graphene.relay.Node.Field()
    personss = SQLAlchemyConnectionField(Person.connection)

    def resolve_people(self, info, id):
        return Person.get_node(info=info, id=id)

    def resolve_persons(self, info):
        q = Person.get_query(info)
        return q.all()


app = Flask(__name__)
schema = graphene.Schema(query=Query)
app.add_url_rule("/grapql", view_func=GraphQLView.as_view('grapql', schema=schema, graphiql=True))

if __name__ == '__main__':
    app.run(debug=True)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值