我将 Python Ariadne 与 Flask 框架一起使用,除了 Ariadne 游乐场无法访问服务器之外,一切似乎都很好,这很奇怪,因为游乐场是从同一个开发服务器加载的。下面是错误的屏幕截图。您还可以在此链接上查看类似的错误。
] 2
以下是相关的代码文件:
在里面
from flask import Flask
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from dotenv import dotenv_values
import os
server = Flask(__name__)
CORS(server)
# Loads DB env variables
config = dotenv_values(".flaskenv")
# Database configuration
server.config[
"SQLALCHEMY_DATABASE_URI"
] = f"postgresql://{config['DB_USERNAME']}:{config['DB_PASSWORD']}@fanny.db.elephantsql.com/xdmriqqe"
server.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
# Application extensions
db = SQLAlchemy(server)
migrate = Migrate(server, db)
# Application views (uses blueprint)
from app.views import bp
server.register_blueprint(bp)
# Database models
import app.models
GraphQL 架构
type TodoList {
id: ID!
itemName: String!
sublist: [TodoList!]
}
type TodoListResult {
success: String!
error: [String]
todoList: TodoList
}
type Query {
todoList: [TodoListResult!]
}
type Mutation {
updateTodoItem(id: ID!, itemName: String!): TodoListResult!
deleteTodoItem(id: ID!): TodoListResult!
}
schema {
query: Query
mutation: Mutation
}
解析器
from datetime import date
from ariadne import convert_kwargs_to_snake_case
from app.models import TodoList
def list_todos_resolver(*_):
try:
todos = [todo.to_dict() for todo in TodoList]
payload = {"success": True, "todos": todos}
except Exception as error:
raise error
# payload {"success":False, "error":[str(error)]}
return payload
@convert_kwargs_to_snake_case
def update_todos_item_resolver(*_, id, itemName):
pass
@convert_kwargs_to_snake_case
def delete_todos_item_resolver(*_, id):
pass
意见*
from app import server
from flask import Blueprint, request, jsonify
from ariadne.constants import PLAYGROUND_HTML
from ariadne import (
ObjectType,
graphql_sync,
snake_case_fallback_resolvers,
load_schema_from_path,
make_executable_schema,
)
from app.api.resolvers import (
list_todos_resolver,
update_todos_item_resolver,
delete_todos_item_resolver,
)
bp = Blueprint("views", __name__, url_prefix="/api")
# GraphQL schema type definitions
graphql_type_defs = load_schema_from_path("app/api/column.graphql")
# Binds resolver to graphQL Query Type
query = ObjectType("Query")
query.set_field("todoList", list_todos_resolver)
# Binds resolver to graphQL Mutation Type
query = ObjectType("Mutation")
query.set_field("updateTodoItem", update_todos_item_resolver)
query.set_field("deleteTodoItem", delete_todos_item_resolver)
# Bind and execute type definition to query
schema = make_executable_schema(graphql_type_defs, query, snake_case_fallback_resolvers)
@bp.route("/", methods=["GET"])
def client():
return PLAYGROUND_HTML, 200
@bp.route("/", methods=["POST"])
def api():
data = request.get_json()
success, result = graphql_sync(
schema, data, context_value=request, debug=server.debug
)
status_code = 200 if success else 400
return jsonify(data), status_code