如何使用Orientdb和Flask将多个记录传递给graphql?

时间:2018-02-20 16:34:32

标签: python flask graphql orientdb

我有以下代码,我尝试构建和微服务,允许我在我的应用程序中获取特定字段,从orientdb和graphql开始:

from flask import Flask, request
import graphene
import json
import pyorient

app = Flask(__name__)

class Person(graphene.ObjectType):
  name = graphene.String()
  middle_name = graphene.String()
  last_name = graphene.String()

class Query(graphene.ObjectType):

  person = graphene.Field(Person, id=graphene.Argument(graphene.Int))
  persons = graphene.Field(Person)

def resolve_person(self, info, id):
    with open('orientdb_config.json') as config_file:
        orient_config = json.load(config_file)
        try:
            client = pyorient.OrientDB(orient_config["host"], orient_config["port"])
            session_id = client.connect(orient_config["user"], orient_config["password"])
            client.db_open(orient_config["database"], orient_config["user"], orient_config["password"])
            if client is not None:
                query = "SELECT * FROM Person WHERE @rid = #12: %(id)s" % {'id': id}
                data = client.query(query)
                print(data[0])
                return data[0]
            else:
                return None
        except Exception as e:
            return None

def resolve_persons(self, info):
    with open('orientdb_config.json') as config_file:
        orient_config = json.load(config_file)
        try:
            client = pyorient.OrientDB(orient_config["host"], orient_config["port"])
            session_id = client.connect(orient_config["user"], orient_config["password"])
            client.db_open(orient_config["database"], orient_config["user"], orient_config["password"])
            if client is not None:
                query = "SELECT * FROM Person"
                data = client.query(query)
                result = []
                for d in data:
                    result.append(d)
                return result
            else:
                return None
        except Exception as e:
            return None

schema = graphene.Schema(query=Query)

@app.route("/", methods=['POST'])
def main():
data = json.loads(request.data)
return json.dumps(schema.execute(data['query']).data)

if __name__ == '__main__':
app.run(host='0.0.0.0', port=5002, debug=True)

当我使用其id请求Person时,一切似乎都有效,但当我尝试获取所有人时,graphql以空值响应,我验证查询的结果并且值就在那里。

1 个答案:

答案 0 :(得分:0)

在GraphQL定义中,你应该有

persons = graphene.List(lambda: Person)