INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Decorator to log user actions
def log_this(cls, f): """Decorator to log user actions""" @functools.wraps(f) def wrapper(*args, **kwargs): user_id = None if g.user: user_id = g.user.get_id() d = request.form.to_dict() or {} # request parameters can overwrite pos...
A decorator to label an endpoint as an API. Catches uncaught exceptions and return the response in the JSON format
def api(f): """ A decorator to label an endpoint as an API. Catches uncaught exceptions and return the response in the JSON format """ def wraps(self, *args, **kwargs): try: return f(self, *args, **kwargs) except Exception as e: logging.exception(e) ...
A decorator to catch superset exceptions. Use it after the @api decorator above so superset exception handler is triggered before the handler for generic exceptions.
def handle_api_exception(f): """ A decorator to catch superset exceptions. Use it after the @api decorator above so superset exception handler is triggered before the handler for generic exceptions. """ def wraps(self, *args, **kwargs): try: return f(self, *args, **kwargs) ...
Meant to be used in `pre_update` hooks on models to enforce ownership Admin have all access, and other users need to be referenced on either the created_by field that comes with the ``AuditMixin``, or in a field named ``owners`` which is expected to be a one-to-many with the User model. It is meant to ...
def check_ownership(obj, raise_if_false=True): """Meant to be used in `pre_update` hooks on models to enforce ownership Admin have all access, and other users need to be referenced on either the created_by field that comes with the ``AuditMixin``, or in a field named ``owners`` which is expected to be ...
Customize how fields are bound by stripping all whitespace. :param form: The form :param unbound_field: The unbound field :param options: The field options :returns: The bound field
def bind_field( self, form: DynamicForm, unbound_field: UnboundField, options: Dict[Any, Any], ) -> Field: """ Customize how fields are bound by stripping all whitespace. :param form: The form :param unbound_field: The unbound field :param options: The field opti...
Common data always sent to the client
def common_bootsrap_payload(self): """Common data always sent to the client""" messages = get_flashed_messages(with_categories=True) locale = str(get_locale()) return { 'flash_messages': messages, 'conf': {k: conf.get(k) for k in FRONTEND_CONF_KEYS}, '...
Delete function logic, override to implement diferent logic deletes the record with primary_key = pk :param pk: record primary key to delete
def _delete(self, pk): """ Delete function logic, override to implement diferent logic deletes the record with primary_key = pk :param pk: record primary key to delete """ item = self.datamodel.get(pk, self._base_filters) if not item: ...
Returns a set of tuples with the perm name and view menu name
def get_all_permissions(self): """Returns a set of tuples with the perm name and view menu name""" perms = set() for role in self.get_user_roles(): for perm_view in role.permissions: t = (perm_view.permission.name, perm_view.view_menu.name) perms.add(t...
Returns the details of view_menus for a perm name
def get_view_menus(self, permission_name): """Returns the details of view_menus for a perm name""" vm = set() for perm_name, vm_name in self.get_all_permissions(): if perm_name == permission_name: vm.add(vm_name) return vm
Destroy a driver
def destroy_webdriver(driver): """ Destroy a driver """ # This is some very flaky code in selenium. Hence the retries # and catch-all exceptions try: retry_call(driver.close, tries=2) except Exception: pass try: driver.quit() except Exception: pass
Given a schedule, delivery the dashboard as an email report
def deliver_dashboard(schedule): """ Given a schedule, delivery the dashboard as an email report """ dashboard = schedule.dashboard dashboard_url = _get_url_path( 'Superset.dashboard', dashboard_id=dashboard.id, ) # Create a driver, fetch the page, wait for the page to rend...
Given a schedule, delivery the slice as an email report
def deliver_slice(schedule): """ Given a schedule, delivery the slice as an email report """ if schedule.email_format == SliceEmailReportFormat.data: email = _get_slice_data(schedule) elif schedule.email_format == SliceEmailReportFormat.visualization: email = _get_slice_visualization...
Find all active schedules and schedule celery tasks for each of them with a specific ETA (determined by parsing the cron schedule for the schedule)
def schedule_window(report_type, start_at, stop_at, resolution): """ Find all active schedules and schedule celery tasks for each of them with a specific ETA (determined by parsing the cron schedule for the schedule) """ model_cls = get_scheduler_model(report_type) dbsession = db.create_scop...
Celery beat job meant to be invoked hourly
def schedule_hourly(): """ Celery beat job meant to be invoked hourly """ if not config.get('ENABLE_SCHEDULED_EMAIL_REPORTS'): logging.info('Scheduled email reports not enabled in config') return resolution = config.get('EMAIL_REPORTS_CRON_RESOLUTION', 0) * 60 # Get the top of the hou...
De-duplicates a list of string by suffixing a counter Always returns the same number of entries as provided, and always returns unique values. Case sensitive comparison by default. >>> print(','.join(dedup(['foo', 'bar', 'bar', 'bar', 'Bar']))) foo,bar,bar__1,bar__2,Bar >>> print(','.join(dedup(['...
def dedup(l, suffix='__', case_sensitive=True): """De-duplicates a list of string by suffixing a counter Always returns the same number of entries as provided, and always returns unique values. Case sensitive comparison by default. >>> print(','.join(dedup(['foo', 'bar', 'bar', 'bar', 'Bar']))) fo...
Given a numpy dtype, Returns a generic database type
def db_type(cls, dtype): """Given a numpy dtype, Returns a generic database type""" if isinstance(dtype, ExtensionDtype): return cls.type_map.get(dtype.kind) elif hasattr(dtype, 'char'): return cls.type_map.get(dtype.char)
Provides metadata about columns for data visualization. :return: dict, with the fields name, type, is_date, is_dim and agg.
def columns(self): """Provides metadata about columns for data visualization. :return: dict, with the fields name, type, is_date, is_dim and agg. """ if self.df.empty: return None columns = [] sample_size = min(INFER_COL_TYPES_SAMPLE_SIZE, len(self.df.index)...
Getting the time component of the query
def get_timestamp_expression(self, time_grain): """Getting the time component of the query""" label = utils.DTTM_ALIAS db = self.table.database pdf = self.python_date_format is_epoch = pdf in ('epoch_s', 'epoch_ms') if not self.expression and not time_grain and not is_ep...
Convert datetime object to a SQL expression string If database_expression is empty, the internal dttm will be parsed as the string with the pattern that the user inputted (python_date_format) If database_expression is not empty, the internal dttm will be parsed as the sql senten...
def dttm_sql_literal(self, dttm, is_epoch_in_utc): """Convert datetime object to a SQL expression string If database_expression is empty, the internal dttm will be parsed as the string with the pattern that the user inputted (python_date_format) If database_expression is not emp...
Takes a sql alchemy column object and adds label info if supported by engine. :param sqla_col: sql alchemy column instance :param label: alias/label that column is expected to have :return: either a sql alchemy column or label instance if supported by engine
def make_sqla_column_compatible(self, sqla_col, label=None): """Takes a sql alchemy column object and adds label info if supported by engine. :param sqla_col: sql alchemy column instance :param label: alias/label that column is expected to have :return: either a sql alchemy column or lab...
Runs query against sqla to retrieve some sample values for the given column.
def values_for_column(self, column_name, limit=10000): """Runs query against sqla to retrieve some sample values for the given column. """ cols = {col.column_name: col for col in self.columns} target_col = cols[column_name] tp = self.get_template_processor() qry ...
Apply config's SQL_QUERY_MUTATOR Typically adds comments to the query with context
def mutate_query_from_config(self, sql): """Apply config's SQL_QUERY_MUTATOR Typically adds comments to the query with context""" SQL_QUERY_MUTATOR = config.get('SQL_QUERY_MUTATOR') if SQL_QUERY_MUTATOR: username = utils.get_username() sql = SQL_QUERY_MUTATOR(sql...
Turn an adhoc metric into a sqlalchemy column. :param dict metric: Adhoc metric definition :param dict cols: Columns for the current table :returns: The metric defined as a sqlalchemy column :rtype: sqlalchemy.sql.column
def adhoc_metric_to_sqla(self, metric, cols): """ Turn an adhoc metric into a sqlalchemy column. :param dict metric: Adhoc metric definition :param dict cols: Columns for the current table :returns: The metric defined as a sqlalchemy column :rtype: sqlalchemy.sql.column ...
Querying any sqla table from this common interface
def get_sqla_query( # sqla self, groupby, metrics, granularity, from_dttm, to_dttm, filter=None, # noqa is_timeseries=True, timeseries_limit=15, timeseries_limit_metric=None, row_limit=None, inner_f...
Fetches the metadata for the table and merges it in
def fetch_metadata(self): """Fetches the metadata for the table and merges it in""" try: table = self.get_sqla_table_object() except Exception as e: logging.exception(e) raise Exception(_( "Table [{}] doesn't seem to exist in the specified data...
Imports the datasource from the object to the database. Metrics and columns and datasource will be overrided if exists. This function can be used to import/export dashboards between multiple superset instances. Audit metadata isn't copies over.
def import_obj(cls, i_datasource, import_time=None): """Imports the datasource from the object to the database. Metrics and columns and datasource will be overrided if exists. This function can be used to import/export dashboards between multiple superset instances. Audit metadata is...
Loading lat/long data from a csv file in the repo
def load_long_lat_data(): """Loading lat/long data from a csv file in the repo""" data = get_example_data('san_francisco.csv.gz', make_bytes=True) pdf = pd.read_csv(data, encoding='utf-8') start = datetime.datetime.now().replace( hour=0, minute=0, second=0, microsecond=0) pdf['datetime'] = [...
Gets column info from the source system
def external_metadata(self, datasource_type=None, datasource_id=None): """Gets column info from the source system""" if datasource_type == 'druid': datasource = ConnectorRegistry.get_datasource( datasource_type, datasource_id, db.session) elif datasource_type == 'tabl...
Returns a list of non empty values or None
def filter_not_empty_values(value): """Returns a list of non empty values or None""" if not value: return None data = [x for x in value if x] if not data: return None return data
If the user has access to the database or all datasource 1. if schemas_allowed_for_csv_upload is empty a) if database does not support schema user is able to upload csv without specifying schema name b) if database supports schema user ...
def at_least_one_schema_is_allowed(database): """ If the user has access to the database or all datasource 1. if schemas_allowed_for_csv_upload is empty a) if database does not support schema user is able to upload csv without specifying schema name ...
Filter queries to only those owned by current user if can_only_access_owned_queries permission is set. :returns: query
def apply( self, query: BaseQuery, func: Callable) -> BaseQuery: """ Filter queries to only those owned by current user if can_only_access_owned_queries permission is set. :returns: query """ if security_manager.can_only_access_owned_q...
Simple hack to redirect to explore view after saving
def edit(self, pk): """Simple hack to redirect to explore view after saving""" resp = super(TableModelView, self).edit(pk) if isinstance(resp, str): return resp return redirect('/superset/explore/table/{}/'.format(pk))
Get/cache a language pack Returns the langugage pack from cache if it exists, caches otherwise >>> get_language_pack('fr')['Dashboards'] "Tableaux de bords"
def get_language_pack(locale): """Get/cache a language pack Returns the langugage pack from cache if it exists, caches otherwise >>> get_language_pack('fr')['Dashboards'] "Tableaux de bords" """ pack = ALL_LANGUAGE_PACKS.get(locale) if not pack: filename = DIR + '/{}/LC_MESSAGES/me...
Build `form_data` for chart GET request from dashboard's `default_filters`. When a dashboard has `default_filters` they need to be added as extra filters in the GET request for charts.
def get_form_data(chart_id, dashboard=None): """ Build `form_data` for chart GET request from dashboard's `default_filters`. When a dashboard has `default_filters` they need to be added as extra filters in the GET request for charts. """ form_data = {'slice_id': chart_id} if dashboard is...
Return external URL for warming up a given chart/table cache.
def get_url(params): """Return external URL for warming up a given chart/table cache.""" baseurl = 'http://{SUPERSET_WEBSERVER_ADDRESS}:{SUPERSET_WEBSERVER_PORT}/'.format( **app.config) with app.test_request_context(): return urllib.parse.urljoin( baseurl, url_for('Su...
Warm up cache. This task periodically hits charts to warm up the cache.
def cache_warmup(strategy_name, *args, **kwargs): """ Warm up cache. This task periodically hits charts to warm up the cache. """ logger.info('Loading strategy') class_ = None for class_ in strategies: if class_.name == strategy_name: break else: message = f...
Mocked. Retrieve the logs produced by the execution of the query. Can be called multiple times to fetch the logs produced after the previous call. :returns: list<str> :raises: ``ProgrammingError`` when no query has been started .. note:: This is not a part of DB-API.
def fetch_logs(self, max_rows=1024, orientation=None): """Mocked. Retrieve the logs produced by the execution of the query. Can be called multiple times to fetch the logs produced after the previous call. :returns: list<str> :raises: ``ProgrammingError`` when no query has been started...
Refresh metadata of all datasources in the cluster If ``datasource_name`` is specified, only that datasource is updated
def refresh_datasources( self, datasource_name=None, merge_flag=True, refreshAll=True): """Refresh metadata of all datasources in the cluster If ``datasource_name`` is specified, only that datasource is updated """ ds_list = self.get_dataso...
Fetches metadata for the specified datasources and merges to the Superset database
def refresh(self, datasource_names, merge_flag, refreshAll): """ Fetches metadata for the specified datasources and merges to the Superset database """ session = db.session ds_list = ( session.query(DruidDatasource) .filter(DruidDatasource.cluster_...
Refresh metrics based on the column metadata
def refresh_metrics(self): """Refresh metrics based on the column metadata""" metrics = self.get_metrics() dbmetrics = ( db.session.query(DruidMetric) .filter(DruidMetric.datasource_id == self.datasource_id) .filter(DruidMetric.metric_name.in_(metrics.keys()))...
Imports the datasource from the object to the database. Metrics and columns and datasource will be overridden if exists. This function can be used to import/export dashboards between multiple superset instances. Audit metadata isn't copies over.
def import_obj(cls, i_datasource, import_time=None): """Imports the datasource from the object to the database. Metrics and columns and datasource will be overridden if exists. This function can be used to import/export dashboards between multiple superset instances. Audit metadata i...
Merges the ds config from druid_config into one stored in the db.
def sync_to_db_from_config( cls, druid_config, user, cluster, refresh=True): """Merges the ds config from druid_config into one stored in the db.""" session = db.session datasource = ( session.query(cls) .filter_...
For a metric specified as `postagg` returns the kind of post aggregation for pydruid.
def get_post_agg(mconf): """ For a metric specified as `postagg` returns the kind of post aggregation for pydruid. """ if mconf.get('type') == 'javascript': return JavascriptPostAggregator( name=mconf.get('name', ''), field_names=mconf....
Return a list of metrics that are post aggregations
def find_postaggs_for(postagg_names, metrics_dict): """Return a list of metrics that are post aggregations""" postagg_metrics = [ metrics_dict[name] for name in postagg_names if metrics_dict[name].metric_type == POST_AGG_TYPE ] # Remove post aggregations that were...
Retrieve some values for the given column
def values_for_column(self, column_name, limit=10000): """Retrieve some values for the given column""" logging.info( 'Getting values for columns [{}] limited to [{}]' .format(column_name, limit)) # TODO: Use Lexicographi...
Returns a dictionary of aggregation metric names to aggregation json objects :param metrics_dict: dictionary of all the metrics :param saved_metrics: list of saved metric names :param adhoc_metrics: list of adhoc metric names :raise SupersetException: if one or more metr...
def get_aggregations(metrics_dict, saved_metrics, adhoc_metrics=[]): """ Returns a dictionary of aggregation metric names to aggregation json objects :param metrics_dict: dictionary of all the metrics :param saved_metrics: list of saved metric names :param adhoc_...
Replace dimensions specs with their `dimension` values, and ignore those without
def _dimensions_to_values(dimensions): """ Replace dimensions specs with their `dimension` values, and ignore those without """ values = [] for dimension in dimensions: if isinstance(dimension, dict): if 'extractionFn' in dimension: ...
Runs a query against Druid and returns a dataframe.
def run_query( # noqa / druid self, groupby, metrics, granularity, from_dttm, to_dttm, filter=None, # noqa is_timeseries=True, timeseries_limit=None, timeseries_limit_metric=None, row_limit=None, in...
Converting all GROUPBY columns to strings When grouping by a numeric (say FLOAT) column, pydruid returns strings in the dataframe. This creates issues downstream related to having mixed types in the dataframe Here we replace None with <NULL> and make the whole series a str inst...
def homogenize_types(df, groupby_cols): """Converting all GROUPBY columns to strings When grouping by a numeric (say FLOAT) column, pydruid returns strings in the dataframe. This creates issues downstream related to having mixed types in the dataframe Here we replace None with ...
Given Superset filter data structure, returns pydruid Filter(s)
def get_filters(cls, raw_filters, num_cols, columns_dict): # noqa """Given Superset filter data structure, returns pydruid Filter(s)""" filters = None for flt in raw_filters: col = flt.get('col') op = flt.get('op') eq = flt.get('val') if ( ...
Get the environment variable or raise exception.
def get_env_variable(var_name, default=None): """Get the environment variable or raise exception.""" try: return os.environ[var_name] except KeyError: if default is not None: return default else: error_msg = 'The environment variable {} was missing, abort...'\...
Returns datasource with columns and metrics.
def get_eager_datasource(cls, session, datasource_type, datasource_id): """Returns datasource with columns and metrics.""" datasource_class = ConnectorRegistry.sources[datasource_type] return ( session.query(datasource_class) .options( subqueryload(datasou...
Loading a dashboard featuring misc charts
def load_misc_dashboard(): """Loading a dashboard featuring misc charts""" print('Creating the dashboard') db.session.expunge_all() dash = db.session.query(Dash).filter_by(slug=DASH_SLUG).first() if not dash: dash = Dash() js = textwrap.dedent("""\ { "CHART-BkeVbh8ANQ": { "...
Loads the world bank health dataset, slices and a dashboard
def load_world_bank_health_n_pop(): """Loads the world bank health dataset, slices and a dashboard""" tbl_name = 'wb_health_population' data = get_example_data('countries.json.gz') pdf = pd.read_json(data) pdf.columns = [col.replace('.', '_') for col in pdf.columns] pdf.year = pd.to_datetime(pdf...
Loading data for map with country map
def load_country_map_data(): """Loading data for map with country map""" csv_bytes = get_example_data( 'birth_france_data_for_country_map.csv', is_gzip=False, make_bytes=True) data = pd.read_csv(csv_bytes, encoding='utf-8') data['dttm'] = datetime.datetime.now().date() data.to_sql( # pylint...
Returns a list of SQL statements as strings, stripped
def get_statements(self): """Returns a list of SQL statements as strings, stripped""" statements = [] for statement in self._parsed: if statement: sql = str(statement).strip(' \n;\t') if sql: statements.append(sql) return st...
Reformats the query into the create table as query. Works only for the single select SQL statements, in all other cases the sql query is not modified. :param superset_query: string, sql query that will be executed :param table_name: string, will contain the results of the qu...
def as_create_table(self, table_name, overwrite=False): """Reformats the query into the create table as query. Works only for the single select SQL statements, in all other cases the sql query is not modified. :param superset_query: string, sql query that will be executed :param...
returns the query with the specified limit
def get_query_with_new_limit(self, new_limit): """returns the query with the specified limit""" """does not change the underlying query""" if not self._limit: return self.sql + ' LIMIT ' + str(new_limit) limit_pos = None tokens = self._parsed[0].tokens # Add a...
Read a url or post parameter and use it in your SQL Lab query When in SQL Lab, it's possible to add arbitrary URL "query string" parameters, and use those in your SQL code. For instance you can alter your url and add `?foo=bar`, as in `{domain}/superset/sqllab?foo=bar`. Then if your query is something ...
def url_param(param, default=None): """Read a url or post parameter and use it in your SQL Lab query When in SQL Lab, it's possible to add arbitrary URL "query string" parameters, and use those in your SQL code. For instance you can alter your url and add `?foo=bar`, as in `{domain}/superset/sqllab...
Gets a values for a particular filter as a list This is useful if: - you want to use a filter box to filter a query where the name of filter box column doesn't match the one in the select statement - you want to have the ability for filter inside the main query for speed purposes Thi...
def filter_values(column, default=None): """ Gets a values for a particular filter as a list This is useful if: - you want to use a filter box to filter a query where the name of filter box column doesn't match the one in the select statement - you want to have the ability for filter ...
Processes a sql template >>> sql = "SELECT '{{ datetime(2017, 1, 1).isoformat() }}'" >>> process_template(sql) "SELECT '2017-01-01T00:00:00'"
def process_template(self, sql, **kwargs): """Processes a sql template >>> sql = "SELECT '{{ datetime(2017, 1, 1).isoformat() }}'" >>> process_template(sql) "SELECT '2017-01-01T00:00:00'" """ template = self.env.from_string(sql) kwargs.update(self.context) ...
Compatibility layer for handling of datasource info datasource_id & datasource_type used to be passed in the URL directory, now they should come as part of the form_data, This function allows supporting both without duplicating code
def get_datasource_info(datasource_id, datasource_type, form_data): """Compatibility layer for handling of datasource info datasource_id & datasource_type used to be passed in the URL directory, now they should come as part of the form_data, This function allows supporting both without duplicating code...
Protecting from has_access failing from missing perms/view
def can_access(self, permission_name, view_name): """Protecting from has_access failing from missing perms/view""" user = g.user if user.is_anonymous: return self.is_item_public(permission_name, view_name) return self._has_view_access(user, permission_name, view_name)
FAB leaves faulty permissions that need to be cleaned up
def clean_perms(self): """FAB leaves faulty permissions that need to be cleaned up""" logging.info('Cleaning faulty perms') sesh = self.get_session pvms = ( sesh.query(ab_models.PermissionView) .filter(or_( ab_models.PermissionView.permission == No...
Inits the Superset application with security roles and such
def sync_role_definitions(self): """Inits the Superset application with security roles and such""" from superset import conf logging.info('Syncing role definition') self.create_custom_permissions() # Creating default roles self.set_role('Admin', self.is_admin_pvm) ...
Exports the supported import/export schema to a dictionary
def export_schema_to_dict(back_references): """Exports the supported import/export schema to a dictionary""" databases = [Database.export_schema(recursive=True, include_parent_ref=back_references)] clusters = [DruidCluster.export_schema(recursive=True, include_parent_ref=bac...
Exports databases and druid clusters to a dictionary
def export_to_dict(session, recursive, back_references, include_defaults): """Exports databases and druid clusters to a dictionary""" logging.info('Starting export') dbs = session.query(Database) databases = [database.export_to_dict(recursive=recu...
Imports databases and druid clusters from dictionary
def import_from_dict(session, data, sync=[]): """Imports databases and druid clusters from dictionary""" if isinstance(data, dict): logging.info('Importing %d %s', len(data.get(DATABASES_KEY, [])), DATABASES_KEY) for database in data.get(DATABASES_KEY, [...
Takes a query_obj constructed in the client and returns payload data response for the given query_obj. params: query_context: json_blob
def query(self): """ Takes a query_obj constructed in the client and returns payload data response for the given query_obj. params: query_context: json_blob """ query_context = QueryContext(**json.loads(request.form.get('query_context'))) security_manager.assert_d...
Get the formdata stored in the database for existing slice. params: slice_id: integer
def query_form_data(self): """ Get the formdata stored in the database for existing slice. params: slice_id: integer """ form_data = {} slice_id = request.args.get('slice_id') if slice_id: slc = db.session.query(models.Slice).filter_by(id=slice_id).one...
Loads 2 css templates to demonstrate the feature
def load_css_templates(): """Loads 2 css templates to demonstrate the feature""" print('Creating default CSS templates') obj = db.session.query(CssTemplate).filter_by(template_name='Flat').first() if not obj: obj = CssTemplate(template_name='Flat') css = textwrap.dedent("""\ .gridster d...
Get a mapping of foreign name to the local name of foreign keys
def _parent_foreign_key_mappings(cls): """Get a mapping of foreign name to the local name of foreign keys""" parent_rel = cls.__mapper__.relationships.get(cls.export_parent) if parent_rel: return {l.name: r.name for (l, r) in parent_rel.local_remote_pairs} return {}
Get all (single column and multi column) unique constraints
def _unique_constrains(cls): """Get all (single column and multi column) unique constraints""" unique = [{c.name for c in u.columns} for u in cls.__table_args__ if isinstance(u, UniqueConstraint)] unique.extend({c.name} for c in cls.__table__.columns if c.unique) return...
Export schema as a dictionary
def export_schema(cls, recursive=True, include_parent_ref=False): """Export schema as a dictionary""" parent_excludes = {} if not include_parent_ref: parent_ref = cls.__mapper__.relationships.get(cls.export_parent) if parent_ref: parent_excludes = {c.name ...
Import obj from a dictionary
def import_from_dict(cls, session, dict_rep, parent=None, recursive=True, sync=[]): """Import obj from a dictionary""" parent_refs = cls._parent_foreign_key_mappings() export_fields = set(cls.export_fields) | set(parent_refs.keys()) new_children = {c: dict_rep.ge...
Export obj to dictionary
def export_to_dict(self, recursive=True, include_parent_ref=False, include_defaults=False): """Export obj to dictionary""" cls = self.__class__ parent_excludes = {} if recursive and not include_parent_ref: parent_ref = cls.__mapper__.relationships.get(c...
Overrides the plain fields of the dashboard.
def override(self, obj): """Overrides the plain fields of the dashboard.""" for field in obj.__class__.export_fields: setattr(self, field, getattr(obj, field))
Move since and until to time_range.
def update_time_range(form_data): """Move since and until to time_range.""" if 'since' in form_data or 'until' in form_data: form_data['time_range'] = '{} : {}'.format( form_data.pop('since', '') or '', form_data.pop('until', '') or '', )
Use this decorator to cache functions that have predefined first arg. enable_cache is treated as True by default, except enable_cache = False is passed to the decorated function. force means whether to force refresh the cache and is treated as False by default, except force = True is passed to the dec...
def memoized_func(key=view_cache_key, attribute_in_key=None): """Use this decorator to cache functions that have predefined first arg. enable_cache is treated as True by default, except enable_cache = False is passed to the decorated function. force means whether to force refresh the cache and is trea...
Name property
def name(self): """Name property""" ts = datetime.now().isoformat() ts = ts.replace('-', '').replace(':', '').split('.')[0] tab = (self.tab_name.replace(' ', '_').lower() if self.tab_name else 'notab') tab = re.sub(r'\W+', '', tab) return f'sqllab_{tab}_{ts...
Check if user can access a cached response from explore_json. This function takes `self` since it must have the same signature as the the decorated method.
def check_datasource_perms(self, datasource_type=None, datasource_id=None): """ Check if user can access a cached response from explore_json. This function takes `self` since it must have the same signature as the the decorated method. """ form_data = get_form_data()[0] datasource_id, data...
Check if user can access a cached response from slice_json. This function takes `self` since it must have the same signature as the the decorated method.
def check_slice_perms(self, slice_id): """ Check if user can access a cached response from slice_json. This function takes `self` since it must have the same signature as the the decorated method. """ form_data, slc = get_form_data(slice_id, use_slice_data=True) datasource_type = slc.datas...
Applies the configuration's http headers to all responses
def apply_caching(response): """Applies the configuration's http headers to all responses""" for k, v in config.get('HTTP_HEADERS').items(): response.headers[k] = v return response
Updates the role with the give datasource permissions. Permissions not in the request will be revoked. This endpoint should be available to admins only. Expects JSON in the format: { 'role_name': '{role_name}', 'database': [{ 'datasource_type': '{t...
def override_role_permissions(self): """Updates the role with the give datasource permissions. Permissions not in the request will be revoked. This endpoint should be available to admins only. Expects JSON in the format: { 'role_name': '{role_name}', 'data...
Serves all request that GET or POST form_data This endpoint evolved to be the entry point of many different requests that GETs or POSTs a form_data. `self.generate_json` receives this input and returns different payloads based on the request args in the first block TODO: break...
def explore_json(self, datasource_type=None, datasource_id=None): """Serves all request that GET or POST form_data This endpoint evolved to be the entry point of many different requests that GETs or POSTs a form_data. `self.generate_json` receives this input and returns different ...
Overrides the dashboards using json instances from the file.
def import_dashboards(self): """Overrides the dashboards using json instances from the file.""" f = request.files.get('file') if request.method == 'POST' and f: dashboard_import_export.import_dashboards(db.session, f.stream) return redirect('/dashboard/list/') ret...
Deprecated endpoint, here for backward compatibility of urls
def explorev2(self, datasource_type, datasource_id): """Deprecated endpoint, here for backward compatibility of urls""" return redirect(url_for( 'Superset.explore', datasource_type=datasource_type, datasource_id=datasource_id, **request.args))
Endpoint to retrieve values for specified column. :param datasource_type: Type of datasource e.g. table :param datasource_id: Datasource id :param column: Column name to retrieve values for :return:
def filter(self, datasource_type, datasource_id, column): """ Endpoint to retrieve values for specified column. :param datasource_type: Type of datasource e.g. table :param datasource_id: Datasource id :param column: Column name to retrieve values for :return: ""...
Save or overwrite a slice
def save_or_overwrite_slice( self, args, slc, slice_add_perm, slice_overwrite_perm, slice_download_perm, datasource_id, datasource_type, datasource_name): """Save or overwrite a slice""" slice_name = args.get('slice_name') action = args.get('action') form_data = g...
endpoint for checking/unchecking any boolean in a sqla model
def checkbox(self, model_view, id_, attr, value): """endpoint for checking/unchecking any boolean in a sqla model""" modelview_to_model = { '{}ColumnInlineView'.format(name.capitalize()): source.column_class for name, source in ConnectorRegistry.sources.items() } ...
Endpoint to fetch the list of tables for given database
def tables(self, db_id, schema, substr, force_refresh='false'): """Endpoint to fetch the list of tables for given database""" db_id = int(db_id) force_refresh = force_refresh.lower() == 'true' schema = utils.js_string_to_python(schema) substr = utils.js_string_to_python(substr) ...
Copy dashboard
def copy_dash(self, dashboard_id): """Copy dashboard""" session = db.session() data = json.loads(request.form.get('data')) dash = models.Dashboard() original_dash = ( session .query(models.Dashboard) .filter_by(id=dashboard_id).first()) ...
Save a dashboard's metadata
def save_dash(self, dashboard_id): """Save a dashboard's metadata""" session = db.session() dash = (session .query(models.Dashboard) .filter_by(id=dashboard_id).first()) check_ownership(dash, raise_if_false=True) data = json.loads(request.form.get(...
Add and save slices to a dashboard
def add_slices(self, dashboard_id): """Add and save slices to a dashboard""" data = json.loads(request.form.get('data')) session = db.session() Slice = models.Slice # noqa dash = ( session.query(models.Dashboard).filter_by(id=dashboard_id).first()) check_owne...
Recent activity (actions) for a given user
def recent_activity(self, user_id): """Recent activity (actions) for a given user""" M = models # noqa if request.args.get('limit'): limit = int(request.args.get('limit')) else: limit = 1000 qry = ( db.session.query(M.Log, M.Dashboard, M.Sli...
This lets us use a user's username to pull favourite dashboards
def fave_dashboards_by_username(self, username): """This lets us use a user's username to pull favourite dashboards""" user = security_manager.find_user(username=username) return self.fave_dashboards(user.get_id())
List of slices a user created, or faved
def user_slices(self, user_id=None): """List of slices a user created, or faved""" if not user_id: user_id = g.user.id Slice = models.Slice # noqa FavStar = models.FavStar # noqa qry = ( db.session.query(Slice, FavStar.dttm).j...
List of slices created by this user
def created_slices(self, user_id=None): """List of slices created by this user""" if not user_id: user_id = g.user.id Slice = models.Slice # noqa qry = ( db.session.query(Slice) .filter( sqla.or_( Slice.created_by_f...
Favorite slices for a user
def fave_slices(self, user_id=None): """Favorite slices for a user""" if not user_id: user_id = g.user.id qry = ( db.session.query( models.Slice, models.FavStar.dttm, ) .join( models.FavStar, ...
Warms up the cache for the slice or table. Note for slices a force refresh occurs.
def warm_up_cache(self): """Warms up the cache for the slice or table. Note for slices a force refresh occurs. """ slices = None session = db.session() slice_id = request.args.get('slice_id') table_name = request.args.get('table_name') db_name = request.a...