superset 后端增加注册接口

好烦啊-- :<

1.先定义modes:

superset\superset\models\user.py

# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

from flask_appbuilder.security.sqla.models import User
from sqlalchemy import String, Column, Boolean
from typing import Union
from superset import db


def id_or_slug_filter(models_name, id_or_slug):
    if isinstance(id_or_slug, int):
        return models_name.id == id_or_slug
    if id_or_slug.isdigit():
        return models_name.id == int(id_or_slug)
    return models_name.slug == id_or_slug


class UserV2(User):
    __tablename__ = "ab_user"

    @classmethod
    def get(cls, id_or_slug: Union[str, int]):
        query = db.session.query(UserV2).filter(id_or_slug_filter(UserV2, id_or_slug))
        return query.one_or_none()

    @classmethod
    def get_user_by_cn_name(cls, cn_name: Union[str]):
        query = db.session.query(UserV2).filter(UserV2.username == cn_name)
        return query.one_or_none()

    @classmethod
    def get_model_by_username(cls, username: Union[str]):
        query = db.session.query(UserV2).filter(UserV2.username == username)
        return query.one_or_none()


    def as_dict(self):
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}

    def __repr__(self):
        return self.username



2.新增注册接口接口

superset\superset\views\users\api.py

# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT     OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
from flask import g, Response, request
from flask_appbuilder.api import expose, safe, BaseApi
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_appbuilder.security.sqla.models import User
from flask_jwt_extended.exceptions import NoAuthorizationError

from superset import appbuilder
from superset.models.user import UserV2
from superset.views.base_api import BaseSupersetApi
from superset.views.users.schemas import UserResponseSchema
from superset.views.utils import bootstrap_user_data

user_response_schema = UserResponseSchema()


class CurrentUserRestApi(BaseSupersetApi):
    """An API to get information about the current user"""

    resource_name = "me"
    openapi_spec_tag = "Current User"
    openapi_spec_component_schemas = (UserResponseSchema,)

    @expose("/", methods=("GET",))
    @safe
    def get_me(self) -> Response:
        """Get the user object corresponding to the agent making the request.
        ---
        get:
          summary: Get the user object
          description: >-
            Gets the user object corresponding to the agent making the request,
            or returns a 401 error if the user is unauthenticated.
          responses:
            200:
              description: The current user
              content:
                application/json:
                  schema:
                    type: object
                    properties:
                      result:
                        $ref: '#/components/schemas/UserResponseSchema'
            401:
              $ref: '#/components/responses/401'
        """
        try:
            if g.user is None or g.user.is_anonymous:
                return self.response_401()
        except NoAuthorizationError:
            return self.response_401()

        return self.response(200, result=user_response_schema.dump(g.user))

    @expose("/roles/", methods=("GET",))
    @safe
    def get_my_roles(self) -> Response:
        """Get the user roles corresponding to the agent making the request.
        ---
        get:
          summary: Get the user roles
          description: >-
            Gets the user roles corresponding to the agent making the request,
            or returns a 401 error if the user is unauthenticated.
          responses:
            200:
              description: The current user
              content:
                application/json:
                  schema:
                    type: object
                    properties:
                      result:
                        $ref: '#/components/schemas/UserResponseSchema'
            401:
              $ref: '#/components/responses/401'
        """
        try:
            if g.user is None or g.user.is_anonymous:
                return self.response_401()
        except NoAuthorizationError:
            return self.response_401()
        user = bootstrap_user_data(g.user, include_perms=True)
        return self.response(200, result=user)


class UserRestApi(BaseApi):
    """
    继承Flask-appbuilder原生用户视图类, 扩展用户操作的接口类
    """
    route_base = "/api/v1/users"
    datamodel = SQLAInterface(UserV2)
    include_route_methods = {
        "register"
    }

    @expose("/register/", methods=("POST",))
    @safe
    def register(self) -> Response:
        """Get the user roles corresponding to the agent making the request.
        ---
        get:
          summary: Get the user roles
          description: >-
            Gets the user roles corresponding to the agent making the request,
            or returns a 401 error if the user is unauthenticated.
          responses:
            200:
              description: The current user
              content:
                application/json:
                  schema:
                    type: object
                    properties:
                      result:
                        $ref: '#/components/schemas/UserResponseSchema'
            401:
              $ref: '#/components/responses/401'
        """
        try:

            data = request.get_json()
            username = data.get("username")

            user_models = UserV2.get_model_by_username(username)
            if username and not user_models:

                result = appbuilder.sm.add_user(

                    username,
                    data.get("first_name"),
                    data.get("last_name"),
                    data.get("email"),
                    appbuilder.sm.find_role(data.get("role")),
                    data.get("password"),
                )
                if result:

                    return self.response(200, result={
                        "status": "Success",
                        "message": "ok",
                    })
                else:
                    return self.response_401()
            else:
                return self.response_401()
        except NoAuthorizationError:
            return self.response_401()

3. 增加api导入

superset\superset\initialization_init_.py

		...
        from superset.views.users.api import UserRestApi
		...
        appbuilder.add_api(UserRestApi)

在这里插入图片描述

4. postman 测试:

参数:

{
    "username": "1213",
    "first_name": "122",
    "last_name":"last_name",
    "email":"email@qq.com",
    "role":"admin",
    "password":"sasadasd121324rd"
}

在这里插入图片描述
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/186981.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

RevCol:可逆的柱状神经网络

文章目录 摘要1、简介2、方法2.1、Multi-LeVEl ReVERsible Unit2.2、可逆列架构2.2.1、MACRo设计2.2.2、MicRo 设计 2.3、中间监督 3、实验部分3.1、图像分类3.2、目标检测3.3、语义分割3.4、与SOTA基础模型的系统级比较3.5、更多分析实验3.5.1、可逆列架构的性能提升3.5.2、可…

App Inventor 2 什么情况下需要使用字典?

介绍 字典在其他语言中称为映射、关联数组或列表&#xff0c;是一种将一个值&#xff08;通常称为键&#xff09;与另一个值关联的数据结构。 Q&#xff1a;App Inventor 2 什么情况下需要使用字典&#xff1f; A&#xff1a;列表能完成字典的绝大部分功能&#xff0c;不过字…

YOLOv8改进 | 2023 | LSKAttention大核注意力机制助力极限涨点

论文地址&#xff1a;官方论文地址 代码地址&#xff1a;官方代码地址 一、本文介绍 在这篇文章中&#xff0c;我们将讲解如何将LSKAttention大核注意力机制应用于YOLOv8&#xff0c;以实现显著的性能提升。首先&#xff0c;我们介绍LSKAttention机制的基本原理&#xff0c;…

硬盘上不小心删除了重要文档?试试这6个成功率高的数据恢复工具!

您是否不小心重新格式化了存储卡或删除了想要保留的照片&#xff1f;最好的照片恢复软件可以提供帮助&#xff01;如果您使用数码相机拍摄的时间足够长&#xff0c;那么当您错误地删除了想要保留的图像、重新格式化了错误的 SD 卡&#xff0c;或者发现您的珍贵照片由于某种莫名…

NB-IoT BC260Y Open CPU平台篇②AEP物联网平台天翼物联CWing

NB-IoT BC260Y Open CPU平台篇②AEP物联网平台天翼物联CWing 1、注册账号2、创建属于自己项目的产品3、协议解析:4、添加设备5、设备模拟测试:6、设备调试:最近做了几个项目,都是将终端产品连接到天翼物联Cwing平台和Onenet平台,个人感觉这2个平台功能还是挺全的比较好用。…

[SWPUCTF 2021 新生赛]PseudoProtocols

题目很明确了就是伪协议 php://filter/convert.base64-encode/resourcehint.php 提交的伪协议的内容需要是 I want flag&#xff0c;就会echo flag 方法1&#xff1a;adata://text/plain,I want flag 方法2&#xff1a;adata://text/plain;base64,SSB3YW50IGZsYWc

文献速递:人工智能(AI)用于神经学家:数字神经元会梦见电子羊吗?

这篇文章详细讨论了人工智能&#xff08;AI&#xff09;在神经学领域的应用及其对医疗保健行业的深远影响。主要内容可以分为以下几个部分&#xff1a; **1.AI和机器学习的基础知识&#xff1a;**文章首先解释了AI的基本概念&#xff0c;回顾了从最初的基于规则的方法到当前的…

Python潮流周刊:Twitter 的强敌 Threads 是用 Python 开发的!

&#x1f984;文章&教程 1、聊一聊 Python 和 Golang 的垃圾回收 常见的垃圾回收算法有哪些&#xff0c;它们的优缺点是什么&#xff1f;Python 的垃圾回收机制由什么组成&#xff0c;如何解决内存泄漏问题&#xff1f;Golang 的垃圾回收机制又是怎样的&#xff0c;如何解…

模块的学习

模块合包的基本概念&#xff1a; 模块&#xff08;module&#xff09;&#xff1a;在python中&#xff0c;xx.py文件&#xff0c;就可以被看作模块 包&#xff08;package&#xff09;: 用来管理和存放模块的文件夹&#xff0c;就被称为包&…

CleanMyMacX4.14.5macOS电脑系统免费清理工具

CleanMyMac X是一款专业的Mac清理软件&#xff0c;可智能清理mac磁盘垃圾和多余语言安装包&#xff0c;快速释放电脑内存&#xff0c;轻松管理和升级Mac上的应用。同时CleanMyMac X可以强力卸载恶意软件&#xff0c;修复系统漏洞&#xff0c;一键扫描和优化Mac系统&#xff0c;…

安卓开发——Android Studio常见报错与解决方法

1. No toolchains found in the NDK toolchains folder for ABI with prefix: arm-linux-android 这个错误是由于较新版本的NDK的./toolchains目录中没有arm-linux-androideabi文件&#xff0c;解决办法是从旧的NDK版本里面把相关的lib复制到要使用的NDK的版本里面&#xff0c…

ubuntu环境删除qtcreator方法

文章目录 方法1方法2方法3参考不同的安装方法,对应不同的删除方法 方法1 apt-get或者dpkg 方法2 QtCreatorUninstaller 方法3 MaintenanceTool

Clion在Windows下build时出现undefined reference,即使cmake已经正确链接第三方库(如protobuf)?

你是否正在使用clion自带的vcpkg来安装了protobuf&#xff1f; 或者你是否自己使用visual studio自己编译了libprotobuf.lib&#xff1f; 你是否已经正确在CmakeLists.txt中添加了以下命令&#xff1a; find_package(Protobuf CONFIG REQUIRED) include_directories(${Protobu…

中文地址命名实体识别训练和预测

效果 github项目地址 https://github.com/taishan1994/pytorch_bert_bilstm_crf_ner 下载项目 放在这个位置“F:\Python\github\ultralytics-main\submain\pytorch_bert_bilstm_crf_ner-main” 训练和预测步骤 1、下载数据集 从github项目可以找到数据集下载地址 https:…

个人硬件测试用例入门设计

&#x1f4d1;打牌 &#xff1a; da pai ge的个人主页 &#x1f324;️个人专栏 &#xff1a; da pai ge的博客专栏 ☁️宝剑锋从磨砺出&#xff0c;梅花香自苦寒来 &#x1f324;️功能测试 进行新增、…

yolov5从英伟达平台移植到华为昇腾开发板上的思路

作者&#xff1a;朱金灿 来源&#xff1a;clever101的专栏 为什么大多数人学不会人工智能编程&#xff1f;>>> 最近需要将yolov5代码从英伟达平台移植到华为昇腾开发板上。搜了一些代码和资料&#xff0c;大致明白了二者的差别。 1.二者使用的模型文件不一样 yolov…

葡萄酒如何按颜色进行分类?

在世界众多的葡萄酒中&#xff0c;葡萄酒的颜色受品种、产区和酿造方法影响&#xff0c;可谓多种多样&#xff0c;用万紫千红形容也不为过。为了更好辨识&#xff0c;一般葡萄酒根据不同颜色&#xff0c;分为三个大类即&#xff1a;红葡萄酒、白葡萄酒、桃红葡萄酒。 红葡萄酒…

表单考勤签到作业周期打卡打分评价评分小程序开源版开发

表单考勤签到作业周期打卡打分评价评分小程序开源版开发 表单打卡评分 表单签到功能&#xff1a;学生可以通过扫描二维码或输入签到码进行签到&#xff0c;方便教师进行考勤管理。 考勤功能&#xff1a;可以记录学生的出勤情况&#xff0c;并自动生成出勤率和缺勤次数等统计数…

五种多目标优化算法(NSDBO、NSGA3、MOGWO、NSWOA、MOPSO)求解微电网多目标优化调度(MATLAB代码)

一、多目标优化算法简介 &#xff08;1&#xff09;非支配排序的蜣螂优化算法NSDBO 多目标应用&#xff1a;基于非支配排序的蜣螂优化算法NSDBO求解微电网多目标优化调度&#xff08;MATLAB&#xff09;-CSDN博客 &#xff08;2&#xff09;NSGA3 NSGA-III求解微电网多目标…

两年功能五年自动化测试面试经验分享

最近有机会做一些面试工作&#xff0c;主要负责面试软件测试人员招聘的技术面试。 之前一直是应聘者的角色&#xff0c;经历了不少次的面试之后&#xff0c;多少也积累一点面试的经验&#xff0c;现在发生了角色转变。初次的面试就碰到个工作年限比我长的&#xff0c;也没有时…