在石墨烯中使用与多个解析器相同的连接
Posted
技术标签:
【中文标题】在石墨烯中使用与多个解析器相同的连接【英文标题】:Using same connection with multiple resolvers in graphene 【发布时间】:2020-03-26 09:13:15 【问题描述】:我有这样的代码,
# 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。代码工作得很好,但我认为我在这里遗漏了一些东西,因为我需要在每个解析器中打开新连接,并且我需要再次编写相同的查询,所以存在数据重复,所以这是正确的做法还是我遗漏了什么?
任何帮助将不胜感激!提前谢谢你。
【问题讨论】:
【参考方案1】:在每个查询(在这种情况下为解析器)打开一个新连接是可以的。您还可以设置一个连接池来最小化打开连接的成本。
只是好奇,您使用的是什么数据库适配器或 ORM?如果您可以将连接和游标步骤重构为单个函数以调用每个解析器并且只需要传递 SQL 查询字符串,那就太好了。
【讨论】:
以上是关于在石墨烯中使用与多个解析器相同的连接的主要内容,如果未能解决你的问题,请参考以下文章
如何动态创建石墨烯对象?例如,我想在运行时根据配置文件添加字段和解析器
多个字段解析器使用不同的查询参数解析相同的 REST API