公开基于 GraphQL 的 API

Exposing GraphQL based APIs

我将数据存储在文件系统中(跨多个小文件标准化)并且我已经将 python 函数写入文件系统中的 read/write 数据。读取 API returns 作业类型的对象。写入 API 期望将类型为 Job 的对象作为参数传递。

def get_jobs(starttime, endtime):
  ''' Reads and returns jobs that ran between starttime and endtime interval '''


def put_job(job):
  ''' Persists Job object to a file system '''


class Job:
    def __init__(self, name, key, starttime, endtime):
        self.name = name 
        self.key = key
        self.starttime = starttime
        self.endtime = endtime

现在我想通过网络服务器公开这些功能。我更喜欢用 Django 公开 GraphQL APIs。

问题:

注:

Django 可能是一个(不错但更重)的解决方案,但这里是使用 Flask:

的更简单的解决方案
from flask import Flask, jsonify

app = Flask(__name__)

class Job:
    def __init__(self, name, key, starttime, endtime):
        self.name = name 
        self.key = key
        self.starttime = starttime
        self.endtime = endtime

@app.route("/get", methods=['GET'])
def get_jobs(starttime, endtime):
    ''' Reads and returns jobs that ran between starttime and endtime interval '''
    jobs = read_data(starttime, endtime) # your read_data() method
    return jsonify({'jobs': jobs})

@app.route("/put", methods=['POST'])   # or methods=['PUT']
def put_job(request):

    # access your data trough the request object:
    job_name = request.args.get('name', '')
    job_key = request.args.get('key', '')

    # or get it in json
    job_data = request.json

    write_data(Job.from_json(job_data))

我在这里使用 Json 是因为我更习惯使用它,但是如果 GraphQL 对您很重要,我向您推荐 Graphene-Python 库。

There is also a project of integration of Graphene with Flask