python — 搭建GraphQL服務(wù)

怎么說, 用python簡直是一種享受. 以為python提供了神奇的魔術(shù)方法, 基于這些方法寫出的框架非常"智能".

代碼冗余少, 實(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的語法, 因?yàn)閙ongodb的特性, 省去了遷移等操作從而更加方便.

那有同學(xué)說了, mongodb不需要orm!

確實(shí),mongodb比起MySQL等關(guān)系型數(shù)據(jù)庫, 操作起來簡單不少. 但是在限制字段類型和處理關(guān)系事務(wù)時(shí), 難免會(huì)陷入造輪子的尷尬. 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()

好了, 一個(gè)模型就這樣定義完成了.試試看

>>> 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ù), 單獨(dú)使用也可以與各種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中實(shí)現(xiàn)相同的功能需要冗長的定義和各種重復(fù)的代碼. 對(duì)比之下這樣的實(shí)現(xiàn)無疑非常優(yōu)雅.

與mongoengine的結(jié)合

因?yàn)槲覀儾⑽炊xid字段, mongodb自動(dòng)生成的表示字段為_id, 而在graphql中id將作為標(biāo)識(shí)字段

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

手動(dòng)定義id字段, 映射到mongodb自動(dòng)生成的_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)

雖然實(shí)現(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é)合

因?yàn)間raphql的特性, 只需要一個(gè)url即可響應(yīng)所有的請(qǐng)求. 我們當(dāng)然可以自己寫一個(gè)入口, 用于接收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: 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)

結(jié)束語

開發(fā)效率一級(jí)棒, 寫起來也非常爽. 這是python的魅力. golang實(shí)現(xiàn)相同的功能需要數(shù)倍于python的代碼量.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • # Python 資源大全中文版 我想很多程序員應(yīng)該記得 GitHub 上有一個(gè) Awesome - XXX 系列...
    aimaile閱讀 26,822評(píng)論 6 427
  • Python 資源大全中文版 我想很多程序員應(yīng)該記得 GitHub 上有一個(gè) Awesome - XXX 系列的資...
    Clemente閱讀 3,303評(píng)論 0 54
  • 22年12月更新:個(gè)人網(wǎng)站關(guān)停,如果仍舊對(duì)舊教程有興趣參考 Github 的markdown內(nèi)容[https://...
    tangyefei閱讀 35,388評(píng)論 22 257
  • 環(huán)境管理管理Python版本和環(huán)境的工具。p–非常簡單的交互式python版本管理工具。pyenv–簡單的Pyth...
    MrHamster閱讀 3,949評(píng)論 1 61
  • 在第二個(gè)工作離職的前兩年,我便開始不安分起來,經(jīng)常蠢蠢欲動(dòng)想做點(diǎn)什么。這種不安分,來自于對(duì)日復(fù)一日重復(fù)性工作的厭倦...
    相知是緣閱讀 771評(píng)論 0 0

友情鏈接更多精彩內(nèi)容