graphene-python学习笔记(3)scalars
二、标量
(1)标量的参数
所有标量类型都接受以下参数。所有都是可选的:
name:字符串
覆盖字段的名称。
description:字符串
要在GraphiQL浏览器中显示的类型的说明。
required:布尔值
如果True,服务器将强制执行此字段的值。见NonNull。默认是False。
deprecation_reason:字符串
提供字段的弃用原因。
default_value:任何
为Field提供默认值。
2、标量的类型
graphene提供了以下基础标量
graphene.String
表示文本数据,表示为UTF-8字符序列。GraphQL最常用于表示自由形式的人类可读文本。
graphene.Int
表示非小数有符号整数值。Int可以表示- (2 ^ 53-1)和2 ^ 53-1之间的值,因为在JSON中表示为IEEE 754指定的双精度浮点数。
graphene.Float
表示由IEEE 754指定的带符号的双精度小数值 。
graphene.Boolean
表示真或假。
graphene.ID
表示唯一标识符,通常用于重新获取对象或作为缓存的键。ID类型作为String出现在JSON响应中; 但是,它并不是人类可读的。当预期作为输入类型时,任何字符串(例如“4”)或整数(例如4)输入值都将被接受为ID。
Graphene还为Dates,Times和JSON提供自定义标量:
graphene.types.datetime.Date
表示由iso8601指定的Date值。
graphene.types.datetime.DateTime
表示由iso8601指定的DateTime值。
graphene.types.datetime.Time
表示由iso8601指定的Time值。
graphene.types.json.JSONString
表示JSON字符串。
3、自定义基础标量
自定义DateTime。
import datetime
from graphene.types import Scalar
from graphql.language import ast
class DateTime(Scalar):
'''DateTime Scalar Description'''
@staticmethod
def serialize(dt):
return dt.isoformat()
@staticmethod
def parse_literal(node):
if isinstance(node, ast.StringValue):
return datetime.datetime.strptime(
node.value, "%Y-%m-%dT%H:%M:%S.%f")
@staticmethod
def parse_value(value):
return datetime.datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%f")
4、使用标量
标量一般会作为ObjectType,Interface,Mutation,Query中作为字段类型
示例
class Person(graphene.ObjectType):
name = graphene.String()
# Is equivalent to:
class Person(graphene.ObjectType):
name = graphene.Field(graphene.String)
注意,使用Field构造字段时传递的是graphene.String Type而不是实例graphene.String()
实例可以使用参数:参数to使用的就是实例。
graphene.Field(graphene.String, to=graphene.String()) # Is equivalent to: graphene.Field(graphene.String, to=graphene.Argument(graphene.String))
浙公网安备 33010602011771号