Flask-GraphQL-SQLAlchemy 开发文档 | Develop Docs
作者 | Author:杨晗光
概述 | Overview
GraphQL是一个由facebook开发的API查询语言。对于前端开发者来说,它非常棒。但是有关于它的python开发文档却很少。所以我写了这个文档来帮助后来者快速搭建一个GraphQL服务。
GraphQL is a API query language developed by facebook. It’s pretty cool for frontend developers. But there are few documents about its python version. So I write this doc to help the later start quickly build a GraphQL service.
注意,这不是一个Python的新手教程,所以我将不会一步一步的教你怎么写代码。如果你发现某些部分难以理解,我想谷歌和百度是万能的。
Please note, this is not a beginner’s tutorial for Python, so I will not teach you step by step. If you find some parts are hard to understand, I think you can search the results by Baidu or Google.
这篇文档的原始版本是用于公司内部的纯英文说明,在这里抽取主要部分并翻译成中文后发布出来,如果有哪里感觉别扭还请见谅。
The original version of this document is for the company’s in-house instructions in pure English, I extracted the main parts and translated into Chinese and released, if you feel uncomfortable, please forgive me.
入门 | Getting Started
虚拟环境 | Virtual Environment
GraphQL同时支持python2.7和pythong3.4+,但是即将到来的更新至支持python3.6+。你最好用这个版本来创建虚拟环境。
GraphQL support both python2.7 and python3.4+, but the upcoming update only support python3.6+. You’d better build virtualenv from this version.
virtualenv -p python3.6 graphql
source graphql/bin/activate
安装依赖 | Install Requirements
这里有一些最常用的依赖包。如果你有其它需求,你可以上github搜索。
Here are some of the most commonly used dependency packages. If you have other requirements, you can search them on github.
pip install flask sqlalchemy graphene flask-graphql flask-sqlalchemy graphene-sqlalchemy
# MySQL
pip install mysqlclient
# PostgreSQL
pip install psycopg2-binary
运行服务器 | Run Server
首先,你需要创建一个flask app,用PyCharm很简单就能搞定。然后你应该把下面的代码添加到你的app里。我觉得你应该知道它们应该放到哪。
First, you need create a flask app. You can easily do it by PyCharm. Then please add codes below to your app. I think you know where they should be.
import graphene
from flask_graphql.graphqlview import GraphQLView
class Query(graphene.ObjectType):
foo = graphene.String()
schema = graphene.Schema(query=Query, auto_camelcase=False)
app.add_url_rule('/graphql', view_func=GraphQLView.as_view('graphql',
schema=schema, graphiql=True))
查询 | Query
如果你有公网,你可以直接在浏览器访问 http://localhost:5000/graphql 。这是GraphiQL,对新手非常友好的一个前端。但是如果你没有的话,就只能自己手动发送POST请求了。
If you have a public network, you can access http://localhost:5000/graphql in your browser. It atually is GraphiQL, friendly for new hand. But if not, you should consider POST request by yourself.
curl命令:
curl command:
curl -H "Content-Type: application/json" \
-d '{"query": "{foo}"}' \
http://localhost:5000/graphql
python请求:
python requests:
import requests
requests.post('http://localhost:5000/graphql', json={
'query': '{foo}'
})
新字段 | New Fields
Hello World!
让我们在上面的Query类中创建一个"Hello World!"字段。
Let’s create a “Hello World!” field in Query class above…
class Query(graphene.ObjectType):
hello_world = graphene.String()
@staticmethod
def resolve_hello_world(obj, info, **kwargs):
return "Hello World!"
好!尝试发送一个请求吧!
Cool! Try to post a query now!
requests.post('http://localhost:5000/graphql', json={
'query': '{hello_world}'
})
简单字段 | Simple Field
如上所述,一个简单的字段需要声明字段类型并定义一个该字段的解析器。GraphQL有很多内建类型(标量类型),像Int,Float,String,Boolean等。你可以在graphene.types里找到它们。它们的实现和Hello World差不多。
As we explained above, simple field should declare a field type and define a field resolver. GraphQL has a lot of built-in field types (Scalar Type), such as Int, Float, String, Boolean, etc. You can find all of them in graphene.types. All of them are similar to your Hello World.
你可以给自己的字段加上描述,把参数description={some_text}
传递给你的类型定义即可。你可以在GraphiQL上看到你的描述。
You could also add some description to your field. Just pass description={some_text}
to your type definition. You could see your descriptions on GraphiQL.
你可能还想自定义一些参数,这对于复杂查询非常有用。你应该把你的参数名和类型传递到你的字段类型定义中。参数类型和字段类型其实有一点小区别,但是现在你就姑且当它们是一样的吧。这些参数将会被graphql传递到你的解析器中。
Another point is maybe you want to add some custom args, it’s useful for our complex queries. You should pass custom args with their types to field type definition same as description. The args type has a little different with field type, but for now, you can just think they are all the same. You can get them in your resolver function.
现在让我们来创建一个简单的计算函数:add
Now, let’s create a new field to implement a simple calculate function: add
class Query(graphene.ObjectType):
add = graphene