在石墨烯中与多个旋转变压器使用相同的连接



我有这样的代码,

# 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))

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

任何帮助将不胜感激!提前谢谢你。

在每个查询(在本例中为解析程序(上打开一个新连接是可以的。您还可以设置连接池以最大程度地降低打开连接的成本。

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

最新更新