【问题标题】:how can I pass curent_user from flask-security to a pluggable view function?如何将curent_user 从flask-security 传递给可插入的视图函数?
【发布时间】:2018-06-16 10:56:54
【问题描述】:

我有一个烧瓶应用程序,它使用烧瓶安全性进行身份验证。我想使用带有graphene 的graphql 来获取数据,但是我无法访问current_user 代理,这是我一直用来解析请求的。 graphene 仅提供了一个自定义的pluggable view,这是可以理解的,但它无法在应用程序的上下文中访问 c​​urrent_user,因此 current_user 恢复为 AnonymousUser。

这里是一些示例代码

from flask import Flask, render_template, redirect, request
from flask_security import Security, SQLAlchemySessionUserDatastore, login_required, current_user, login_user

from flask_graphql import GraphQLView
import graphene
from graphene_sqlalchemy import SQLAlchemyConnectionField

from .models import UserModel, RoleModel, Todo, TodoModel
from .pipeline import session

app = Flask(__name__, template_folder="../templates", static_folder="../static")
app.config.from_object('core.pipeline.configs.DevConfig')
user_datastore = SQLAlchemySessionUserDatastore(session, UserModel, RoleModel)
security = Security(app, user_datastore)

@app.route('/')
@login_required
def index(path):
    user = current_user

    return render_template('index.html')

【问题讨论】:

  • 你在使用 JWT 进行身份验证吗?

标签: flask flask-sqlalchemy graphql flask-security graphene-python


【解决方案1】:

您的代码中的主要问题是

app.add_url_rule('/graphql', view_func=graphql_view())

graphql_view() 在代码加载期间在没有任何烧瓶请求上下文的情况下运行。

请试试这个代码

class GraphQLViewCurrentUser(GraphQLView):

    def get_context(self, request):
        context = super().get_context(request)
        context.update({'current_user': current_user})
        return context


app.add_url_rule(
    '/graphql', view_func=GraphQLViewCurrentUser.as_view(
        'graphql', schema=schema, context={}, graphiql=True))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    • 2023-03-31
    • 1970-01-01
    相关资源
    最近更新 更多