怎么说, 用python简直是一种享受. 以为python提供了神奇的魔术方法, 基于这些方法写出的框架非常”智能”.

代码冗余少, 实现优雅 !

本篇文章将简述如何用python提供mongodb+GraphQL的基本服务.

mongoengine

MongoEngine is a Document-Object Mapper (think ORM, but for document databases) for working with MongoDB from Python.

用过Django的同学都知道, 它的orm写的非常顺滑, 用起来行云流水. mongoengine学习了django-orm的语法, 因为mongodb的特性, 省去了迁移等操作从而更加方便.

那有同学说了, mongodb不需要orm!

确实,mongodb比起MySQL等关系型数据库, 操作起来简单不少. 但是在限制字段类型和处理关系事务时, 难免会陷入造轮子的尴尬. mongoengine可以说是神器.

# model.py
from mongoengine import *
from mongoengine import connect
connect('your db name', host='your host',port = 'your port')
class Hero(Document):
    name = StringField(required=True, max_length=12)

    def __str__(self):
        return self.to_json()

好了, 一个模型就这样定义完成了.试试看

>>> from model import Hero
>>> Hero(name='wsq').save()

得到结果


graphene

Graphene is a Python library for building GraphQL schemas/types fast and easily.

提供基本的GraphQL解析服务, 单独使用也可以与各种web框架很好的配合. 作者还提供了graphql-django 和 graphql-flask之类的封装好的包.

import graphene
class Hero(graphene.ObjectType):
    id = graphene.ID()
    name = graphene.String()

class Query(graphene.ObjectType):
    hero = graphene.Field(Hero)
    def resolve_hero(self, info):
        return Hero(id=1, name='wsq')
    
schema = graphene.Schema(query=Query)
query = '''
    query something{
      patron {
        id
        name
        age
      }
    }
'''
result = schema.execute(query)
print(result.data['hero'])

可以看到 schema和query的定义都很方便的完成了. 定义resolver也只需要在Query里定义名为resolve_[name]的函数, 这就是python的方便之处了.

携带参数

class Query(graphene.ObjectType):
   hero = graphene.Field(Hero,id=graphene.String(required=True))
   def resolve_hero(self, info, id):
       return Hero(id=id,name='wsq')

要在golang中实现相同的功能需要冗长的定义和各种重复的代码. 对比之下这样的实现无疑非常优雅.

与mongoengine的结合

因为我们并未定义id字段, mongodb自动生成的表示字段为_id, 而在graphql中id将作为标识字段

# model.py
class Hero(Document):
    id = ObjectIdField(name='_id')
    name = StringField(required=True, max_length=12)

手动定义id字段, 映射到mongodb自动生成的_id.

from model import Hero as HeroModel
def resolve_hero(self, info, id):
        hero = HeroModel.objects.get(id=id)
        return Hero(id=hero.id, name=hero.name)

虽然实现很方便, 但是这样的代码还是有些笨拙. 作者贴心的提供了graphene_mongo这样的中间件, 可以解决大部分字段类型的绑定问题.

import graphene
from model import Hero as HeroModel
from graphene_mongo import MongoengineObjectType

class Hero(MongoengineObjectType):
    class Meta:
        model = HeroModel

class Query(ObjectType):
    heroes = graphene.List(Hero)
    hero = graphene.Field(Hero, id=ID(required=True))

    def resolve_heroes(self, info):
        return list(HeroModel.objects())

    def resolve_hero(self, info, id):
        return HeroModel.objects.get(id=id)

与flask的结合

因为graphql的特性, 只需要一个url即可响应所有的请求. 我们当然可以自己写一个入口, 用于接收graphql字符串,处理以后返回json字符串.

这是标准化的流程, 作者提供了flask-graphql这样的中间件, 一键开启基于flask的graphql服务.

from flask import Flask
from flask_graphql import GraphQLView
from test import schema

app = Flask(__name__)
app.debug = True

app.add_url_rule('/graphql', view_func=GraphQLView.as_view('graphql', schema=schema, graphiql=True))
if __name__ == '__main__':
    app.run()

Supported options

  • schema: The GraphQLSchema object that you want the view to execute when it gets a valid request.
  • context: A value to pass as the context to the graphql() function.
  • root_value: The root_value you want to provide to executor.execute.
  • pretty: Whether or not you want the response to be pretty printed JSON.
  • executor: The Executor that you want to use to execute queries.
  • graphiql: If True, may present GraphiQL when loaded directly from a browser (a useful tool for debugging and exploration).
  • graphiql_template: Inject a Jinja template string to customize GraphiQL.
  • batch: Set the GraphQL view as batch (for using in Apollo-Client or ReactRelayNetworkLayer)

结束语

开发效率一级棒, 写起来也非常爽. 这是python的魅力. golang实现相同的功能需要数倍于python的代码量.

文章来源于互联网:python — 搭建GraphQL服务

发表评论