0

我有这样的代码,

# SWAMI KARUPPASWAMI THUNNAI

import jwt
import graphene
from flask import request
from auth.helper import medease_token
from database.get_connection import get_connection
from flask_graphql import GraphQLView


class CredentialInformation(graphene.ObjectType):
    """
    graphene object type to get the personal information about the user
    """

    country_code = graphene.String()
    phone = graphene.String()
    verified = graphene.Int()

    @medease_token
    def resolve_country_code(self, root):
        customer_token = request.headers["x-access-token"]
        decoded_token = jwt.decode(customer_token, verify=False)
        customer_id = decoded_token["customer_id"]
        try:
            connection = get_connection()
            cursor = connection.cursor()
            cursor.execute("select country_code from customer_credential where id=%s limit 1", (customer_id, ))
            result = cursor.fetchone()
            return result["country_code"]
        finally:
            cursor.close()
            connection.close()

    @medease_token
    def resolve_phone(self, root):
        customer_token = request.headers["x-access-token"]
        decoded_token = jwt.decode(customer_token, verify=False)
        customer_id = decoded_token["customer_id"]
        try:
            connection = get_connection()
            cursor = connection.cursor()
            cursor.execute("select phone from customer_credential where id=%s limit 1", (customer_id, ))
            result = cursor.fetchone()
            return result["phone"]
        finally:
            cursor.close()
            connection.close()

    @medease_token
    def resolve_verified(self, root):
        customer_token = request.headers["x-access-token"]
        decoded_token = jwt.decode(customer_token, verify=False)
        customer_id = decoded_token["customer_id"]
        try:
            connection = get_connection()
            cursor = connection.cursor()
            cursor.execute("select verified from customer_credential where id=%s limit 1", (customer_id,))
            result = cursor.fetchone()
            return result["verified"]
        finally:
            cursor.close()
            connection.close()


def credential_information_wrapper():
    return GraphQLView.as_view("graphql", schema=graphene.Schema(query=CredentialInformation))

它为 Python graphql 使用了 flask-graphql 和 graphene。代码工作得很好,但我认为我在这里遗漏了一些东西,因为我需要在每个解析器中打开新连接,并且我需要再次编写相同的查询,所以存在数据重复,所以这是正确的做法还是我遗漏了什么?

任何帮助将不胜感激!先感谢您。

4

1 回答 1

0

在每个查询(在这种情况下为解析器)打开一个新连接是可以的。您还可以设置一个连接池以最小化打开连接的成本。

只是好奇,您使用的是什么数据库适配器或 ORM?如果您可以将连接和游标步骤重构为单个函数以调用每个解析器并且只需要传递 SQL 查询字符串,那就太好了。

于 2019-12-15T18:10:00.207 回答