温欣爸比

  • 主页
  • Alfred Workflow
  • 《Vim 练级手册》
  • 常用命令
  • 代码笔记
  • 合辑
  • 在线工具
所有文章 友链 关于我

温欣爸比

  • 主页
  • Alfred Workflow
  • 《Vim 练级手册》
  • 常用命令
  • 代码笔记
  • 合辑
  • 在线工具

Python 中使用 Graphql 返回 JSON 类型

2018-02-14

在使用 Graphql 在 Python 中的模块 Graphene 时,发现默认返回类型没有 JSON 格式,通过网上资料发现需要自己补充该类型才可以。



  • py2
  • py3
  • 使用

py2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import graphene
from graphene.types.scalars import MIN_INT, MAX_INT
from graphql.language.ast import BooleanValue, StringValue, IntValue, ListValue, ObjectValue, FloatValue


class JSON(graphene.Scalar):
"""
The `JSON` scalar type represents JSON values as specified by
[ECMA-404](http://www.ecma-international.org/
publications/files/ECMA-ST/ECMA-404.pdf).
"""

@staticmethod
def identity(value):
if isinstance(value, (unicode, str, bool, int, float)):
return value.__class__(value)
elif isinstance(value, (list, dict)):
return value
else:
return None

serialize = identity
parse_value = identity

@staticmethod
def parse_literal(ast):
if isinstance(ast, (StringValue, BooleanValue)):
return ast.value
elif isinstance(ast, IntValue):
num = int(ast.value)
if MIN_INT <= num <= MAX_INT:
return num
elif isinstance(ast, FloatValue):
return float(ast.value)
elif isinstance(ast, ListValue):
return [JSON.parse_literal(value) for value in ast.values]
elif isinstance(ast, ObjectValue):
return {field.name.value: JSON.parse_literal(field.value) for field in ast.fields}
else:
return None

py3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import graphene
from graphql.language.ast import BooleanValue, StringValue, IntValue, ListValue, ObjectValue, FloatValue

class JSON(graphene.Scalar):
"""
The `JSON` scalar type represents JSON values as specified by
[ECMA-404](http://www.ecma-international.org/
publications/files/ECMA-ST/ECMA-404.pdf).
"""

@staticmethod
def identity(value):
if isinstance(value, (str, bool, int, float)):
return value.__class__(value)
elif isinstance(value, (list, dict)):
return value
else:
return None

serialize = identity
parse_value = identity

@staticmethod
def parse_literal(ast):
if isinstance(ast, (StringValue, BooleanValue)):
return ast.value
elif isinstance(ast, IntValue):
return int(ast.value)
elif isinstance(ast, FloatValue):
return float(ast.value)
elif isinstance(ast, ListValue):
return [JSON.parse_literal(value) for value in ast.values]
elif isinstance(ast, ObjectValue):
return {field.name.value: JSON.parse_literal(field.value) for field in ast.fields}
else:
return None

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy(wxnacy@gmail.com)

import graphene

class Query(graphene.ObjectType):
test = graphene.Field(JSON)

def resolve_test(self, info):
return dict(name="wxnacy", age=12, types = ['shuaiqi', 'youcai'],
book=dict(name='wohenshuai'))

schema = graphene.Schema(query=Query)

result = schema.execute('{ test }')
print(result.data['test'])
# {'name': 'wxnacy', 'age': 12, 'types': ['shuaiqi', 'youcai'], 'book': {'name': 'wohenshuai'}}

完整 demo 地址:https://github.com/wxnacy/study/blob/master/python/graphql_demo/type_json.py

  • Implement JSON type
最近更新
Alfred Workflow 命令行帮助工具
最近热读
Go 判断数组中是否包含某个 item
Vim 高级功能 vimgrep 全局搜索文件
办理北京工作居住证的一些细节
Go 语法错误:Non-declaration statement outside function body
Mac 电脑查看字体文件位置
扫码关注公众号,或搜索公众号“温欣爸比” 及时获取我的最新文章
赏

谢谢你请我喝咖啡

支付宝
微信
  • python
  • graphql
除夕啦
Javascript trim() 方法及兼容
  1. 1. py2
  2. 2. py3
  3. 3. 使用
© 2017 - 2022 温欣爸比 京ICP备15062634号 总访问量3297次 访客数3249人次 本文总阅读量3次
Hexo Theme Yilia by Litten
  • 所有文章
  • 友链
  • 关于我

tag:

  • python
  • flask
  • javascript
  • docker
  • 工具
  • openresty
  • 微信
  • java
  • hexo
  • 杂谈
  • vim
  • git
  • mysql
  • http
  • linux
  • mac
  • tmux
  • ssh
  • 算法
  • 开发
  • node
  • 杂文
  • jinja2
  • maven
  • spring
  • 北京
  • 生活
  • springboot
  • react
  • shell
  • graphql
  • iterm
  • expect
  • nginx
  • sqlalchemy
  • html
  • electron
  • vagrant
  • elastic
  • 宝贝
  • ansible
  • css
  • jquery
  • go
  • markdown
  • awk
  • redis
  • leetcode
  • zsh
  • 漫威
  • ssr
  • android
  • ffmpeg
  • chrome
  • vmware
  • youtube
  • windows
  • jupyter
  • excel
  • jq
  • Mac
  • Homebrew
  • mongo
  • py2
  • HomeBrew
  • movie
  • nodejs

    缺失模块。
    1、请确保node版本大于6.2
    2、在博客根目录(注意不是yilia根目录)执行以下命令:
    npm i hexo-generator-json-content --save

    3、在根目录_config.yml里添加配置:

      jsonContent:
        meta: false
        pages: false
        posts:
          title: true
          date: true
          path: true
          text: false
          raw: false
          content: false
          slug: false
          updated: false
          comments: false
          link: false
          permalink: false
          excerpt: false
          categories: false
          tags: true
    

  • Guru99
每天看书
每天背单词
每天一篇
写写代码
听听周杰伦
爱爱老婆