【问题标题】:Exposing GraphQL based APIs公开基于 GraphQL 的 API
【发布时间】:2019-10-28 01:39:54
【问题描述】:

我将数据存储在文件系统中(跨多个小文件进行标准化),并且我编写了 python 函数来从文件系统读取/写入数据。读取 API 返回 Job 类型的对象。 Write 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

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

问题:

  • Django/Django REST 框架是否是一个正确的选择?我是新手 Django 和 GraphQL。
  • Django 模型似乎与数据库紧密耦合。我是否必须创建另一个 Job 模型类,并使用 read_jobs 函数返回的 Job 创建它?如果是,我如何从这里创建一个简单的 Web 应用程序?

注意:

  • Job 对象是一个三层嵌套对象,具有许多属性/属性。出于演示目的,我在此处的问题中只保留了四个属性/属性。
  • 我更喜欢 Django,因为我的应用程序在这个阶段可能看起来有点小,但随着时间的推移它会增长,而且我有很多需要添加的功能。我专门寻找基于 django-graphene 的应用程序的解决方案,而不使用 SQLite DB 或假设数据是从某个数据库中获取的。我想利用我的持久性 API 方法从文件系统中查询数据。

【问题讨论】:

    标签: python django graphql graphene-python graphene-django


    【解决方案1】:

    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 库。

    还有一个project of integration of Graphene with Flask

    【讨论】:

    • 感谢您的帮助。我仍然更喜欢 Django,因为在这个阶段我的应用程序可能看起来有点小,但随着时间的推移它会增长,而且我有很多需要添加的功能。我专门寻找创建基于 django-graphene 的应用程序的解决方案,而不使用 SQLite DB 或假设数据是从某个数据库中获取的。我想利用我的持久性 API 方法从文件系统中查询数据。
    • 这里是:github.com/graphql-python/graphene-django>。使用 Django,您不会避免使用数据库,至少对于用户和组而言……但没有什么能阻止您在不使用该数据库的情况下编写视图和处理请求。
    猜你喜欢
    • 2017-12-31
    • 2020-10-19
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    • 1970-01-01
    • 2012-11-17
    • 1970-01-01
    相关资源
    最近更新 更多