superset详解(六)--添加/编辑表

本文详细介绍了在Superset平台上添加和编辑表的过程。在添加表时,通过TableModelView的post_add()函数自动获取表的基本信息并展示其列和指标。编辑表后,将直接跳转至数据查询页面,简化配置流程。

添加表

我们在superset上添加表之后,表的列和指标就自动展示出来了,这个主要是在tablemodelview的post_add()函数中做的操作。

class TableModelView(DatasourceModelView, DeleteMixin, YamlExportMixin):  # noqa
    datamodel = SQLAInterface(models.SqlaTable)
    pass
   
   def post_add(self, table, flash_message=True):
	    table.fetch_metadata()             # 主要是这个函数获取表的基本信息
	    security_manager.merge_perm('datasource_access', table.get_perm())
	    if table.schema:
	        security_manager.merge_perm('schema_access', table.schema_perm)
	
	    if flash_message:
	        flash(_(
	            'The table was created. '
	            'As part of this two phase configuration '
	            'process, you should now click the edit button by '
	            'the new table to configure it.'), 'info')

    def fetch_metadata(self):
        """Fetches the metadata for the table and merges it in"""
        try:
            table = self.get_sqla_table_object()
        except Exception:
            raise Exception(_(
                "Table [{}] doesn't seem to exist in the specified database, "
                "couldn't fetch column information").format(self.table_name))

        M = SqlMetric  # noqa
        metrics = []
        any_date_col = None
        db_dialect = self.database.get_dialect()
        #获取mysql的comment信息
        comment_info_dict=self.init_table(table)
        dbcols = (
            db.session.query(TableColumn)
            .filter(TableColumn.table == self)
            .filter(or_(TableColumn.column_name == col.name
                        for col in table.columns)))
        dbcols = {dbcol.column_name: dbcol for dbcol in dbcols}
        count=0
        for col in table.columns:
            try:
                datatype = col.type.compile(dialect=db_dialect).upper()
            except Exception as e:
                datatype = 'UNKNOWN'
                logging.error(
                    'Unrecognized data type in {}.{}'.format(table, col.name))
                logging.exception(e)
            dbcol = dbcols.get(col.name, None)
            if not dbcol:
                dbcol = TableColumn(column_name=col.name, type=datatype)
                dbcol.groupby = dbcol.is_string
                dbcol.filterable = dbcol.is_string
                dbcol.sum = dbcol.is_num
                #dbcol.avg = dbcol.is_num
                dbcol.is_dttm = dbcol.is_time
                dbcol.order_number=count*100
                count+=1
                if comment_info_dict:
                    dbcol.verbose_name=comment_info_dict[dbcol.column_name]
            else:
                dbcol.type = datatype
            self.columns.append(dbcol)
            if not any_date_col and dbcol.is_time:
                any_date_col = col.name
            metrics += dbcol.get_metrics().values()

        metrics.append(M(
            metric_name='count',
            verbose_name='COUNT(*)',
            metric_type='count',
            expression='COUNT(*)',
        ))
        if not self.main_dttm_col:
            self.main_dttm_col = any_date_col
        self.add_missing_metrics(metrics)
        db.session.merge(self)
        db.session.commit()

如果表的信息更新了,可以使用Refresh Metadata 来更新表的内容。

编辑表

编辑表之后在页面跳转到数据查询页面

@expose('/edit/<pk>', methods=['GET', 'POST'])
@has_access
 def edit(self, pk):
     """Simple hack to redirect to explore view after saving"""
     resp = super(TableModelView, self).edit(pk)
     if isinstance(resp, basestring):
         return resp
     return redirect('/superset/explore/table/{}/'.format(pk))   # 页面跳转

(venv) gapinyc@DESKTOP-9QS7RL5:~/superset$ tsql -H 192.168.110.219 -p 1433 -U sa -P 'sasa' locale is "C.UTF-8" locale charset is "UTF-8" using default charset "UTF-8" 1> SELECT SYSTEM_USER, DB_NAME() go 2> go sa master (1 row affected) (venv) gapinyc@DESKTOP-9QS7RL5:~/superset$ curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg sudo mv microsoft.gpg /etc/apt/trusted.gpg.d/microsoft.gpg % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 975 100 975 0 0 2653 0 --:--:-- --:--:-- --:--:-- 2656 (venv) gapinyc@DESKTOP-9QS7RL5:~/superset$ curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg sudo mv microsoft.gpg /etc/apt/trusted.gpg.d/microsoft.gpg % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 975 100 975 0 0 1381 0 --:--:-- --:--:-- --:--:-- 1381 (venv) gapinyc@DESKTOP-9QS7RL5:~/superset$ pip install pyodbc Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple/ Requirement already satisfied: pyodbc in ./venv/lib/python3.10/site-packages (5.3.0) (venv) gapinyc@DESKTOP-9QS7RL5:~/superset$ python test_pyodbc.py python: can't open file '/home/gapinyc/superset/test_pyodbc.py': [Errno 2] No such file or directory (venv) gapinyc@DESKTOP-9QS7RL5:~/superset$ python test_pyodbc.py ❌ 连接失败: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]SSL Provider: [error:0A000102:SSL routines::unsupported protocol] (-1) (SQLDriverConnect)') (venv) gapinyc@DESKTOP-9QS7RL5:~/superset$
最新发布
11-06
你遇到了一个常见的 `npm install` 错误: ``` npm error ENOTEMPTY: directory not empty, rename ... -> '/home/gapinyc/superset-prod/superset-5.0.0/superset-frontend/packages/superset-ui-core/node_modules/.d3-scale-qbNTvgZE' ``` 这是 **npm 在重命名目录时失败**,因为目标路径已被占用或系统锁定了文件。这在使用 **lerna/yarn workspace 类型的单体仓库(monorepo)** 项目(如 Superset)中非常常见。 --- ## 🔍 错误原因分析 Superset 使用了 **多包结构(monorepo)**,即: - `/packages/superset-ui-core` - `/packages/superset-ui-connection` - 等等 这些子包有自己的 `node_modules`,而 `npm install` 在根目录运行时会尝试链接依赖、移动文件夹,但在某些情况下: > ❌ `npm` 想把 `d3-scale` 临时重命名为 `.d3-scale-xxx` 来更新它,但原目录非空或被占用 → 报 `ENOTEMPTY` 常见于: - 文件正在被使用(如编辑器打开) - 杀毒软件/WSL 文件系统延迟 - 并发操作冲突 --- ## ✅ 解决方案:彻底清理 + 强制安装 ### ✅ 步骤 1:确保没有进程占用文件 关闭所有可能访问该项目的程序: - VS Code、WebStorm 等编辑- 终端标签页(尤其是仍在该目录下的) - Git GUI 工具 然后重新进入目录: ```bash cd ~/superset-prod/superset-5.0.0/superset-frontend ``` --- ### ✅ 步骤 2:强制删除所有 `node_modules`(包括嵌套的) 你之前只删了根目录的 `node_modules`,但没删 `/packages/...` 下的! 执行递归删除: ```bash # 删除根目录和所有 packages 下的 node_modules find . -name "node_modules" -type d -prune -exec rm -rf '{}' + ``` ✅ 这会删除: - `./node_modules` - `./packages/superset-ui-core/node_modules` - `./packages/superset-ui-demo/node_modules` - 所有插件下的 `node_modules` 同时删除锁文件: ```bash rm -f package-lock.json find . -name "package-lock.json" -type f -delete ``` --- ### ✅ 步骤 3:设置淘宝镜像(已做,确认即可) ```bash npm config set registry https://registry.npmmirror.com npm config get registry # 应输出: https://registry.npmmirror.com/ ``` --- ### ✅ 步骤 4:重新运行 `npm install` ```bash npm install ``` ⏳ 耐心等待(可能需要 10~20 分钟),不要中断。 --- ### ✅ 步骤 5:验证是否成功 安装完成后检查: ```bash ls node_modules/cross-env/bin/cross-env.js ``` ✅ 如果存在,则说明依赖安装成功。 再检查子模块是否正常: ```bash ls packages/superset-ui-core/node_modules/d3-scale/package.json ``` 也应该存在。 --- ## 🛠️ 额外建议(避免再次出错) ### 🔧 1. 使用 `npm ci` 替代 `npm install`(推荐用于构建环境) 如果你有完整的 `package-lock.json`,可以用: ```bash npm ci ``` 它比 `npm install` 更严格、更快、更可靠,适合 CI/CD 和生产构建。 > ⚠️ 注意:`npm ci` 要求 `package-lock.json` 存在且与 `package.json` 匹配。 所以先确保锁文件重建: ```bash npm install --package-lock-only # 先生成 lock 文件 npm ci # 再用 ci 安装 ``` --- ### 🔧 2. 推荐改用 `yarn` 构建 Superset(官方更支持) Apache Superset 官方推荐使用 `yarn` 而不是 `npm`,因为它是基于 **Yarn Workspaces** 的 monorepo 结构。 #### ✅ 切换到 yarn 的方法: ```bash # 1. 安装 yarn npm install -g yarn # 2. 回到 superset 根目录(不是 frontend!) cd ~/superset-prod/superset-5.0.0 # 3. 清理 npm 状态 rm -rf node_modules yarn.lock find . -name "node_modules" -type d -prune -exec rm -rf '{}' + # 4. 使用 yarn 安装(自动识别 yarn.lock) yarn install ``` ✅ `yarn` 对 monorepo 支持更好,基本不会出现 `ENOTEMPTY` 问题。 然后进前端目录构建: ```bash cd superset-frontend yarn build ``` 或者直接: ```bash yarn build # 在根目录运行(如果脚本已定义) ``` --- ## ✅ 总结:你现在应该执行的命令序列 ```bash # 1. 回到项目根目录(superset-frontend) cd ~/superset-prod/superset-5.0.0/superset-frontend # 2. 关闭编辑器等占用程序 # 3. 彻底清除所有 node_modules 和 lock 文件 find . -name "node_modules" -type d -prune -exec rm -rf '{}' + rm -f package-lock.json find . -name "package-lock.json" -type f -delete # 4. 设置镜像 npm config set registry https://registry.npmmirror.com # 5. 重新安装 npm install ``` 如果仍然失败 → **强烈建议切换为 `yarn`** ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值