怎么說, 用python簡直是一種享受. 以為python提供了神奇的魔術(shù)方法, 基于這些方法寫出的框架非常"智能".
代碼冗余少, 實現(xiàn)優(yōu)雅 !
本篇文章將簡述如何用python提供mongodb+GraphQL的基本服務(wù).
mongoengine
MongoEngine is a Document-Object Mapper (think ORM, but for document databases) for working with MongoDB from Python.
用過Django的同學(xué)都知道, 它的orm寫的非常順滑, 用起來行云流水. mongoengine學(xué)習(xí)了django-orm的語法, 因為mongodb的特性, 省去了遷移等操作從而更加方便.
那有同學(xué)說了, mongodb不需要orm!
確實,mongodb比起MySQL等關(guān)系型數(shù)據(jù)庫, 操作起來簡單不少. 但是在限制字段類型和處理關(guān)系事務(wù)時, 難免會陷入造輪子的尷尬. 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()
得到結(jié)果
<Hero: {"name": "wsq"}>
graphene
Graphene is a Python library for building GraphQL schemas/types fast and easily.
提供基本的GraphQL解析服務(wù), 單獨使用也可以與各種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]的函數(shù), 這就是python的方便之處了.
攜帶參數(shù)
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中實現(xiàn)相同的功能需要冗長的定義和各種重復(fù)的代碼. 對比之下這樣的實現(xiàn)無疑非常優(yōu)雅.
與mongoengine的結(jié)合
因為我們并未定義id字段, mongodb自動生成的表示字段為_id
, 而在graphql中id
將作為標(biāo)識字段
# 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)
雖然實現(xiàn)很方便, 但是這樣的代碼還是有些笨拙. 作者貼心的提供了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的結(jié)合
因為graphql的特性, 只需要一個url即可響應(yīng)所有的請求. 我們當(dāng)然可以自己寫一個入口, 用于接收graphql字符串,處理以后返回json字符串.
這是標(biāo)準(zhǔn)化的流程, 作者提供了flask-graphql這樣的中間件, 一鍵開啟基于flask的graphql服務(wù).
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
: TheGraphQLSchema
object that you want the view to execute when it gets a valid request.context
: A value to pass as thecontext
to thegraphql()
function.root_value
: Theroot_value
you want to provide toexecutor.execute
.pretty
: Whether or not you want the response to be pretty printed JSON.executor
: TheExecutor
that you want to use to execute queries.graphiql
: IfTrue
, 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)
結(jié)束語
開發(fā)效率一級棒, 寫起來也非常爽. 這是python的魅力. golang實現(xiàn)相同的功能需要數(shù)倍于python的代碼量.