跳至主要內容
在 GitHub 上編輯此頁面

設定 Superset

superset_config.py

Superset 透過其 config.py 模組公開了數百個可配置的參數。公開的變數和物件作為您可能想要設定、變更和介面的大部分的公共介面。在此 Python 模組中,您會找到所有這些參數、合理的預設值,以及以註解形式呈現的豐富文件。

若要設定您的應用程式,您需要建立自己的組態模組,以便您覆寫這些參數中的少數或多數。您需要定義自己的模組(通常是一個名為 superset_config.py 的檔案),而不是變更核心模組。將此檔案新增至您的 PYTHONPATH,或建立一個環境變數 SUPERSET_CONFIG_PATH,指定 superset_config.py 的完整路徑。

例如,如果直接在以 Linux 為基礎的系統上部署 Superset,而您的 superset_config.py 位於 /app 目錄下,則可以執行

export SUPERSET_CONFIG_PATH=/app/superset_config.py

如果您使用自己的自訂 Dockerfile,並以官方 Superset 映像檔作為基礎映像檔,則可以如下所示新增您的覆寫

COPY --chown=superset superset_config.py /app/
ENV SUPERSET_CONFIG_PATH /app/superset_config.py

Docker Compose 部署使用特定的慣例以不同的方式處理應用程式組態。請參閱Docker Compose 提示與組態以取得詳細資訊。

以下是一個範例,僅示範您可以在 superset_config.py 檔案中設定的幾個參數

# Superset specific config
ROW_LIMIT = 5000

# Flask App Builder configuration
# Your App secret key will be used for securely signing the session cookie
# and encrypting sensitive information on the database
# Make sure you are changing this key for your deployment with a strong key.
# Alternatively you can set it with `SUPERSET_SECRET_KEY` environment variable.
# You MUST set this for production environments or the server will refuse
# to start and you will see an error in the logs accordingly.
SECRET_KEY = 'YOUR_OWN_RANDOM_GENERATED_SECRET_KEY'

# The SQLAlchemy connection string to your database backend
# This connection defines the path to the database that stores your
# superset metadata (slices, connections, tables, dashboards, ...).
# Note that the connection information to connect to the datasources
# you want to explore are managed directly in the web UI
# The check_same_thread=false property ensures the sqlite client does not attempt
# to enforce single-threaded access, which may be problematic in some edge cases
SQLALCHEMY_DATABASE_URI = 'sqlite:////path/to/superset.db?check_same_thread=false'

# Flask-WTF flag for CSRF
WTF_CSRF_ENABLED = True
# Add endpoints that need to be exempt from CSRF protection
WTF_CSRF_EXEMPT_LIST = []
# A CSRF token that expires in 1 year
WTF_CSRF_TIME_LIMIT = 60 * 60 * 24 * 365

# Set this API key to enable Mapbox visualizations
MAPBOX_API_KEY = ''
提示

請注意,通常會將您想要變更的核心 superset/config.py 的部分 [僅] 與相關註解複製並貼到您自己的 superset_config.py 檔案中。

您可以在您的本機 superset_config.py 中變更 superset/config.py 中定義的所有參數和預設值。管理員會想要詳閱該檔案,以了解可以在本機設定的內容以及現有的預設值。

由於 superset_config.py 作為 Flask 組態模組,因此可以用來變更 Flask 本身的設定,以及 Superset 捆綁的 Flask 擴充功能,例如 flask-wtfflask-cachingflask-migrateflask-appbuilder。這些擴充功能中的每一個都提供了複雜的設定能力。Superset 使用的 Web 框架 Flask App Builder 也提供了許多組態設定。請參閱Flask App Builder 文件,以取得有關如何設定它的詳細資訊。

至少,您會想要變更 SECRET_KEYSQLALCHEMY_DATABASE_URI。請繼續閱讀以了解有關這些的詳細資訊。

指定 SECRET_KEY

新增初始 SECRET_KEY

Superset 需要使用者指定的 SECRET_KEY 才能啟動。此要求已在2.1.0 版本中新增,以強制執行安全設定。在您的 superset_config.py 檔案中新增強式 SECRET_KEY,例如

SECRET_KEY = 'YOUR_OWN_RANDOM_GENERATED_SECRET_KEY'

您可以使用 openssl rand -base64 42 產生強式的安全金鑰。

使用強式密鑰

此金鑰將用於安全地簽署工作階段 Cookie 和加密儲存在 Superset 應用程式中繼資料資料庫中的敏感資訊。您的部署必須使用複雜且獨特的金鑰。

輪換至較新的 SECRET_KEY

如果您想要變更現有的 SECRET_KEY,請將現有的 SECRET_KEY 新增至您的 superset_config.py 檔案,作為 PREVIOUS_SECRET_KEY = ,並將您的新金鑰提供為 SECRET_KEY =。您可以使用以下命令找到您目前的 SECRET_KEY - 如果使用 Docker 執行 Superset,請從 Superset 應用程式容器內執行

superset shell
from flask import current_app; print(current_app.config["SECRET_KEY"])

使用這些值儲存您的 superset_config.py,然後執行 superset re-encrypt-secrets

設定生產中繼資料資料庫

Superset 需要資料庫來儲存它所管理的資訊,例如圖表、儀表板和許多其他項目的定義。

依預設,Superset 設定為使用 SQLite,這是一個獨立的單一檔案資料庫,提供簡單快速的入門方式(無需任何安裝)。但是,由於安全性、可擴充性和資料完整性的考量,強烈建議不要在生產環境中使用 SQLite。務必僅使用支援的資料庫引擎,並考慮在不同的主機或容器上使用不同的資料庫引擎。

Superset 支援下列資料庫引擎/版本

資料庫引擎支援的版本
PostgreSQL10.X、11.X、12.X、13.X、14.X、15.X
MySQL5.7、8.X

使用下列資料庫驅動程式和連線字串

資料庫PyPI 套件連線字串
PostgreSQLpip install psycopg2postgresql://<UserName>:<DBPassword>@<Database Host>/<Database Name>
MySQLpip install mysqlclientmysql://<UserName>:<DBPassword>@<Database Host>/<Database Name>
提示

正確設定中繼資料存放區不在本文件涵蓋範圍內。我們建議使用託管的受管理服務,例如 Amazon RDSGoogle Cloud Databases,以處理服務和支援基礎結構以及備份策略。

若要設定 Superset 中繼資料存放區,請將 superset_config 上的 SQLALCHEMY_DATABASE_URI 組態金鑰設定為適當的連線字串。

在 WSGI HTTP 伺服器上執行

雖然您可以在 NGINX 或 Apache 上執行 Superset,但我們建議以非同步模式使用 Gunicorn。這可以實現令人印象深刻的並行性,而且安裝和設定相當容易。請參閱您偏好的技術的文件,以在您的環境中以運作良好的方式設定此 Flask WSGI 應用程式。以下是一個已知在生產環境中運作良好的非同步設定

      -w 10 \
-k gevent \
--worker-connections 1000 \
--timeout 120 \
-b 0.0.0.0:6666 \
--limit-request-line 0 \
--limit-request-field_size 0 \
--statsd-host localhost:8125 \
"superset.app:create_app()"

如需詳細資訊,請參閱Gunicorn 文件請注意,開發 Web 伺服器 (superset runflask run) 不適用於生產環境。

如果您未使用 Gunicorn,您可能會想要在 superset_config.py 中將 COMPRESS_REGISTER = False 來停用 flask-compress 的使用。

目前,Google BigQuery Python SDK 與 gevent 不相容,這是因為 gevent 在 Python 核心程式庫上進行了一些動態修補。因此,當您在 Superset 上使用 BigQuery 資料來源時,您必須使用 gunicorn 工作者類型,而不是 gevent

HTTPS 設定

您可以透過負載平衡器或反向 Proxy(例如 Nginx)設定上游 HTTPS,並在流量到達 Superset 應用程式之前執行 SSL/TLS Offloading。在此設定中,從 Celery 工作者擷取圖表快照以用於警示與報表的本機流量,可以從進入點後方存取 http:// URL 上的 Superset。如果您使用官方 Superset Docker 映像檔,也可以在 Gunicorn(Python Web 伺服器)中設定 SSL。

負載平衡器後方的設定

如果您在負載平衡器或反向 Proxy(例如 AWS 上的 NGINX 或 ELB)後方執行 Superset,您可能需要使用運作狀態檢查端點,讓您的負載平衡器知道您的 Superset 執行個體是否正在執行。這在 /health 提供,如果 Web 伺服器正在執行,則會傳回包含「OK」的 200 回應。

如果負載平衡器正在插入 X-Forwarded-For/X-Forwarded-Proto 標頭,您應該在 Superset 設定檔 (superset_config.py) 中設定 ENABLE_PROXY_FIX = True,以擷取並使用標頭。

如果反向 Proxy 用於提供 SSL 加密,則可能需要明確定義 X-Forwarded-Proto。對於 Apache Web 伺服器,可以如下設定

RequestHeader set X-Forwarded-Proto "https"

自訂 OAuth2 設定

Superset 建構於 Flask-AppBuilder (FAB) 之上,它開箱即支援許多供應商 (GitHub、Twitter、LinkedIn、Google、Azure 等)。除此之外,Superset 還可以設定為與其他支援「code」授權的 OAuth2 授權伺服器實作連接。

請確保在網頁伺服器上已安裝 pip 套件 Authlib

首先,在 Superset 的 superset_config.py 中設定授權。

from flask_appbuilder.security.manager import AUTH_OAUTH

# Set the authentication type to OAuth
AUTH_TYPE = AUTH_OAUTH

OAUTH_PROVIDERS = [
{ 'name':'egaSSO',
'token_key':'access_token', # Name of the token in the response of access_token_url
'icon':'fa-address-card', # Icon for the provider
'remote_app': {
'client_id':'myClientId', # Client Id (Identify Superset application)
'client_secret':'MySecret', # Secret for this Client Id (Identify Superset application)
'client_kwargs':{
'scope': 'read' # Scope for the Authorization
},
'access_token_method':'POST', # HTTP Method to call access_token_url
'access_token_params':{ # Additional parameters for calls to access_token_url
'client_id':'myClientId'
},
'jwks_uri':'https://myAuthorizationServe/adfs/discovery/keys', # may be required to generate token
'access_token_headers':{ # Additional headers for calls to access_token_url
'Authorization': 'Basic Base64EncodedClientIdAndSecret'
},
'api_base_url':'https://myAuthorizationServer/oauth2AuthorizationServer/',
'access_token_url':'https://myAuthorizationServer/oauth2AuthorizationServer/token',
'authorize_url':'https://myAuthorizationServer/oauth2AuthorizationServer/authorize'
}
}
]

# Will allow user self registration, allowing to create Flask users from Authorized User
AUTH_USER_REGISTRATION = True

# The default user self registration role
AUTH_USER_REGISTRATION_ROLE = "Public"

然後,建立一個 CustomSsoSecurityManager,它繼承 SupersetSecurityManager 並覆寫 oauth_user_info

import logging
from superset.security import SupersetSecurityManager

class CustomSsoSecurityManager(SupersetSecurityManager):

def oauth_user_info(self, provider, response=None):
logging.debug("Oauth2 provider: {0}.".format(provider))
if provider == 'egaSSO':
# As example, this line request a GET to base_url + '/' + userDetails with Bearer Authentication,
# and expects that authorization server checks the token, and response with user details
me = self.appbuilder.sm.oauth_remotes[provider].get('userDetails').data
logging.debug("user_data: {0}".format(me))
return { 'name' : me['name'], 'email' : me['email'], 'id' : me['user_name'], 'username' : me['user_name'], 'first_name':'', 'last_name':''}
...

這個檔案必須與 superset_config.py 位於同一個目錄下,並且命名為 custom_sso_security_manager.py。最後,將以下兩行程式碼加入 superset_config.py

from custom_sso_security_manager import CustomSsoSecurityManager
CUSTOM_SECURITY_MANAGER = CustomSsoSecurityManager

注意事項

  • 重新導向 URL 將會是 https://<superset-webserver>/oauth-authorized/<provider-name>,在需要時設定 OAuth2 授權供應商。例如,對於上述設定,重新導向 URL 將會是 https://<superset-webserver>/oauth-authorized/egaSSO

  • 如果 OAuth2 授權伺服器支援 OpenID Connect 1.0,您可以只設定其設定文件 URL,而無需提供 api_base_urlaccess_token_urlauthorize_url 和其他所需的選項,例如使用者資訊端點、jwks uri 等。例如:

    OAUTH_PROVIDERS = [
    { 'name':'egaSSO',
    'token_key':'access_token', # Name of the token in the response of access_token_url
    'icon':'fa-address-card', # Icon for the provider
    'remote_app': {
    'client_id':'myClientId', # Client Id (Identify Superset application)
    'client_secret':'MySecret', # Secret for this Client Id (Identify Superset application)
    'server_metadata_url': 'https://myAuthorizationServer/.well-known/openid-configuration'
    }
    }
    ]

使用 Flask-OIDC 的 Keycloak 特定設定

如果您使用 Keycloak 作為 OpenID Connect 1.0 提供者,上述基於 Authlib 的設定可能無法運作。在這種情況下,使用 Flask-OIDC 是一個可行的選項。

請確保在網頁伺服器上已安裝 pip 套件 Flask-OIDC。已成功使用 2.2.0 版本進行測試。這個套件需要 Flask-OpenID 作為相依性套件。

以下程式碼定義了一個新的安全性管理器。將它加入一個名為 keycloak_security_manager.py 的新檔案中,該檔案與您的 superset_config.py 檔案放在同一個目錄下。

from flask_appbuilder.security.manager import AUTH_OID
from superset.security import SupersetSecurityManager
from flask_oidc import OpenIDConnect
from flask_appbuilder.security.views import AuthOIDView
from flask_login import login_user
from urllib.parse import quote
from flask_appbuilder.views import ModelView, SimpleFormView, expose
from flask import (
redirect,
request
)
import logging

class OIDCSecurityManager(SupersetSecurityManager):

def __init__(self, appbuilder):
super(OIDCSecurityManager, self).__init__(appbuilder)
if self.auth_type == AUTH_OID:
self.oid = OpenIDConnect(self.appbuilder.get_app)
self.authoidview = AuthOIDCView

class AuthOIDCView(AuthOIDView):

@expose('/login/', methods=['GET', 'POST'])
def login(self, flag=True):
sm = self.appbuilder.sm
oidc = sm.oid

@self.appbuilder.sm.oid.require_login
def handle_login():
user = sm.auth_user_oid(oidc.user_getfield('email'))

if user is None:
info = oidc.user_getinfo(['preferred_username', 'given_name', 'family_name', 'email'])
user = sm.add_user(info.get('preferred_username'), info.get('given_name'), info.get('family_name'),
info.get('email'), sm.find_role('Gamma'))

login_user(user, remember=False)
return redirect(self.appbuilder.get_url_for_index)

return handle_login()

@expose('/logout/', methods=['GET', 'POST'])
def logout(self):
oidc = self.appbuilder.sm.oid

oidc.logout()
super(AuthOIDCView, self).logout()
redirect_url = request.url_root.strip('/') + self.appbuilder.get_url_for_login

return redirect(
oidc.client_secrets.get('issuer') + '/protocol/openid-connect/logout?redirect_uri=' + quote(redirect_url))

然後將以下程式碼加入您的 superset_config.py 檔案。

from keycloak_security_manager import OIDCSecurityManager
from flask_appbuilder.security.manager import AUTH_OID, AUTH_REMOTE_USER, AUTH_DB, AUTH_LDAP, AUTH_OAUTH
import os

AUTH_TYPE = AUTH_OID
SECRET_KEY: 'SomethingNotEntirelySecret'
OIDC_CLIENT_SECRETS = '/path/to/client_secret.json'
OIDC_ID_TOKEN_COOKIE_SECURE = False
OIDC_OPENID_REALM: '<myRealm>'
OIDC_INTROSPECTION_AUTH_METHOD: 'client_secret_post'
CUSTOM_SECURITY_MANAGER = OIDCSecurityManager

# Will allow user self registration, allowing to create Flask users from Authorized User
AUTH_USER_REGISTRATION = True

# The default user self registration role
AUTH_USER_REGISTRATION_ROLE = 'Public'

將您的用戶端特定的 OpenID 資訊儲存在一個名為 client_secret.json 的檔案中。在與 superset_config.py 相同的目錄下建立此檔案。

{
"<myOpenIDProvider>": {
"issuer": "https://<myKeycloakDomain>/realms/<myRealm>",
"auth_uri": "https://<myKeycloakDomain>/realms/<myRealm>/protocol/openid-connect/auth",
"client_id": "https://<myKeycloakDomain>",
"client_secret": "<myClientSecret>",
"redirect_uris": [
"https://<SupersetWebserver>/oauth-authorized/<myOpenIDProvider>"
],
"userinfo_uri": "https://<myKeycloakDomain>/realms/<myRealm>/protocol/openid-connect/userinfo",
"token_uri": "https://<myKeycloakDomain>/realms/<myRealm>/protocol/openid-connect/token",
"token_introspection_uri": "https://<myKeycloakDomain>/realms/<myRealm>/protocol/openid-connect/token/introspect"
}
}

LDAP 驗證

FAB 支援針對 LDAP 伺服器驗證使用者憑證。若要使用 LDAP,您必須安裝 python-ldap 套件。詳細資訊請參閱 FAB 的 LDAP 文件

將 LDAP 或 OAUTH 群組對應到 Superset 角色

Flask-AppBuilder 中的 AUTH_ROLES_MAPPING 是一個字典,它將 LDAP/OAUTH 群組名稱對應到 FAB 角色。它用於將角色指派給使用 LDAP 或 OAuth 驗證的使用者。

將 OAUTH 群組對應到 Superset 角色

以下 AUTH_ROLES_MAPPING 字典會將 OAUTH 群組 "superset_users" 對應到 Superset 角色 "Gamma" 和 "Alpha",並將 OAUTH 群組 "superset_admins" 對應到 Superset 角色 "Admin"。

AUTH_ROLES_MAPPING = {
"superset_users": ["Gamma","Alpha"],
"superset_admins": ["Admin"],
}

將 LDAP 群組對應到 Superset 角色

以下 AUTH_ROLES_MAPPING 字典會將 LDAP DN "cn=superset_users,ou=groups,dc=example,dc=com" 對應到 Superset 角色 "Gamma" 和 "Alpha",並將 LDAP DN "cn=superset_admins,ou=groups,dc=example,dc=com" 對應到 Superset 角色 "Admin"。

AUTH_ROLES_MAPPING = {
"cn=superset_users,ou=groups,dc=example,dc=com": ["Gamma","Alpha"],
"cn=superset_admins,ou=groups,dc=example,dc=com": ["Admin"],
}

注意:這需要設定 AUTH_LDAP_SEARCH。有關詳細資訊,請參閱 FAB 安全性文件

登入時同步角色

您也可以使用 AUTH_ROLES_SYNC_AT_LOGIN 組態變數來控制 Flask-AppBuilder 將使用者角色與 LDAP/OAUTH 群組同步的頻率。如果 AUTH_ROLES_SYNC_AT_LOGIN 設定為 True,Flask-AppBuilder 將在使用者每次登入時同步其角色。如果 AUTH_ROLES_SYNC_AT_LOGIN 設定為 False,Flask-AppBuilder 只會在使用者首次註冊時同步其角色。

Flask 應用程式組態掛鉤

FLASK_APP_MUTATOR 是一個組態函式,可以在您的環境中提供,它會接收應用程式物件並可以以任何方式更改它。例如,將 FLASK_APP_MUTATOR 加入您的 superset_config.py,將會話 Cookie 過期時間設定為 24 小時。

from flask import session
from flask import Flask


def make_session_permanent():
'''
Enable maxAge for the cookie 'session'
'''
session.permanent = True

# Set up max age of session to 24 hours
PERMANENT_SESSION_LIFETIME = timedelta(hours=24)
def FLASK_APP_MUTATOR(app: Flask) -> None:
app.before_request_funcs.setdefault(None, []).append(make_session_permanent)

功能旗標

為了支援不同的使用者群體,Superset 有一些預設不啟用的功能。例如,某些使用者有較強的安全性限制,而某些使用者可能沒有。因此,Superset 允許使用者通過組態啟用或停用某些功能。對於功能擁有者,您可以在 Superset 中新增可選功能,但只會影響一部分使用者。

您可以使用 superset_config.py 中的旗標啟用或停用功能。

FEATURE_FLAGS = {
'PRESTO_EXPAND_DATA': False,
}

目前的功能旗標列表可以在 RESOURCES/FEATURE_FLAGS.md 中找到。