Python 3.x 在石墨烯中使用与多个解析器相同的连接
我有这样的代码Python 3.x 在石墨烯中使用与多个解析器相同的连接,python-3.x,flask,graphql,graphene-python,flask-graphql,Python 3.x,Flask,Graphql,Graphene Python,Flask Graphql,我有这样的代码 # 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(gr
# 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查询字符串,那就太好了