Python flask_babel.lazy_gettext() Examples

The following are 30 code examples of flask_babel.lazy_gettext(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask_babel , or try the search function .
Example #1
Source File: core.py    From incubator-superset with Apache License 2.0 6 votes vote down vote up
def profile(self, username: str) -> FlaskResponse:
        """User profile page"""
        user = (
            db.session.query(ab_models.User).filter_by(username=username).one_or_none()
        )
        if not user:
            abort(404, description=f"User: {username} does not exist.")

        payload = {
            "user": bootstrap_user_data(user, include_perms=True),
            "common": common_bootstrap_payload(),
        }

        return self.render_template(
            "superset/basic.html",
            title=_("%(user)s's profile", user=username),
            entry="profile",
            bootstrap_data=json.dumps(
                payload, default=utils.pessimistic_json_iso_dttm_ser
            ),
        ) 
Example #2
Source File: admin.py    From maple-blog with GNU General Public License v3.0 6 votes vote down vote up
def init_app(app):
    admin = Admin(
        name=_("honmaple"),
        index_view=AdminIndexView(
            template="admin/index.html",
            url=app.config.get("ADMIN_URL", "/"),
        ),
        template_mode="bootstrap3")

    admins = [
        "maple.admin",
        "maple.blog.admin",
        "maple.storage.admin",
    ]
    [import_string(i).init_admin(admin) for i in admins]
    admin.init_app(app) 
Example #3
Source File: viz_sip38.py    From incubator-superset with Apache License 2.0 6 votes vote down vote up
def query_obj(self):
        form_data = self.form_data
        d = super().query_obj()

        self.x_metric = form_data["x"]
        self.y_metric = form_data["y"]
        self.z_metric = form_data["size"]
        self.entity = form_data.get("entity")
        self.series = form_data.get("series") or self.entity
        d["row_limit"] = form_data.get("limit")

        d["metrics"] = [self.z_metric, self.x_metric, self.y_metric]
        if len(set(self.metric_labels)) < 3:
            raise QueryObjectValidationError(_("Please use 3 different metric labels"))
        if not all(d["metrics"] + [self.entity]):
            raise QueryObjectValidationError(_("Pick a metric for x, y and size"))
        return d 
Example #4
Source File: views.py    From Flask-Framework-Cookbook-Second-Edition with MIT License 6 votes vote down vote up
def create_product():
    form = ProductForm()

    if form.validate_on_submit():
        name = form.name.data
        price = form.price.data
        category = Category.query.get_or_404(
            form.category.data
        )
        image = form.image.data
        if allowed_file(image.filename):
            filename = secure_filename(image.filename)
            image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        product = Product(name, price, category, filename)
        db.session.add(product)
        db.session.commit()
        flash(_('The product %(name)s has been created', name=name), 'success')
        return redirect(url_for('catalog.product', id=product.id))

    if form.errors:
        flash(form.errors, 'danger')

    return render_template('product-create.html', form=form) 
Example #5
Source File: jinja.py    From maple-blog with GNU General Public License v3.0 6 votes vote down vote up
def timesince(dt, default=_("just now")):
    now = datetime.utcnow()
    diff = now - dt
    if diff.days > 90:
        return format_datetime(dt, 'Y-MM-dd')
    if diff.days > 10:
        return format_datetime(dt, 'Y-MM-dd HH:mm')
    elif diff.days <= 10 and diff.days > 0:
        periods = ((diff.days, "day", "days"), )
    elif diff.days <= 0 and diff.seconds > 3600:
        periods = ((diff.seconds / 3600, "hour", "hours"), )
    elif diff.seconds <= 3600 and diff.seconds > 90:
        periods = ((diff.seconds / 60, "minute", "minutes"), )
    else:
        return default

    for period, singular, plural in periods:

        if period:
            return "%d %s ago" % (period, singular if period == 1 else plural)

    return default 
Example #6
Source File: views.py    From Flask-Framework-Cookbook-Second-Edition with MIT License 6 votes vote down vote up
def create_category():
    form = CategoryForm()

    if form.validate_on_submit():
        name = form.name.data
        category = Category(name)
        db.session.add(category)
        db.session.commit()
        flash(
            _('The category %(name)s has been created', name=name), 'success'
        )
        return redirect(
            url_for('catalog.category', id=category.id)
        )

    if form.errors:
        flash(form.errors, 'danger')

    return render_template('category-create.html', form=form) 
Example #7
Source File: admin.py    From c3bottles with MIT License 6 votes vote down vote up
def user_password():
    form = PasswordForm()
    if not form.validate_on_submit():
        abort(400)
    user = User.get_or_404(form.user_id.data)
    if form.password_1.data == form.password_2.data:
        user.password = bcrypt.generate_password_hash(form.password_1.data)
        user.token = make_secure_token()
        db.session.add(user)
        db.session.commit()
        flash({
            "class": "success",
            "text": lazy_gettext("The user's password has been changed successfully")
        })
        if user == current_user:
            return redirect(url_for("main.index"))
        else:
            return redirect(url_for("admin.index"))
    else:
        flash({
            "class": "danger",
            "text": lazy_gettext("The passwords do not match.")
        })
        return redirect(url_for("admin.index")) 
Example #8
Source File: admin.py    From c3bottles with MIT License 6 votes vote down vote up
def create_user():
    form = UserCreateForm()
    if not form.validate_on_submit():
        abort(400)
    if User.get(form.username.data) is not None:
        flash({
            "class": "danger",
            "text": lazy_gettext("A user with this name already exists")
        })
        return redirect(url_for("admin.index"))
    else:
        user = User(
            form.username.data, form.password.data, form.can_visit.data,
            form.can_edit.data, form.is_admin.data, False
        )
        db.session.add(user)
        db.session.commit()
        flash({
            "class": "success",
            "text": lazy_gettext("The new user has been created successfully.")
        })
        return redirect(url_for("admin.index")) 
Example #9
Source File: drop_point.py    From c3bottles with MIT License 6 votes vote down vote up
def remove(self, time=None):
        """
        Remove a drop point.

        This will not actually purge a drop point from the database but
        simply mark it as removed so it will no longer show up in the
        frontend. The time of removal can be given optionally and will
        default to :func:`datetime.today()`.
        """

        if self.removed:
            raise RuntimeError({"DropPoint": lazy_gettext("Drop point already removed.")})

        if time and not isinstance(time, datetime):
            raise TypeError({"DropPoint": lazy_gettext("Removal time not a datetime object.")})

        if time and time > datetime.today():
            raise ValueError({"DropPoint": lazy_gettext("Removal time in the future.")})

        self.removed = time if time else datetime.today()
        metrics.drop_point_count.labels(
            state=self.last_state, category=self.category.metrics_name
        ).dec() 
Example #10
Source File: viz.py    From incubator-superset with Apache License 2.0 6 votes vote down vote up
def run_extra_queries(self) -> None:
        qry = super().query_obj()
        filters = self.form_data.get("filter_configs") or []
        qry["row_limit"] = self.filter_row_limit
        self.dataframes = {}
        for flt in filters:
            col = flt.get("column")
            if not col:
                raise QueryObjectValidationError(
                    _("Invalid filter configuration, please select a column")
                )
            qry["groupby"] = [col]
            metric = flt.get("metric")
            qry["metrics"] = [metric] if metric else []
            df = self.get_df_payload(query_obj=qry).get("df")
            self.dataframes[col] = df 
Example #11
Source File: viz.py    From incubator-superset with Apache License 2.0 6 votes vote down vote up
def get_data(self, df: pd.DataFrame) -> VizData:
        if df.empty:
            return None

        fd = self.form_data

        if self.form_data.get("granularity") == "all":
            raise QueryObjectValidationError(
                _("Pick a time granularity for your time series")
            )

        metric = utils.get_metric_name(fd["metric"])
        metric_2 = utils.get_metric_name(fd["metric_2"])
        df = df.pivot_table(index=DTTM_ALIAS, values=[metric, metric_2])

        chart_data = self.to_series(df)
        return chart_data 
Example #12
Source File: mixins.py    From incubator-superset with Apache License 2.0 6 votes vote down vote up
def check_extra(self, database: Database) -> None:  # pylint: disable=no-self-use
        # this will check whether json.loads(extra) can succeed
        try:
            extra = database.get_extra()
        except Exception as ex:
            raise Exception(
                _("Extra field cannot be decoded by JSON. %{msg}s", msg=str(ex))
            )

        # this will check whether 'metadata_params' is configured correctly
        metadata_signature = inspect.signature(MetaData)
        for key in extra.get("metadata_params", {}):
            if key not in metadata_signature.parameters:
                raise Exception(
                    _(
                        "The metadata_params in Extra field "
                        "is not configured correctly. The key "
                        "%{key}s is invalid.",
                        key=key,
                    )
                ) 
Example #13
Source File: base.py    From incubator-superset with Apache License 2.0 6 votes vote down vote up
def validate_sqlatable(table: models.SqlaTable) -> None:
    """Checks the table existence in the database."""
    with db.session.no_autoflush:
        table_query = db.session.query(models.SqlaTable).filter(
            models.SqlaTable.table_name == table.table_name,
            models.SqlaTable.schema == table.schema,
            models.SqlaTable.database_id == table.database.id,
        )
        if db.session.query(table_query.exists()).scalar():
            raise Exception(get_datasource_exist_error_msg(table.full_name))

    # Fail before adding if the table can't be found
    try:
        table.get_sqla_table_object()
    except Exception as ex:
        logger.exception("Got an error in pre_add for %s", table.name)
        raise Exception(
            _(
                "Table [%{table}s] could not be found, "
                "please double check your "
                "database connection, schema, and "
                "table name, error: {}"
            ).format(table.name, str(ex))
        ) 
Example #14
Source File: viz.py    From incubator-superset with Apache License 2.0 6 votes vote down vote up
def query_obj(self) -> QueryObjectDict:
        form_data = self.form_data
        d = super().query_obj()
        d["groupby"] = [form_data.get("entity")]
        if form_data.get("series"):
            d["groupby"].append(form_data.get("series"))

        # dedup groupby if it happens to be the same
        d["groupby"] = list(dict.fromkeys(d["groupby"]))

        self.x_metric = form_data["x"]
        self.y_metric = form_data["y"]
        self.z_metric = form_data["size"]
        self.entity = form_data.get("entity")
        self.series = form_data.get("series") or self.entity
        d["row_limit"] = form_data.get("limit")

        d["metrics"] = [self.z_metric, self.x_metric, self.y_metric]
        if len(set(self.metric_labels)) < 3:
            raise QueryObjectValidationError(_("Please use 3 different metric labels"))
        if not all(d["metrics"] + [self.entity]):
            raise QueryObjectValidationError(_("Pick a metric for x, y and size"))
        return d 
Example #15
Source File: viz_sip38.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def should_be_timeseries(self):
        fd = self.form_data
        # TODO handle datasource-type-specific code in datasource
        conditions_met = (fd.get("granularity") and fd.get("granularity") != "all") or (
            fd.get("granularity_sqla") and fd.get("time_grain_sqla")
        )
        if fd.get("include_time") and not conditions_met:
            raise QueryObjectValidationError(
                _("Pick a granularity in the Time section or " "uncheck 'Include Time'")
            )
        return bool(fd.get("include_time")) 
Example #16
Source File: viz.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def query_obj(self) -> QueryObjectDict:
        d = super().query_obj()
        fd = self.form_data
        if len(d["groupby"]) < len(fd.get("groupby") or []) + len(
            fd.get("columns") or []
        ):
            raise QueryObjectValidationError(
                _("Can't have overlap between Series and Breakdowns")
            )
        if not fd.get("metrics"):
            raise QueryObjectValidationError(_("Pick at least one metric"))
        if not fd.get("groupby"):
            raise QueryObjectValidationError(_("Pick at least one field for [Series]"))
        return d 
Example #17
Source File: viz.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def query_obj(self) -> QueryObjectDict:
        """Returns the query object for this visualization"""
        d = super().query_obj()
        d["row_limit"] = self.form_data.get("row_limit", int(config["VIZ_ROW_LIMIT"]))
        numeric_columns = self.form_data.get("all_columns_x")
        if numeric_columns is None:
            raise QueryObjectValidationError(
                _("Must have at least one numeric column specified")
            )
        self.columns = numeric_columns
        d["columns"] = numeric_columns + self.groupby
        # override groupby entry to avoid aggregation
        d["groupby"] = []
        return d 
Example #18
Source File: viz_sip38.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def query_obj(self):
        d = super().query_obj()
        fd = self.form_data

        if not fd.get("metrics"):
            raise QueryObjectValidationError(_("Pick at least one metric"))

        if fd.get("groupby") and len(fd.get("metrics")) > 1:
            raise QueryObjectValidationError(
                _("When using 'Group By' you are limited to use a single metric")
            )
        return d 
Example #19
Source File: viz.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def query_obj(self) -> QueryObjectDict:
        d = super().query_obj()
        m1 = self.form_data.get("metric")
        m2 = self.form_data.get("metric_2")
        d["metrics"] = [m1, m2]
        if not m1:
            raise QueryObjectValidationError(_("Pick a metric for left axis!"))
        if not m2:
            raise QueryObjectValidationError(_("Pick a metric for right axis!"))
        if m1 == m2:
            raise QueryObjectValidationError(
                _("Please choose different metrics" " on left and right axis")
            )
        return d 
Example #20
Source File: exceptions.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def __init__(self) -> None:
        super().__init__(
            _("One or more columns already exist"), field_names=["columns"]
        ) 
Example #21
Source File: viz.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def run_extra_queries(self) -> None:
        fd = self.form_data

        time_compare = fd.get("time_compare") or []
        # backwards compatibility
        if not isinstance(time_compare, list):
            time_compare = [time_compare]

        for option in time_compare:
            query_object = self.query_obj()
            delta = utils.parse_past_timedelta(option)
            query_object["inner_from_dttm"] = query_object["from_dttm"]
            query_object["inner_to_dttm"] = query_object["to_dttm"]

            if not query_object["from_dttm"] or not query_object["to_dttm"]:
                raise QueryObjectValidationError(
                    _(
                        "`Since` and `Until` time bounds should be specified "
                        "when using the `Time Shift` feature."
                    )
                )
            query_object["from_dttm"] -= delta
            query_object["to_dttm"] -= delta

            df2 = self.get_df_payload(query_object, time_compare=option).get("df")
            if df2 is not None and DTTM_ALIAS in df2:
                label = "{} offset".format(option)
                df2[DTTM_ALIAS] += delta
                df2 = self.process_data(df2)
                self._extra_chart_data.append((label, df2)) 
Example #22
Source File: viz.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def query_obj(self) -> QueryObjectDict:
        d = super().query_obj()
        metric = self.form_data.get("metric")
        if not metric:
            raise QueryObjectValidationError(_("Pick a metric!"))
        d["metrics"] = [self.form_data.get("metric")]
        self.form_data["metric"] = metric
        return d 
Example #23
Source File: viz.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def query_obj(self) -> QueryObjectDict:
        form_data = self.form_data
        d = super().query_obj()
        self.metric = form_data["metric"]

        d["metrics"] = [self.metric]
        if not self.metric:
            raise QueryObjectValidationError(_("Pick a metric to display"))
        return d 
Example #24
Source File: viz_sip38.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def query_obj(self):
        form_data = self.form_data
        d = super().query_obj()
        self.metric = form_data.get("metric")

        d["metrics"] = [self.metric]
        if not self.metric:
            raise QueryObjectValidationError(_("Pick a metric to display"))
        return d 
Example #25
Source File: viz.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def query_obj(self) -> QueryObjectDict:
        d = super().query_obj()
        groupby = self.form_data.get("groupby")
        columns = self.form_data.get("columns")
        metrics = self.form_data.get("metrics")
        transpose = self.form_data.get("transpose_pivot")
        if not columns:
            columns = []
        if not groupby:
            groupby = []
        if not groupby:
            raise QueryObjectValidationError(
                _("Please choose at least one 'Group by' field ")
            )
        if transpose and not columns:
            raise QueryObjectValidationError(
                _(
                    (
                        "Please choose at least one 'Columns' field when "
                        "select 'Transpose Pivot' option"
                    )
                )
            )
        if not metrics:
            raise QueryObjectValidationError(_("Please choose at least one metric"))
        if set(groupby) & set(columns):
            raise QueryObjectValidationError(_("Group By' and 'Columns' can't overlap"))
        return d 
Example #26
Source File: viz.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def query_obj(self) -> QueryObjectDict:
        d = super().query_obj()
        fd = self.form_data

        if not fd.get("metrics"):
            raise QueryObjectValidationError(_("Pick at least one metric"))

        if fd.get("groupby") and len(fd["metrics"]) > 1:
            raise QueryObjectValidationError(
                _("When using 'Group By' you are limited to use a single metric")
            )
        return d 
Example #27
Source File: viz.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def __init__(
        self,
        datasource: "BaseDatasource",
        form_data: Dict[str, Any],
        force: bool = False,
    ) -> None:
        if not datasource:
            raise Exception(_("Viz is missing a datasource"))

        self.datasource = datasource
        self.request = request
        self.viz_type = form_data.get("viz_type")
        self.form_data = form_data

        self.query = ""
        self.token = self.form_data.get("token", "token_" + uuid.uuid4().hex[:8])

        self.groupby: List[str] = self.form_data.get("groupby") or []
        self.time_shift = timedelta()

        self.status: Optional[str] = None
        self.error_msg = ""
        self.results: Optional[QueryResult] = None
        self.errors: List[Dict[str, Any]] = []
        self.force = force
        self.from_dttm: Optional[datetime] = None
        self.to_dttm: Optional[datetime] = None

        # Keeping track of whether some data came from cache
        # this is useful to trigger the <CachedLabel /> when
        # in the cases where visualization have many queries
        # (FilterBox for instance)
        self._any_cache_key: Optional[str] = None
        self._any_cached_dttm: Optional[str] = None
        self._extra_chart_data: List[Tuple[str, pd.DataFrame]] = []

        self.process_metrics() 
Example #28
Source File: viz_sip38.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def query_obj(self):
        d = super().query_obj()
        metric = self.form_data.get("metric")
        if not metric:
            raise QueryObjectValidationError(_("Pick a metric!"))
        d["metrics"] = [self.form_data.get("metric")]
        self.form_data["metric"] = metric
        return d 
Example #29
Source File: base.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def get_time_grains(cls) -> Tuple[TimeGrain, ...]:
        """
        Generate a tuple of supported time grains.

        :return: All time grains supported by the engine
        """

        ret_list = []
        time_grains = builtin_time_grains.copy()
        time_grains.update(config["TIME_GRAIN_ADDONS"])
        for duration, func in cls.get_time_grain_expressions().items():
            if duration in time_grains:
                name = time_grains[duration]
                ret_list.append(TimeGrain(name, _(name), func, duration))
        return tuple(ret_list) 
Example #30
Source File: viz.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def get_data(self, df: pd.DataFrame) -> VizData:
        source, target = self.groupby
        (value,) = self.metric_labels
        df.rename(
            columns={source: "source", target: "target", value: "value",}, inplace=True,
        )
        df["source"] = df["source"].astype(str)
        df["target"] = df["target"].astype(str)
        recs = df.to_dict(orient="records")

        hierarchy: Dict[str, Set[str]] = defaultdict(set)
        for row in recs:
            hierarchy[row["source"]].add(row["target"])

        def find_cycle(g: Dict[str, Set[str]]) -> Optional[Tuple[str, str]]:
            """Whether there's a cycle in a directed graph"""
            path = set()

            def visit(vertex: str) -> Optional[Tuple[str, str]]:
                path.add(vertex)
                for neighbour in g.get(vertex, ()):
                    if neighbour in path or visit(neighbour):
                        return (vertex, neighbour)
                path.remove(vertex)
                return None

            for v in g:
                cycle = visit(v)
                if cycle:
                    return cycle
            return None

        cycle = find_cycle(hierarchy)
        if cycle:
            raise QueryObjectValidationError(
                _(
                    "There's a loop in your Sankey, please provide a tree. "
                    "Here's a faulty link: {}"
                ).format(cycle)
            )
        return recs