本文整理汇总了Python中flask_babel.lazy_gettext方法的典型用法代码示例。如果您正苦于以下问题:Python flask_babel.lazy_gettext方法的具体用法?Python flask_babel.lazy_gettext怎么用?Python flask_babel.lazy_gettext使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flask_babel
的用法示例。
在下文中一共展示了flask_babel.lazy_gettext方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_product
# 需要导入模块: import flask_babel [as 别名]
# 或者: from flask_babel import lazy_gettext [as 别名]
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)
示例2: create_category
# 需要导入模块: import flask_babel [as 别名]
# 或者: from flask_babel import lazy_gettext [as 别名]
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)
示例3: timesince
# 需要导入模块: import flask_babel [as 别名]
# 或者: from flask_babel import lazy_gettext [as 别名]
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
示例4: init_app
# 需要导入模块: import flask_babel [as 别名]
# 或者: from flask_babel import lazy_gettext [as 别名]
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)
示例5: user_password
# 需要导入模块: import flask_babel [as 别名]
# 或者: from flask_babel import lazy_gettext [as 别名]
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"))
示例6: create_user
# 需要导入模块: import flask_babel [as 别名]
# 或者: from flask_babel import lazy_gettext [as 别名]
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"))
示例7: remove
# 需要导入模块: import flask_babel [as 别名]
# 或者: from flask_babel import lazy_gettext [as 别名]
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()
示例8: check_extra
# 需要导入模块: import flask_babel [as 别名]
# 或者: from flask_babel import lazy_gettext [as 别名]
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,
)
)
示例9: validate_sqlatable
# 需要导入模块: import flask_babel [as 别名]
# 或者: from flask_babel import lazy_gettext [as 别名]
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))
)
示例10: profile
# 需要导入模块: import flask_babel [as 别名]
# 或者: from flask_babel import lazy_gettext [as 别名]
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
),
)
示例11: query_obj
# 需要导入模块: import flask_babel [as 别名]
# 或者: from flask_babel import lazy_gettext [as 别名]
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
示例12: get_data
# 需要导入模块: import flask_babel [as 别名]
# 或者: from flask_babel import lazy_gettext [as 别名]
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
示例13: run_extra_queries
# 需要导入模块: import flask_babel [as 别名]
# 或者: from flask_babel import lazy_gettext [as 别名]
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
示例14: query_obj
# 需要导入模块: import flask_babel [as 别名]
# 或者: from flask_babel import lazy_gettext [as 别名]
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
示例15: pre_validate
# 需要导入模块: import flask_babel [as 别名]
# 或者: from flask_babel import lazy_gettext [as 别名]
def pre_validate(self, form):
for v, _ in [(c.id, c.name) for c in Category.query.all()]:
if self.data == v:
break
else:
raise ValueError(self.gettext('Not a valid choice'))