sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1 value |
|---|---|---|
def get_form_context(self, obj, ns=None):
"""Return a dict: form instance, action button, submit url...
Used by macro m_tags_form(entity)
"""
return {
"url": url_for("entity_tags.edit", object_id=obj.id),
"form": self.entity_tags_form(obj)(obj=obj, ns=ns),
"buttons": [EDIT_BUTTON],
} | Return a dict: form instance, action button, submit url...
Used by macro m_tags_form(entity) | entailment |
def reindex(clear: bool, progressive: bool, batch_size: int):
"""Reindex all content; optionally clear index before.
All is done in asingle transaction by default.
:param clear: clear index content.
:param progressive: don't run in a single transaction.
:param batch_size: number of documents to process before writing to the
index. Unused in single transaction mode. If `None` then
all documents of same content type are written at once.
"""
reindexer = Reindexer(clear, progressive, batch_size)
reindexer.reindex_all() | Reindex all content; optionally clear index before.
All is done in asingle transaction by default.
:param clear: clear index content.
:param progressive: don't run in a single transaction.
:param batch_size: number of documents to process before writing to the
index. Unused in single transaction mode. If `None` then
all documents of same content type are written at once. | entailment |
def url_for_hit(hit, default="#"):
"""Helper for building URLs from results."""
try:
object_type = hit["object_type"]
object_id = int(hit["id"])
return current_app.default_view.url_for(hit, object_type, object_id)
except KeyError:
return default
except Exception:
logger.error("Error building URL for search result", exc_info=True)
return default | Helper for building URLs from results. | entailment |
def index_update(index, items):
"""
:param:index: index name
:param:items: list of (operation, full class name, primary key, data) tuples.
"""
index_name = index
index = service.app_state.indexes[index_name]
adapted = service.adapted
session = safe_session()
updated = set()
writer = AsyncWriter(index)
try:
for op, cls_name, pk, data in items:
if pk is None:
continue
# always delete. Whoosh manual says that 'update' is actually delete + add
# operation
object_key = f"{cls_name}:{pk}"
writer.delete_by_term("object_key", object_key)
adapter = adapted.get(cls_name)
if not adapter:
# FIXME: log to sentry?
continue
if object_key in updated:
# don't add twice the same document in same transaction. The writer will
# not delete previous records, ending in duplicate records for same
# document.
continue
if op in ("new", "changed"):
with session.begin(nested=True):
obj = adapter.retrieve(pk, _session=session, **data)
if obj is None:
# deleted after task queued, but before task run
continue
document = service.get_document(obj, adapter)
try:
writer.add_document(**document)
except ValueError:
# logger is here to give us more infos in order to catch a weird bug
# that happens regularly on CI but is not reliably
# reproductible.
logger.error("writer.add_document(%r)", document, exc_info=True)
raise
updated.add(object_key)
except Exception:
writer.cancel()
raise
session.close()
writer.commit()
try:
# async thread: wait for its termination
writer.join()
except RuntimeError:
# happens when actual writer was already available: asyncwriter didn't need
# to start a thread
pass | :param:index: index name
:param:items: list of (operation, full class name, primary key, data) tuples. | entailment |
def init_indexes(self):
"""Create indexes for schemas."""
state = self.app_state
for name, schema in self.schemas.items():
if current_app.testing:
storage = TestingStorage()
else:
index_path = (Path(state.whoosh_base) / name).absolute()
if not index_path.exists():
index_path.mkdir(parents=True)
storage = FileStorage(str(index_path))
if storage.index_exists(name):
index = FileIndex(storage, schema, name)
else:
index = FileIndex.create(storage, schema, name)
state.indexes[name] = index | Create indexes for schemas. | entailment |
def clear(self):
"""Remove all content from indexes, and unregister all classes.
After clear() the service is stopped. It must be started again
to create new indexes and register classes.
"""
logger.info("Resetting indexes")
state = self.app_state
for _name, idx in state.indexes.items():
writer = AsyncWriter(idx)
writer.commit(merge=True, optimize=True, mergetype=CLEAR)
state.indexes.clear()
state.indexed_classes.clear()
state.indexed_fqcn.clear()
self.clear_update_queue()
if self.running:
self.stop() | Remove all content from indexes, and unregister all classes.
After clear() the service is stopped. It must be started again
to create new indexes and register classes. | entailment |
def searchable_object_types(self):
"""List of (object_types, friendly name) present in the index."""
try:
idx = self.index()
except KeyError:
# index does not exists: service never started, may happens during
# tests
return []
with idx.reader() as r:
indexed = sorted(set(r.field_terms("object_type")))
app_indexed = self.app_state.indexed_fqcn
return [(name, friendly_fqcn(name)) for name in indexed if name in app_indexed] | List of (object_types, friendly name) present in the index. | entailment |
def search(
self,
q,
index="default",
fields=None,
Models=(),
object_types=(),
prefix=True,
facet_by_type=None,
**search_args,
):
"""Interface to search indexes.
:param q: unparsed search string.
:param index: name of index to use for search.
:param fields: optionnal mapping of field names -> boost factor?
:param Models: list of Model classes to limit search on.
:param object_types: same as `Models`, but directly the model string.
:param prefix: enable or disable search by prefix
:param facet_by_type: if set, returns a dict of object_type: results with a
max of `limit` matches for each type.
:param search_args: any valid parameter for
:meth:`whoosh.searching.Search.search`. This includes `limit`,
`groupedby` and `sortedby`
"""
index = self.app_state.indexes[index]
if not fields:
fields = self.default_search_fields
valid_fields = {
f
for f in index.schema.names(check_names=fields)
if prefix or not f.endswith("_prefix")
}
for invalid in set(fields) - valid_fields:
del fields[invalid]
parser = DisMaxParser(fields, index.schema)
query = parser.parse(q)
filters = search_args.setdefault("filter", None)
filters = [filters] if filters is not None else []
del search_args["filter"]
if not hasattr(g, "is_manager") or not g.is_manager:
# security access filter
user = current_user
roles = {indexable_role(user)}
if not user.is_anonymous:
roles.add(indexable_role(Anonymous))
roles.add(indexable_role(Authenticated))
roles |= {indexable_role(r) for r in security.get_roles(user)}
filter_q = wq.Or(
[wq.Term("allowed_roles_and_users", role) for role in roles]
)
filters.append(filter_q)
object_types = set(object_types)
for m in Models:
object_type = m.entity_type
if not object_type:
continue
object_types.add(object_type)
if object_types:
object_types &= self.app_state.indexed_fqcn
else:
# ensure we don't show content types previously indexed but not yet
# cleaned from index
object_types = self.app_state.indexed_fqcn
# limit object_type
filter_q = wq.Or([wq.Term("object_type", t) for t in object_types])
filters.append(filter_q)
for func in self.app_state.search_filter_funcs:
filter_q = func()
if filter_q is not None:
filters.append(filter_q)
if filters:
filter_q = wq.And(filters) if len(filters) > 1 else filters[0]
# search_args['filter'] = filter_q
query = filter_q & query
if facet_by_type:
if not object_types:
object_types = [t[0] for t in self.searchable_object_types()]
# limit number of documents to score, per object type
collapse_limit = 5
search_args["groupedby"] = "object_type"
search_args["collapse"] = "object_type"
search_args["collapse_limit"] = collapse_limit
search_args["limit"] = search_args["collapse_limit"] * max(
len(object_types), 1
)
with index.searcher(closereader=False) as searcher:
# 'closereader' is needed, else results cannot by used outside 'with'
# statement
results = searcher.search(query, **search_args)
if facet_by_type:
positions = {
doc_id: pos
for pos, doc_id in enumerate(i[1] for i in results.top_n)
}
sr = results
results = {}
for typename, doc_ids in sr.groups("object_type").items():
results[typename] = [
sr[positions[oid]] for oid in doc_ids[:collapse_limit]
]
return results | Interface to search indexes.
:param q: unparsed search string.
:param index: name of index to use for search.
:param fields: optionnal mapping of field names -> boost factor?
:param Models: list of Model classes to limit search on.
:param object_types: same as `Models`, but directly the model string.
:param prefix: enable or disable search by prefix
:param facet_by_type: if set, returns a dict of object_type: results with a
max of `limit` matches for each type.
:param search_args: any valid parameter for
:meth:`whoosh.searching.Search.search`. This includes `limit`,
`groupedby` and `sortedby` | entailment |
def register_class(self, cls, app_state=None):
"""Register a model class."""
state = app_state if app_state is not None else self.app_state
for Adapter in self.adapters_cls:
if Adapter.can_adapt(cls):
break
else:
return
cls_fqcn = fqcn(cls)
self.adapted[cls_fqcn] = Adapter(cls, self.schemas["default"])
state.indexed_classes.add(cls)
state.indexed_fqcn.add(cls_fqcn) | Register a model class. | entailment |
def after_commit(self, session):
"""Any db updates go through here.
We check if any of these models have ``__searchable__`` fields,
indicating they need to be indexed. With these we update the
whoosh index for the model. If no index exists, it will be
created here; this could impose a penalty on the initial commit
of a model.
"""
if (
not self.running
or session.transaction.nested # inside a sub-transaction:
# not yet written in DB
or session is not db.session()
):
# note: we have not tested too far if session is enclosed in a transaction
# at connection level. For now it's not a standard use case, it would most
# likely happens during tests (which don't do that for now)
return
primary_field = "id"
state = self.app_state
items = []
for op, obj in state.to_update:
model_name = fqcn(obj.__class__)
if model_name not in self.adapted or not self.adapted[model_name].indexable:
# safeguard
continue
# safeguard against DetachedInstanceError
if sa.orm.object_session(obj) is not None:
items.append((op, model_name, getattr(obj, primary_field), {}))
if items:
index_update.apply_async(kwargs={"index": "default", "items": items})
self.clear_update_queue() | Any db updates go through here.
We check if any of these models have ``__searchable__`` fields,
indicating they need to be indexed. With these we update the
whoosh index for the model. If no index exists, it will be
created here; this could impose a penalty on the initial commit
of a model. | entailment |
def index_objects(self, objects, index="default"):
"""Bulk index a list of objects."""
if not objects:
return
index_name = index
index = self.app_state.indexes[index_name]
indexed = set()
with index.writer() as writer:
for obj in objects:
document = self.get_document(obj)
if document is None:
continue
object_key = document["object_key"]
if object_key in indexed:
continue
writer.delete_by_term("object_key", object_key)
try:
writer.add_document(**document)
except ValueError:
# logger is here to give us more infos in order to catch a weird bug
# that happens regularly on CI but is not reliably
# reproductible.
logger.error("writer.add_document(%r)", document, exc_info=True)
raise
indexed.add(object_key) | Bulk index a list of objects. | entailment |
def linkify_url(value):
"""Tranform an URL pulled from the database to a safe HTML fragment."""
value = value.strip()
rjs = r"[\s]*(&#x.{1,7})?".join(list("javascript:"))
rvb = r"[\s]*(&#x.{1,7})?".join(list("vbscript:"))
re_scripts = re.compile(f"({rjs})|({rvb})", re.IGNORECASE)
value = re_scripts.sub("", value)
url = value
if not url.startswith("http://") and not url.startswith("https://"):
url = "http://" + url
url = parse.urlsplit(url).geturl()
if '"' in url:
url = url.split('"')[0]
if "<" in url:
url = url.split("<")[0]
if value.startswith("http://"):
value = value[len("http://") :]
elif value.startswith("https://"):
value = value[len("https://") :]
if value.count("/") == 1 and value.endswith("/"):
value = value[0:-1]
return '<a href="{}">{}</a> <i class="fa fa-external-link"></i>'.format(
url, value
) | Tranform an URL pulled from the database to a safe HTML fragment. | entailment |
def get_preferences(self, user=None):
"""Return a string->value dictionnary representing the given user
preferences.
If no user is provided, the current user is used instead.
"""
if user is None:
user = current_user
return {pref.key: pref.value for pref in user.preferences} | Return a string->value dictionnary representing the given user
preferences.
If no user is provided, the current user is used instead. | entailment |
def set_preferences(self, user=None, **kwargs):
"""Set preferences from keyword arguments."""
if user is None:
user = current_user
d = {pref.key: pref for pref in user.preferences}
for k, v in kwargs.items():
if k in d:
d[k].value = v
else:
d[k] = UserPreference(user=user, key=k, value=v)
db.session.add(d[k]) | Set preferences from keyword arguments. | entailment |
def manager(self, obj):
"""Returns the :class:`AttachmentsManager` instance for this object."""
manager = getattr(obj, _MANAGER_ATTR, None)
if manager is None:
manager = AttachmentsManager()
setattr(obj.__class__, _MANAGER_ATTR, manager)
return manager | Returns the :class:`AttachmentsManager` instance for this object. | entailment |
def get_form_context(self, obj):
"""Return a dict: form instance, action button, submit url...
Used by macro m_attachment_form(entity)
"""
return {
"url": url_for("attachments.create", entity_id=obj.id),
"form": self.Form(),
"buttons": [UPLOAD_BUTTON],
} | Return a dict: form instance, action button, submit url...
Used by macro m_attachment_form(entity) | entailment |
def do_access_control(self):
"""`before_request` handler to check if user should be redirected to
login page."""
from abilian.services import get_service
if current_app.testing and current_app.config.get("NO_LOGIN"):
# Special case for tests
user = User.query.get(0)
login_user(user, force=True)
return
state = self.app_state
user = unwrap(current_user)
# Another special case for tests
if current_app.testing and getattr(user, "is_admin", False):
return
security = get_service("security")
user_roles = frozenset(security.get_roles(user))
endpoint = request.endpoint
blueprint = request.blueprint
access_controllers = []
access_controllers.extend(state.bp_access_controllers.get(None, []))
if blueprint and blueprint in state.bp_access_controllers:
access_controllers.extend(state.bp_access_controllers[blueprint])
if endpoint and endpoint in state.endpoint_access_controllers:
access_controllers.extend(state.endpoint_access_controllers[endpoint])
for access_controller in reversed(access_controllers):
verdict = access_controller(user=user, roles=user_roles)
if verdict is None:
continue
elif verdict is True:
return
else:
if user.is_anonymous:
return self.redirect_to_login()
raise Forbidden()
# default policy
if current_app.config.get("PRIVATE_SITE") and user.is_anonymous:
return self.redirect_to_login() | `before_request` handler to check if user should be redirected to
login page. | entailment |
def get_entities_for_reindex(tags):
"""Collect entities for theses tags."""
if isinstance(tags, Tag):
tags = (tags,)
session = db.session()
indexing = get_service("indexing")
tbl = Entity.__table__
tag_ids = [t.id for t in tags]
query = (
sa.sql.select([tbl.c.entity_type, tbl.c.id])
.select_from(tbl.join(entity_tag_tbl, entity_tag_tbl.c.entity_id == tbl.c.id))
.where(entity_tag_tbl.c.tag_id.in_(tag_ids))
)
entities = set()
with session.no_autoflush:
for entity_type, entity_id in session.execute(query):
if entity_type not in indexing.adapted:
logger.debug("%r is not indexed, skipping", entity_type)
item = ("changed", entity_type, entity_id, ())
entities.add(item)
return entities | Collect entities for theses tags. | entailment |
def schedule_entities_reindex(entities):
"""
:param entities: as returned by :func:`get_entities_for_reindex`
"""
entities = [(e[0], e[1], e[2], dict(e[3])) for e in entities]
return index_update.apply_async(kwargs={"index": "default", "items": entities}) | :param entities: as returned by :func:`get_entities_for_reindex` | entailment |
def scan(self, file_or_stream):
"""
:param file_or_stream: :class:`Blob` instance, filename or file object
:returns: True if file is 'clean', False if a virus is detected, None if
file could not be scanned.
If `file_or_stream` is a Blob, scan result is stored in
Blob.meta['antivirus'].
"""
if not clamd:
return None
res = self._scan(file_or_stream)
if isinstance(file_or_stream, Blob):
file_or_stream.meta["antivirus"] = res
return res | :param file_or_stream: :class:`Blob` instance, filename or file object
:returns: True if file is 'clean', False if a virus is detected, None if
file could not be scanned.
If `file_or_stream` is a Blob, scan result is stored in
Blob.meta['antivirus']. | entailment |
def check_output(*args, **kwargs):
'''Compatibility wrapper for Python 2.6 missin g subprocess.check_output'''
if hasattr(subprocess, 'check_output'):
return subprocess.check_output(stderr=subprocess.STDOUT, universal_newlines=True,
*args, **kwargs)
else:
process = subprocess.Popen(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
universal_newlines=True, **kwargs)
output, _ = process.communicate()
retcode = process.poll()
if retcode:
error = subprocess.CalledProcessError(retcode, args[0])
error.output = output
raise error
return output | Compatibility wrapper for Python 2.6 missin g subprocess.check_output | entailment |
def init_object(self, args, kwargs):
"""This method is reponsible for setting :attr:`obj`.
It is called during :meth:`prepare_args`.
"""
self.object_id = kwargs.pop(self.pk, None)
if self.object_id is not None:
self.obj = self.Model.query.get(self.object_id)
actions.context["object"] = self.obj
return args, kwargs | This method is reponsible for setting :attr:`obj`.
It is called during :meth:`prepare_args`. | entailment |
def prepare_args(self, args, kwargs):
"""
:attr:`form` is initialized here. See also :meth:`View.prepare_args`.
"""
args, kwargs = super().prepare_args(args, kwargs)
form_kwargs = self.get_form_kwargs()
self.form = self.Form(**form_kwargs)
return args, kwargs | :attr:`form` is initialized here. See also :meth:`View.prepare_args`. | entailment |
def form_valid(self, redirect_to=None):
"""Save object.
Called when form is validated.
:param redirect_to: real url (created with url_for) to redirect to,
instead of the view by default.
"""
session = db.session()
with session.no_autoflush:
self.before_populate_obj()
self.form.populate_obj(self.obj)
session.add(self.obj)
self.after_populate_obj()
try:
session.flush()
self.send_activity()
session.commit()
except ValidationError as e:
rv = self.handle_commit_exception(e)
if rv is not None:
return rv
session.rollback()
flash(str(e), "error")
return self.get()
except sa.exc.IntegrityError as e:
rv = self.handle_commit_exception(e)
if rv is not None:
return rv
session.rollback()
logger.error(e)
flash(_("An entity with this name already exists in the system."), "error")
return self.get()
else:
self.commit_success()
flash(self.message_success(), "success")
if redirect_to:
return redirect(redirect_to)
else:
return self.redirect_to_view() | Save object.
Called when form is validated.
:param redirect_to: real url (created with url_for) to redirect to,
instead of the view by default. | entailment |
def get_item(self, obj):
"""Return a result item.
:param obj: Instance object
:returns: a dictionnary with at least `id` and `text` values
"""
return {"id": obj.id, "text": self.get_label(obj), "name": obj.name} | Return a result item.
:param obj: Instance object
:returns: a dictionnary with at least `id` and `text` values | entailment |
def pip(name):
'''Parse requirements file'''
with io.open(os.path.join('requirements', '{0}.pip'.format(name))) as f:
return f.readlines() | Parse requirements file | entailment |
def convert(self, blob, size=500):
"""Size is the maximum horizontal size."""
file_list = []
with make_temp_file(blob) as in_fn, make_temp_file() as out_fn:
try:
subprocess.check_call(["pdftoppm", "-jpeg", in_fn, out_fn])
file_list = sorted(glob.glob(f"{out_fn}-*.jpg"))
converted_images = []
for fn in file_list:
converted = resize(open(fn, "rb").read(), size, size)
converted_images.append(converted)
return converted_images
except Exception as e:
raise ConversionError("pdftoppm failed") from e
finally:
for fn in file_list:
try:
os.remove(fn)
except OSError:
pass | Size is the maximum horizontal size. | entailment |
def convert(self, blob, **kw):
"""Convert using unoconv converter."""
timeout = self.run_timeout
with make_temp_file(blob) as in_fn, make_temp_file(
prefix="tmp-unoconv-", suffix=".pdf"
) as out_fn:
args = ["-f", "pdf", "-o", out_fn, in_fn]
# Hack for my Mac, FIXME later
if Path("/Applications/LibreOffice.app/Contents/program/python").exists():
cmd = [
"/Applications/LibreOffice.app/Contents/program/python",
"/usr/local/bin/unoconv",
] + args
else:
cmd = [self.unoconv] + args
def run_uno():
try:
self._process = subprocess.Popen(
cmd, close_fds=True, cwd=bytes(self.tmp_dir)
)
self._process.communicate()
except Exception as e:
logger.error("run_uno error: %s", bytes(e), exc_info=True)
raise ConversionError("unoconv failed") from e
run_thread = threading.Thread(target=run_uno)
run_thread.start()
run_thread.join(timeout)
try:
if run_thread.is_alive():
# timeout reached
self._process.terminate()
if self._process.poll() is not None:
try:
self._process.kill()
except OSError:
logger.warning("Failed to kill process %s", self._process)
self._process = None
raise ConversionError(f"Conversion timeout ({timeout})")
converted = open(out_fn).read()
return converted
finally:
self._process = None | Convert using unoconv converter. | entailment |
def convert(self, blob, **kw):
"""Convert using soffice converter."""
timeout = self.run_timeout
with make_temp_file(blob) as in_fn:
cmd = [self.soffice, "--headless", "--convert-to", "pdf", in_fn]
# # TODO: fix this if needed, or remove if not needed
# if os.path.exists(
# "/Applications/LibreOffice.app/Contents/program/python"):
# cmd = [
# '/Applications/LibreOffice.app/Contents/program/python',
# '/usr/local/bin/unoconv', '-f', 'pdf', '-o', out_fn, in_fn
# ]
def run_soffice():
try:
self._process = subprocess.Popen(
cmd, close_fds=True, cwd=bytes(self.tmp_dir)
)
self._process.communicate()
except Exception as e:
logger.error("soffice error: %s", bytes(e), exc_info=True)
raise ConversionError("soffice conversion failed") from e
run_thread = threading.Thread(target=run_soffice)
run_thread.start()
run_thread.join(timeout)
try:
if run_thread.is_alive():
# timeout reached
self._process.terminate()
if self._process.poll() is not None:
try:
self._process.kill()
except OSError:
logger.warning("Failed to kill process %s", self._process)
self._process = None
raise ConversionError(f"Conversion timeout ({timeout})")
out_fn = os.path.splitext(in_fn)[0] + ".pdf"
converted = open(out_fn, "rb").read()
return converted
finally:
self._process = None | Convert using soffice converter. | entailment |
def autoescape(filter_func):
"""Decorator to autoescape result from filters."""
@evalcontextfilter
@wraps(filter_func)
def _autoescape(eval_ctx, *args, **kwargs):
result = filter_func(*args, **kwargs)
if eval_ctx.autoescape:
result = Markup(result)
return result
return _autoescape | Decorator to autoescape result from filters. | entailment |
def paragraphs(value):
"""Blank lines delimitates paragraphs."""
result = "\n\n".join(
"<p>{}</p>".format(p.strip().replace("\n", Markup("<br />\n")))
for p in _PARAGRAPH_RE.split(escape(value))
)
return result | Blank lines delimitates paragraphs. | entailment |
def roughsize(size, above=20, mod=10):
"""6 -> '6' 15 -> '15' 134 -> '130+'."""
if size < above:
return str(size)
return "{:d}+".format(size - size % mod) | 6 -> '6' 15 -> '15' 134 -> '130+'. | entailment |
def datetimeparse(s):
"""Parse a string date time to a datetime object.
Suitable for dates serialized with .isoformat()
:return: None, or an aware datetime instance, tz=UTC.
"""
try:
dt = dateutil.parser.parse(s)
except ValueError:
return None
return utc_dt(dt) | Parse a string date time to a datetime object.
Suitable for dates serialized with .isoformat()
:return: None, or an aware datetime instance, tz=UTC. | entailment |
def age(dt, now=None, add_direction=True, date_threshold=None):
"""
:param dt: :class:`datetime<datetime.datetime>` instance to format
:param now: :class:`datetime<datetime.datetime>` instance to compare to `dt`
:param add_direction: if `True`, will add "in" or "ago" (example for `en`
locale) to time difference `dt - now`, i.e "in 9 min." or " 9min. ago"
:param date_threshold: above threshold, will use a formated date instead of
elapsed time indication. Supported values: "day".
"""
# Fail silently for now XXX
if not dt:
return ""
if not now:
now = datetime.datetime.utcnow()
locale = babel.get_locale()
dt = utc_dt(dt)
now = utc_dt(now)
delta = dt - now
if date_threshold is not None:
dy, dw, dd = dt_cal = dt.isocalendar()
ny, nw, nd = now_cal = now.isocalendar()
if dt_cal != now_cal:
# not same day
remove_year = dy == ny
date_fmt = locale.date_formats["long"].pattern
time_fmt = locale.time_formats["short"].pattern
fmt = locale.datetime_formats["medium"]
if remove_year:
date_fmt = date_fmt.replace("y", "").strip()
# remove leading or trailing spaces, comma, etc...
date_fmt = re.sub("^[^A-Za-z]*|[^A-Za-z]*$", "", date_fmt)
fmt = fmt.format(time_fmt, date_fmt)
return babel.format_datetime(dt, format=fmt)
# don't use (flask.ext.)babel.format_timedelta: as of Flask-Babel 0.9 it
# doesn't support "threshold" arg.
return format_timedelta(
delta,
locale=locale,
granularity="minute",
threshold=0.9,
add_direction=add_direction,
) | :param dt: :class:`datetime<datetime.datetime>` instance to format
:param now: :class:`datetime<datetime.datetime>` instance to compare to `dt`
:param add_direction: if `True`, will add "in" or "ago" (example for `en`
locale) to time difference `dt - now`, i.e "in 9 min." or " 9min. ago"
:param date_threshold: above threshold, will use a formated date instead of
elapsed time indication. Supported values: "day". | entailment |
def babel2datepicker(pattern):
"""Convert date format from babel (http://babel.pocoo.org/docs/dates/#date-
fields)) to a format understood by bootstrap-datepicker."""
if not isinstance(pattern, DateTimePattern):
pattern = parse_pattern(pattern)
map_fmt = {
# days
"d": "dd",
"dd": "dd",
"EEE": "D",
"EEEE": "DD",
"EEEEE": "D", # narrow name => short name
# months
"M": "mm",
"MM": "mm",
"MMM": "M",
"MMMM": "MM",
# years
"y": "yyyy",
"yy": "yyyy",
"yyy": "yyyy",
"yyyy": "yyyy",
# time picker format
# hours
"h": "%I",
"hh": "%I",
"H": "%H",
"HH": "%H",
# minutes,
"m": "%M",
"mm": "%M",
# seconds
"s": "%S",
"ss": "%S",
# am/pm
"a": "%p",
}
return pattern.format % map_fmt | Convert date format from babel (http://babel.pocoo.org/docs/dates/#date-
fields)) to a format understood by bootstrap-datepicker. | entailment |
def start(self, ignore_state=False):
"""Starts the service."""
self.logger.debug("Start service")
self._toggle_running(True, ignore_state) | Starts the service. | entailment |
def stop(self, ignore_state=False):
"""Stops the service."""
self.logger.debug("Stop service")
self._toggle_running(False, ignore_state) | Stops the service. | entailment |
def app_state(self):
"""Current service state in current application.
:raise:RuntimeError if working outside application context.
"""
try:
return current_app.extensions[self.name]
except KeyError:
raise ServiceNotRegistered(self.name) | Current service state in current application.
:raise:RuntimeError if working outside application context. | entailment |
def if_running(meth):
"""Decorator for service methods that must be ran only if service is in
running state."""
@wraps(meth)
def check_running(self, *args, **kwargs):
if not self.running:
return
return meth(self, *args, **kwargs)
return check_running | Decorator for service methods that must be ran only if service is in
running state. | entailment |
def clean(self):
'''Clean the workspace'''
if self.config.clean:
logger.info('Cleaning')
self.execute(self.config.clean) | Clean the workspace | entailment |
def publish(self):
'''Publish the current release to PyPI'''
if self.config.publish:
logger.info('Publish')
self.execute(self.config.publish) | Publish the current release to PyPI | entailment |
def header(text):
'''Display an header'''
print(' '.join((blue('>>'), cyan(text))))
sys.stdout.flush() | Display an header | entailment |
def info(text, *args, **kwargs):
'''Display informations'''
text = text.format(*args, **kwargs)
print(' '.join((purple('>>>'), text)))
sys.stdout.flush() | Display informations | entailment |
def success(text):
'''Display a success message'''
print(' '.join((green('✔'), white(text))))
sys.stdout.flush() | Display a success message | entailment |
def error(text):
'''Display an error message'''
print(red('✘ {0}'.format(text)))
sys.stdout.flush() | Display an error message | entailment |
def clean(ctx):
'''Cleanup all build artifacts'''
header(clean.__doc__)
with ctx.cd(ROOT):
for pattern in CLEAN_PATTERNS:
info(pattern)
ctx.run('rm -rf {0}'.format(' '.join(CLEAN_PATTERNS))) | Cleanup all build artifacts | entailment |
def deps(ctx):
'''Install or update development dependencies'''
header(deps.__doc__)
with ctx.cd(ROOT):
ctx.run('pip install -r requirements/develop.pip -r requirements/doc.pip', pty=True) | Install or update development dependencies | entailment |
def qa(ctx):
'''Run a quality report'''
header(qa.__doc__)
with ctx.cd(ROOT):
info('Python Static Analysis')
flake8_results = ctx.run('flake8 bumpr', pty=True, warn=True)
if flake8_results.failed:
error('There is some lints to fix')
else:
success('No lint to fix')
info('Ensure PyPI can render README and CHANGELOG')
readme_results = ctx.run('python setup.py check -r -s', pty=True, warn=True, hide=True)
if readme_results.failed:
print(readme_results.stdout)
error('README and/or CHANGELOG is not renderable by PyPI')
else:
success('README and CHANGELOG are renderable by PyPI')
if flake8_results.failed or readme_results.failed:
exit('Quality check failed', flake8_results.return_code or readme_results.return_code)
success('Quality check OK') | Run a quality report | entailment |
def doc(ctx):
'''Build the documentation'''
header(doc.__doc__)
with ctx.cd(os.path.join(ROOT, 'doc')):
ctx.run('make html', pty=True)
success('Documentation available in doc/_build/html') | Build the documentation | entailment |
def completion(ctx):
'''Generate bash completion script'''
header(completion.__doc__)
with ctx.cd(ROOT):
ctx.run('_bumpr_COMPLETE=source bumpr > bumpr-complete.sh', pty=True)
success('Completion generated in bumpr-complete.sh') | Generate bash completion script | entailment |
def _check_view_permission(self, view):
"""
:param view: a :class:`ObjectView` class or instance
"""
security = get_service("security")
return security.has_permission(current_user, view.permission, self.obj) | :param view: a :class:`ObjectView` class or instance | entailment |
def register(cls):
"""Register an :class:`~.Entity` as a taggable class.
Can be used as a class decorator:
.. code-block:: python
@tag.register
class MyContent(Entity):
....
"""
if not issubclass(cls, Entity):
raise ValueError("Class must be a subclass of abilian.core.entities.Entity")
SupportTagging.register(cls)
return cls | Register an :class:`~.Entity` as a taggable class.
Can be used as a class decorator:
.. code-block:: python
@tag.register
class MyContent(Entity):
.... | entailment |
def supports_tagging(obj):
"""
:param obj: a class or instance
"""
if isinstance(obj, type):
return issubclass(obj, SupportTagging)
if not isinstance(obj, SupportTagging):
return False
if obj.id is None:
return False
return True | :param obj: a class or instance | entailment |
def register(cls):
"""Register an :class:`~.Entity` as a attachmentable class.
Can be used as a class decorator:
.. code-block:: python
@attachment.register
class MyContent(Entity):
....
"""
if not issubclass(cls, Entity):
raise ValueError("Class must be a subclass of abilian.core.entities.Entity")
SupportAttachment.register(cls)
return cls | Register an :class:`~.Entity` as a attachmentable class.
Can be used as a class decorator:
.. code-block:: python
@attachment.register
class MyContent(Entity):
.... | entailment |
def supports_attachments(obj):
"""
:param obj: a class or instance
:returns: True is obj supports attachments.
"""
if isinstance(obj, type):
return issubclass(obj, SupportAttachment)
if not isinstance(obj, SupportAttachment):
return False
if obj.id is None:
return False
return True | :param obj: a class or instance
:returns: True is obj supports attachments. | entailment |
def for_entity(obj, check_support_attachments=False):
"""Return attachments on an entity."""
if check_support_attachments and not supports_attachments(obj):
return []
return getattr(obj, ATTRIBUTE) | Return attachments on an entity. | entailment |
def strip_label(mapper, connection, target):
"""Strip labels at ORM level so the unique=True means something."""
if target.label is not None:
target.label = target.label.strip() | Strip labels at ORM level so the unique=True means something. | entailment |
def _before_insert(mapper, connection, target):
"""Set item to last position if position not defined."""
if target.position is None:
func = sa.sql.func
stmt = sa.select([func.coalesce(func.max(mapper.mapped_table.c.position), -1)])
target.position = connection.execute(stmt).scalar() + 1 | Set item to last position if position not defined. | entailment |
def by_label(self, label):
"""Like `.get()`, but by label."""
# don't use .first(), so that MultipleResultsFound can be raised
try:
return self.filter_by(label=label).one()
except sa.orm.exc.NoResultFound:
return None | Like `.get()`, but by label. | entailment |
def by_position(self, position):
"""Like `.get()`, but by position number."""
# don't use .first(), so that MultipleResultsFound can be raised
try:
return self.filter_by(position=position).one()
except sa.orm.exc.NoResultFound:
return None | Like `.get()`, but by position number. | entailment |
def _remove_session_save_objects(self):
"""Used during exception handling in case we need to remove() session:
keep instances and merge them in the new session.
"""
if self.testing:
return
# Before destroying the session, get all instances to be attached to the
# new session. Without this, we get DetachedInstance errors, like when
# tryin to get user's attribute in the error page...
old_session = db.session()
g_objs = []
for key in iter(g):
obj = getattr(g, key)
if isinstance(obj, db.Model) and sa.orm.object_session(obj) in (
None,
old_session,
):
g_objs.append((key, obj, obj in old_session.dirty))
db.session.remove()
session = db.session()
for key, obj, load in g_objs:
# replace obj instance in bad session by new instance in fresh
# session
setattr(g, key, session.merge(obj, load=load))
# refresh `current_user`
user = getattr(_request_ctx_stack.top, "user", None)
if user is not None and isinstance(user, db.Model):
_request_ctx_stack.top.user = session.merge(user, load=load) | Used during exception handling in case we need to remove() session:
keep instances and merge them in the new session. | entailment |
def log_exception(self, exc_info):
"""Log exception only if Sentry is not used (this avoids getting error
twice in Sentry)."""
dsn = self.config.get("SENTRY_DSN")
if not dsn:
super().log_exception(exc_info) | Log exception only if Sentry is not used (this avoids getting error
twice in Sentry). | entailment |
def init_sentry(self):
"""Install Sentry handler if config defines 'SENTRY_DSN'."""
dsn = self.config.get("SENTRY_DSN")
if not dsn:
return
try:
import sentry_sdk
except ImportError:
logger.error(
'SENTRY_DSN is defined in config but package "sentry-sdk"'
" is not installed."
)
return
from sentry_sdk.integrations.flask import FlaskIntegration
sentry_sdk.init(dsn=dsn, integrations=[FlaskIntegration()]) | Install Sentry handler if config defines 'SENTRY_DSN'. | entailment |
def install_default_handler(self, http_error_code):
"""Install a default error handler for `http_error_code`.
The default error handler renders a template named error404.html
for http_error_code 404.
"""
logger.debug(
"Set Default HTTP error handler for status code %d", http_error_code
)
handler = partial(self.handle_http_error, http_error_code)
self.errorhandler(http_error_code)(handler) | Install a default error handler for `http_error_code`.
The default error handler renders a template named error404.html
for http_error_code 404. | entailment |
def handle_http_error(self, code, error):
"""Helper that renders `error{code}.html`.
Convenient way to use it::
from functools import partial
handler = partial(app.handle_http_error, code)
app.errorhandler(code)(handler)
"""
# 5xx code: error on server side
if (code // 100) == 5:
# ensure rollback if needed, else error page may
# have an error, too, resulting in raw 500 page :-(
db.session.rollback()
template = f"error{code:d}.html"
return render_template(template, error=error), code | Helper that renders `error{code}.html`.
Convenient way to use it::
from functools import partial
handler = partial(app.handle_http_error, code)
app.errorhandler(code)(handler) | entailment |
def register(self, entity, url_func):
"""Associate a `url_func` with entity's type.
:param:entity: an :class:`abilian.core.extensions.db.Model` class or
instance.
:param:url_func: any callable that accepts an entity instance and
return an url for it.
"""
if not inspect.isclass(entity):
entity = entity.__class__
assert issubclass(entity, db.Model)
self._map[entity.entity_type] = url_func | Associate a `url_func` with entity's type.
:param:entity: an :class:`abilian.core.extensions.db.Model` class or
instance.
:param:url_func: any callable that accepts an entity instance and
return an url for it. | entailment |
def url_for(self, entity=None, object_type=None, object_id=None, **kwargs):
"""Return canonical view URL for given entity instance.
If no view has been registered the registry will try to find an
endpoint named with entity's class lowercased followed by '.view'
and that accepts `object_id=entity.id` to generates an url.
:param entity: a instance of a subclass of
:class:`abilian.core.extensions.db.Model`,
:class:`whoosh.searching.Hit` or :class:`python:dict`
:param object_id: if `entity` is not an instance, this parameter
must be set to target id. This is usefull when you know the type and
id of an object but don't want to retrieve it from DB.
:raise KeyError: if no view can be found for the given entity.
"""
if object_type is None:
assert isinstance(entity, (db.Model, Hit, dict))
getter = attrgetter if isinstance(entity, db.Model) else itemgetter
object_id = getter("id")(entity)
object_type = getter("object_type")(entity)
url_func = self._map.get(object_type) # type: Optional[Callable]
if url_func is not None:
return url_func(entity, object_type, object_id, **kwargs)
try:
return url_for(
"{}.view".format(object_type.rsplit(".")[-1].lower()),
object_id=object_id,
**kwargs
)
except Exception:
raise KeyError(object_type) | Return canonical view URL for given entity instance.
If no view has been registered the registry will try to find an
endpoint named with entity's class lowercased followed by '.view'
and that accepts `object_id=entity.id` to generates an url.
:param entity: a instance of a subclass of
:class:`abilian.core.extensions.db.Model`,
:class:`whoosh.searching.Hit` or :class:`python:dict`
:param object_id: if `entity` is not an instance, this parameter
must be set to target id. This is usefull when you know the type and
id of an object but don't want to retrieve it from DB.
:raise KeyError: if no view can be found for the given entity. | entailment |
def file(self):
"""Return :class:`pathlib.Path` object used for storing value."""
from abilian.services.repository import session_repository as repository
return repository.get(self, self.uuid) | Return :class:`pathlib.Path` object used for storing value. | entailment |
def value(self):
# type: () -> bytes
"""Binary value content."""
v = self.file
return v.open("rb").read() if v is not None else v | Binary value content. | entailment |
def value(self, value, encoding="utf-8"):
"""Store binary content to applications's repository and update
`self.meta['md5']`.
:param:content: string, bytes, or any object with a `read()` method
:param:encoding: encoding to use when content is Unicode
"""
from abilian.services.repository import session_repository as repository
repository.set(self, self.uuid, value)
self.meta["md5"] = str(hashlib.md5(self.value).hexdigest())
if hasattr(value, "filename"):
filename = value.filename
if isinstance(filename, bytes):
filename = filename.decode("utf-8")
self.meta["filename"] = filename
if hasattr(value, "content_type"):
self.meta["mimetype"] = value.content_type | Store binary content to applications's repository and update
`self.meta['md5']`.
:param:content: string, bytes, or any object with a `read()` method
:param:encoding: encoding to use when content is Unicode | entailment |
def value(self):
"""Remove value from repository."""
from abilian.services.repository import session_repository as repository
repository.delete(self, self.uuid) | Remove value from repository. | entailment |
def md5(self):
"""Return md5 from meta, or compute it if absent."""
md5 = self.meta.get("md5")
if md5 is None:
md5 = str(hashlib.md5(self.value).hexdigest())
return md5 | Return md5 from meta, or compute it if absent. | entailment |
def forgotten_pw(new_user=False):
"""Reset password for users who have already activated their accounts."""
email = request.form.get("email", "").lower()
action = request.form.get("action")
if action == "cancel":
return redirect(url_for("login.login_form"))
if not email:
flash(_("You must provide your email address."), "error")
return render_template("login/forgotten_password.html")
try:
user = User.query.filter(
sql.func.lower(User.email) == email, User.can_login == True
).one()
except NoResultFound:
flash(
_("Sorry, we couldn't find an account for " "email '{email}'.").format(
email=email
),
"error",
)
return render_template("login/forgotten_password.html"), 401
if user.can_login and not user.password:
user.set_password(random_password())
db.session.commit()
send_reset_password_instructions(user)
flash(
_("Password reset instructions have been sent to your email address."), "info"
)
return redirect(url_for("login.login_form")) | Reset password for users who have already activated their accounts. | entailment |
def send_reset_password_instructions(user):
# type: (User) -> None
"""Send the reset password instructions email for the specified user.
:param user: The user to send the instructions to
"""
token = generate_reset_password_token(user)
url = url_for("login.reset_password", token=token)
reset_link = request.url_root[:-1] + url
subject = _("Password reset instruction for {site_name}").format(
site_name=current_app.config.get("SITE_NAME")
)
mail_template = "password_reset_instructions"
send_mail(subject, user.email, mail_template, user=user, reset_link=reset_link) | Send the reset password instructions email for the specified user.
:param user: The user to send the instructions to | entailment |
def generate_reset_password_token(user):
# type: (User) -> Any
"""Generate a unique reset password token for the specified user.
:param user: The user to work with
"""
data = [str(user.id), md5(user.password)]
return get_serializer("reset").dumps(data) | Generate a unique reset password token for the specified user.
:param user: The user to work with | entailment |
def send_mail(subject, recipient, template, **context):
"""Send an email using the Flask-Mail extension.
:param subject: Email subject
:param recipient: Email recipient
:param template: The name of the email template
:param context: The context to render the template with
"""
config = current_app.config
sender = config["MAIL_SENDER"]
msg = Message(subject, sender=sender, recipients=[recipient])
template_name = f"login/email/{template}.txt"
msg.body = render_template_i18n(template_name, **context)
# msg.html = render_template('%s/%s.html' % ctx, **context)
mail = current_app.extensions.get("mail")
current_app.logger.debug("Sending mail...")
mail.send(msg) | Send an email using the Flask-Mail extension.
:param subject: Email subject
:param recipient: Email recipient
:param template: The name of the email template
:param context: The context to render the template with | entailment |
def register_plugin(self, name):
"""Load and register a plugin given its package name."""
logger.info("Registering plugin: " + name)
module = importlib.import_module(name)
module.register_plugin(self) | Load and register a plugin given its package name. | entailment |
def register_plugins(self):
"""Load plugins listed in config variable 'PLUGINS'."""
registered = set()
for plugin_fqdn in chain(self.APP_PLUGINS, self.config["PLUGINS"]):
if plugin_fqdn not in registered:
self.register_plugin(plugin_fqdn)
registered.add(plugin_fqdn) | Load plugins listed in config variable 'PLUGINS'. | entailment |
def init_breadcrumbs(self):
"""Insert the first element in breadcrumbs.
This happens during `request_started` event, which is triggered
before any url_value_preprocessor and `before_request` handlers.
"""
g.breadcrumb.append(BreadcrumbItem(icon="home", url="/" + request.script_root)) | Insert the first element in breadcrumbs.
This happens during `request_started` event, which is triggered
before any url_value_preprocessor and `before_request` handlers. | entailment |
def check_instance_folder(self, create=False):
"""Verify instance folder exists, is a directory, and has necessary
permissions.
:param:create: if `True`, creates directory hierarchy
:raises: OSError with relevant errno if something is wrong.
"""
path = Path(self.instance_path)
err = None
eno = 0
if not path.exists():
if create:
logger.info("Create instance folder: %s", path)
path.mkdir(0o775, parents=True)
else:
err = "Instance folder does not exists"
eno = errno.ENOENT
elif not path.is_dir():
err = "Instance folder is not a directory"
eno = errno.ENOTDIR
elif not os.access(str(path), os.R_OK | os.W_OK | os.X_OK):
err = 'Require "rwx" access rights, please verify permissions'
eno = errno.EPERM
if err:
raise OSError(eno, err, str(path)) | Verify instance folder exists, is a directory, and has necessary
permissions.
:param:create: if `True`, creates directory hierarchy
:raises: OSError with relevant errno if something is wrong. | entailment |
def init_extensions(self):
"""Initialize flask extensions, helpers and services."""
extensions.redis.init_app(self)
extensions.mail.init_app(self)
extensions.deferred_js.init_app(self)
extensions.upstream_info.extension.init_app(self)
actions.init_app(self)
# auth_service installs a `before_request` handler (actually it's
# flask-login). We want to authenticate user ASAP, so that sentry and
# logs can report which user encountered any error happening later,
# in particular in a before_request handler (like csrf validator)
auth_service.init_app(self)
# webassets
self.setup_asset_extension()
self.register_base_assets()
# Babel (for i18n)
babel = abilian.i18n.babel
# Temporary (?) workaround
babel.locale_selector_func = None
babel.timezone_selector_func = None
babel.init_app(self)
babel.add_translations("wtforms", translations_dir="locale", domain="wtforms")
babel.add_translations("abilian")
babel.localeselector(abilian.i18n.localeselector)
babel.timezoneselector(abilian.i18n.timezoneselector)
# Flask-Migrate
Migrate(self, db)
# CSRF by default
if self.config.get("WTF_CSRF_ENABLED"):
extensions.csrf.init_app(self)
self.extensions["csrf"] = extensions.csrf
extensions.abilian_csrf.init_app(self)
self.register_blueprint(csrf.blueprint)
# images blueprint
from .web.views.images import blueprint as images_bp
self.register_blueprint(images_bp)
# Abilian Core services
security_service.init_app(self)
repository_service.init_app(self)
session_repository_service.init_app(self)
audit_service.init_app(self)
index_service.init_app(self)
activity_service.init_app(self)
preferences_service.init_app(self)
conversion_service.init_app(self)
vocabularies_service.init_app(self)
antivirus.init_app(self)
from .web.preferences.user import UserPreferencesPanel
preferences_service.register_panel(UserPreferencesPanel(), self)
from .web.coreviews import users
self.register_blueprint(users.blueprint)
# Admin interface
Admin().init_app(self)
# Celery async service
# this allows all shared tasks to use this celery app
if getattr(self, "celery_app_cls", None):
celery_app = self.extensions["celery"] = self.celery_app_cls()
# force reading celery conf now - default celery app will
# also update our config with default settings
celery_app.conf # noqa
celery_app.set_default()
# dev helper
if self.debug:
# during dev, one can go to /http_error/403 to see rendering of 403
http_error_pages = Blueprint("http_error_pages", __name__)
@http_error_pages.route("/<int:code>")
def error_page(code):
"""Helper for development to show 403, 404, 500..."""
abort(code)
self.register_blueprint(http_error_pages, url_prefix="/http_error") | Initialize flask extensions, helpers and services. | entailment |
def add_url_rule(self, rule, endpoint=None, view_func=None, roles=None, **options):
"""See :meth:`Flask.add_url_rule`.
If `roles` parameter is present, it must be a
:class:`abilian.service.security.models.Role` instance, or a list of
Role instances.
"""
super().add_url_rule(rule, endpoint, view_func, **options)
if roles:
self.add_access_controller(
endpoint, allow_access_for_roles(roles), endpoint=True
) | See :meth:`Flask.add_url_rule`.
If `roles` parameter is present, it must be a
:class:`abilian.service.security.models.Role` instance, or a list of
Role instances. | entailment |
def add_access_controller(self, name: str, func: Callable, endpoint: bool = False):
"""Add an access controller.
If `name` is None it is added at application level, else if is
considered as a blueprint name. If `endpoint` is True then it is
considered as an endpoint.
"""
auth_state = self.extensions[auth_service.name]
adder = auth_state.add_bp_access_controller
if endpoint:
adder = auth_state.add_endpoint_access_controller
if not isinstance(name, str):
msg = "{} is not a valid endpoint name".format(repr(name))
raise ValueError(msg)
adder(name, func) | Add an access controller.
If `name` is None it is added at application level, else if is
considered as a blueprint name. If `endpoint` is True then it is
considered as an endpoint. | entailment |
def add_static_url(self, url_path, directory, endpoint=None, roles=None):
"""Add a new url rule for static files.
:param url_path: subpath from application static url path. No heading
or trailing slash.
:param directory: directory to serve content from.
:param endpoint: flask endpoint name for this url rule.
Example::
app.add_static_url('myplugin',
'/path/to/myplugin/resources',
endpoint='myplugin_static')
With default setup it will serve content from directory
`/path/to/myplugin/resources` from url `http://.../static/myplugin`
"""
url_path = self.static_url_path + "/" + url_path + "/<path:filename>"
self.add_url_rule(
url_path,
endpoint=endpoint,
view_func=partial(send_file_from_directory, directory=directory),
roles=roles,
)
self.add_access_controller(
endpoint, allow_access_for_roles(Anonymous), endpoint=True
) | Add a new url rule for static files.
:param url_path: subpath from application static url path. No heading
or trailing slash.
:param directory: directory to serve content from.
:param endpoint: flask endpoint name for this url rule.
Example::
app.add_static_url('myplugin',
'/path/to/myplugin/resources',
endpoint='myplugin_static')
With default setup it will serve content from directory
`/path/to/myplugin/resources` from url `http://.../static/myplugin` | entailment |
def _message_send(self, connection):
"""Send a single message instance.
If TESTING is True the message will not actually be sent.
:param self: a Message instance.
"""
sender = current_app.config["MAIL_SENDER"]
if not self.extra_headers:
self.extra_headers = {}
self.extra_headers["Sender"] = sender
connection.send(self, sender) | Send a single message instance.
If TESTING is True the message will not actually be sent.
:param self: a Message instance. | entailment |
def _filter_metadata_for_connection(target, connection, **kw):
"""Listener to control what indexes get created.
Useful for skipping postgres-specific indexes on a sqlite for example.
It's looking for info entry `engines` on an index
(`Index(info=dict(engines=['postgresql']))`), an iterable of engine names.
"""
engine = connection.engine.name
default_engines = (engine,)
tables = target if isinstance(target, sa.Table) else kw.get("tables", [])
for table in tables:
indexes = list(table.indexes)
for idx in indexes:
if engine not in idx.info.get("engines", default_engines):
table.indexes.remove(idx) | Listener to control what indexes get created.
Useful for skipping postgres-specific indexes on a sqlite for example.
It's looking for info entry `engines` on an index
(`Index(info=dict(engines=['postgresql']))`), an iterable of engine names. | entailment |
def url_for(obj, **kw):
"""Polymorphic variant of Flask's `url_for` function.
Behaves like the original function when the first argument is a
string. When it's an object, it
"""
if isinstance(obj, str):
return flask_url_for(obj, **kw)
try:
return current_app.default_view.url_for(obj, **kw)
except KeyError:
if hasattr(obj, "_url"):
return obj._url
elif hasattr(obj, "url"):
return obj.url
raise BuildError(repr(obj), kw, "GET") | Polymorphic variant of Flask's `url_for` function.
Behaves like the original function when the first argument is a
string. When it's an object, it | entailment |
def send_file_from_directory(filename, directory, app=None):
"""Helper to add static rules, like in `abilian.app`.app.
Example use::
app.add_url_rule(
app.static_url_path + '/abilian/<path:filename>',
endpoint='abilian_static',
view_func=partial(send_file_from_directory,
directory='/path/to/static/files/dir'))
"""
if app is None:
app = current_app
cache_timeout = app.get_send_file_max_age(filename)
return send_from_directory(directory, filename, cache_timeout=cache_timeout) | Helper to add static rules, like in `abilian.app`.app.
Example use::
app.add_url_rule(
app.static_url_path + '/abilian/<path:filename>',
endpoint='abilian_static',
view_func=partial(send_file_from_directory,
directory='/path/to/static/files/dir')) | entailment |
def get_model_changes(
entity_type, year=None, month=None, day=None, hour=None, since=None
):
# type: (Text, int, int, int, int, datetime) -> Query
"""Get models modified at the given date with the Audit service.
:param entity_type: string like "extranet_medicen.apps.crm.models.Compte".
Beware the typo, there won't be a warning message.
:param since: datetime
:param year: int
:param month: int
:param day: int
:param hour: int
:returns: a query object
"""
query = AuditEntry.query
if since:
query = query.filter(AuditEntry.happened_at >= since)
if year:
query = query.filter(extract("year", AuditEntry.happened_at) == year)
if month:
query = query.filter(extract("month", AuditEntry.happened_at) == month)
if day:
query = query.filter(extract("day", AuditEntry.happened_at) == day)
if hour:
query = query.filter(extract("hour", AuditEntry.happened_at) == hour)
query = query.filter(AuditEntry.entity_type.like(entity_type)).order_by(
AuditEntry.happened_at
)
return query | Get models modified at the given date with the Audit service.
:param entity_type: string like "extranet_medicen.apps.crm.models.Compte".
Beware the typo, there won't be a warning message.
:param since: datetime
:param year: int
:param month: int
:param day: int
:param hour: int
:returns: a query object | entailment |
def get_columns_diff(changes):
"""Add the changed columns as a diff attribute.
- changes: a list of changes (get_model_changes query.all())
Return: the same list, to which elements we added a "diff"
attribute containing the changed columns. Diff defaults to [].
"""
for change in changes:
change.diff = []
elt_changes = change.get_changes()
if elt_changes:
change.diff = elt_changes.columns
return changes | Add the changed columns as a diff attribute.
- changes: a list of changes (get_model_changes query.all())
Return: the same list, to which elements we added a "diff"
attribute containing the changed columns. Diff defaults to []. | entailment |
def _has_argument(func):
"""Test whether a function expects an argument.
:param func:
The function to be tested for existence of an argument.
"""
if hasattr(inspect, 'signature'):
# New way in python 3.3
sig = inspect.signature(func)
return bool(sig.parameters)
else:
# Old way
return bool(inspect.getargspec(func).args) | Test whether a function expects an argument.
:param func:
The function to be tested for existence of an argument. | entailment |
def make_site(cls,
searchpath="templates",
outpath=".",
contexts=None,
rules=None,
encoding="utf8",
followlinks=True,
extensions=None,
staticpaths=None,
filters=None,
env_globals=None,
env_kwargs=None,
mergecontexts=False):
"""Create a :class:`Site <Site>` object.
:param searchpath:
A string representing the absolute path to the directory that the
Site should search to discover templates. Defaults to
``'templates'``.
If a relative path is provided, it will be coerced to an absolute
path by prepending the directory name of the calling module. For
example, if you invoke staticjinja using ``python build.py`` in
directory ``/foo``, then *searchpath* will be ``/foo/templates``.
:param outpath:
A string representing the name of the directory that the Site
should store rendered files in. Defaults to ``'.'``.
:param contexts:
A list of *(regex, context)* pairs. The Site will render templates
whose name match *regex* using *context*. *context* must be either
a dictionary-like object or a function that takes either no
arguments or a single :class:`jinja2.Template` as an argument and
returns a dictionary representing the context. Defaults to ``[]``.
:param rules:
A list of *(regex, function)* pairs. The Site will delegate
rendering to *function* if *regex* matches the name of a template
during rendering. *function* must take a
:class:`jinja2.Environment` object, a filename, and a context as
parameters and render the template. Defaults to ``[]``.
:param encoding:
A string representing the encoding that the Site should use when
rendering templates. Defaults to ``'utf8'``.
:param followlinks:
A boolean describing whether symlinks in searchpath should be
followed or not. Defaults to ``True``.
:param extensions:
A list of :ref:`Jinja extensions <jinja-extensions>` that the
:class:`jinja2.Environment` should use. Defaults to ``[]``.
:param staticpaths:
List of directories to get static files from (relative to
searchpath). Defaults to ``None``.
:param filters:
A dictionary of Jinja2 filters to add to the Environment. Defaults
to ``{}``.
:param env_globals:
A mapping from variable names that should be available all the time
to their values. Defaults to ``{}``.
:param env_kwargs:
A dictionary that will be passed as keyword arguments to the
jinja2 Environment. Defaults to ``{}``.
:param mergecontexts:
A boolean value. If set to ``True``, then all matching regex from
the contexts list will be merged (in order) to get the final
context. Otherwise, only the first matching regex is used.
Defaults to ``False``.
"""
# Coerce search to an absolute path if it is not already
if not os.path.isabs(searchpath):
# TODO: Determine if there is a better way to write do this
calling_module = inspect.getmodule(inspect.stack()[-1][0])
# Absolute path to project
project_path = os.path.realpath(os.path.dirname(
calling_module.__file__))
searchpath = os.path.join(project_path, searchpath)
if env_kwargs is None:
env_kwargs = {}
env_kwargs['loader'] = FileSystemLoader(searchpath=searchpath,
encoding=encoding,
followlinks=followlinks)
env_kwargs.setdefault('extensions', extensions or [])
environment = Environment(**env_kwargs)
if filters:
environment.filters.update(filters)
if env_globals:
environment.globals.update(env_globals)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler())
return cls(environment,
searchpath=searchpath,
outpath=outpath,
encoding=encoding,
logger=logger,
rules=rules,
contexts=contexts,
staticpaths=staticpaths,
mergecontexts=mergecontexts,
) | Create a :class:`Site <Site>` object.
:param searchpath:
A string representing the absolute path to the directory that the
Site should search to discover templates. Defaults to
``'templates'``.
If a relative path is provided, it will be coerced to an absolute
path by prepending the directory name of the calling module. For
example, if you invoke staticjinja using ``python build.py`` in
directory ``/foo``, then *searchpath* will be ``/foo/templates``.
:param outpath:
A string representing the name of the directory that the Site
should store rendered files in. Defaults to ``'.'``.
:param contexts:
A list of *(regex, context)* pairs. The Site will render templates
whose name match *regex* using *context*. *context* must be either
a dictionary-like object or a function that takes either no
arguments or a single :class:`jinja2.Template` as an argument and
returns a dictionary representing the context. Defaults to ``[]``.
:param rules:
A list of *(regex, function)* pairs. The Site will delegate
rendering to *function* if *regex* matches the name of a template
during rendering. *function* must take a
:class:`jinja2.Environment` object, a filename, and a context as
parameters and render the template. Defaults to ``[]``.
:param encoding:
A string representing the encoding that the Site should use when
rendering templates. Defaults to ``'utf8'``.
:param followlinks:
A boolean describing whether symlinks in searchpath should be
followed or not. Defaults to ``True``.
:param extensions:
A list of :ref:`Jinja extensions <jinja-extensions>` that the
:class:`jinja2.Environment` should use. Defaults to ``[]``.
:param staticpaths:
List of directories to get static files from (relative to
searchpath). Defaults to ``None``.
:param filters:
A dictionary of Jinja2 filters to add to the Environment. Defaults
to ``{}``.
:param env_globals:
A mapping from variable names that should be available all the time
to their values. Defaults to ``{}``.
:param env_kwargs:
A dictionary that will be passed as keyword arguments to the
jinja2 Environment. Defaults to ``{}``.
:param mergecontexts:
A boolean value. If set to ``True``, then all matching regex from
the contexts list will be merged (in order) to get the final
context. Otherwise, only the first matching regex is used.
Defaults to ``False``. | entailment |
def get_context(self, template):
"""Get the context for a template.
If no matching value is found, an empty context is returned.
Otherwise, this returns either the matching value if the value is
dictionary-like or the dictionary returned by calling it with
*template* if the value is a function.
If several matching values are found, the resulting dictionaries will
be merged before being returned if mergecontexts is True. Otherwise,
only the first matching value is returned.
:param template: the template to get the context for
"""
context = {}
for regex, context_generator in self.contexts:
if re.match(regex, template.name):
if inspect.isfunction(context_generator):
if _has_argument(context_generator):
context.update(context_generator(template))
else:
context.update(context_generator())
else:
context.update(context_generator)
if not self.mergecontexts:
break
return context | Get the context for a template.
If no matching value is found, an empty context is returned.
Otherwise, this returns either the matching value if the value is
dictionary-like or the dictionary returned by calling it with
*template* if the value is a function.
If several matching values are found, the resulting dictionaries will
be merged before being returned if mergecontexts is True. Otherwise,
only the first matching value is returned.
:param template: the template to get the context for | entailment |
def get_rule(self, template_name):
"""Find a matching compilation rule for a function.
Raises a :exc:`ValueError` if no matching rule can be found.
:param template_name: the name of the template
"""
for regex, render_func in self.rules:
if re.match(regex, template_name):
return render_func
raise ValueError("no matching rule") | Find a matching compilation rule for a function.
Raises a :exc:`ValueError` if no matching rule can be found.
:param template_name: the name of the template | entailment |
def is_static(self, filename):
"""Check if a file is a static file (which should be copied, rather
than compiled using Jinja2).
A file is considered static if it lives in any of the directories
specified in ``staticpaths``.
:param filename: the name of the file to check
"""
if self.staticpaths is None:
# We're not using static file support
return False
for path in self.staticpaths:
if filename.startswith(path):
return True
return False | Check if a file is a static file (which should be copied, rather
than compiled using Jinja2).
A file is considered static if it lives in any of the directories
specified in ``staticpaths``.
:param filename: the name of the file to check | entailment |
def is_partial(self, filename):
"""Check if a file is a partial.
Partial files are not rendered, but they are used in rendering
templates.
A file is considered a partial if it or any of its parent directories
are prefixed with an ``'_'``.
:param filename: the name of the file to check
"""
return any((x.startswith("_") for x in filename.split(os.path.sep))) | Check if a file is a partial.
Partial files are not rendered, but they are used in rendering
templates.
A file is considered a partial if it or any of its parent directories
are prefixed with an ``'_'``.
:param filename: the name of the file to check | entailment |
def is_template(self, filename):
"""Check if a file is a template.
A file is a considered a template if it is neither a partial nor
ignored.
:param filename: the name of the file to check
"""
if self.is_partial(filename):
return False
if self.is_ignored(filename):
return False
if self.is_static(filename):
return False
return True | Check if a file is a template.
A file is a considered a template if it is neither a partial nor
ignored.
:param filename: the name of the file to check | entailment |
def _ensure_dir(self, template_name):
"""Ensure the output directory for a template exists."""
head = os.path.dirname(template_name)
if head:
file_dirpath = os.path.join(self.outpath, head)
if not os.path.exists(file_dirpath):
os.makedirs(file_dirpath) | Ensure the output directory for a template exists. | entailment |
def render_template(self, template, context=None, filepath=None):
"""Render a single :class:`jinja2.Template` object.
If a Rule matching the template is found, the rendering task is
delegated to the rule.
:param template:
A :class:`jinja2.Template` to render.
:param context:
Optional. A dictionary representing the context to render
*template* with. If no context is provided, :meth:`get_context` is
used to provide a context.
:param filepath:
Optional. A file or file-like object to dump the complete template
stream into. Defaults to to ``os.path.join(self.outpath,
template.name)``.
"""
self.logger.info("Rendering %s..." % template.name)
if context is None:
context = self.get_context(template)
if not os.path.exists(self.outpath):
os.makedirs(self.outpath)
self._ensure_dir(template.name)
try:
rule = self.get_rule(template.name)
except ValueError:
if filepath is None:
filepath = os.path.join(self.outpath, template.name)
template.stream(**context).dump(filepath, self.encoding)
else:
rule(self, template, **context) | Render a single :class:`jinja2.Template` object.
If a Rule matching the template is found, the rendering task is
delegated to the rule.
:param template:
A :class:`jinja2.Template` to render.
:param context:
Optional. A dictionary representing the context to render
*template* with. If no context is provided, :meth:`get_context` is
used to provide a context.
:param filepath:
Optional. A file or file-like object to dump the complete template
stream into. Defaults to to ``os.path.join(self.outpath,
template.name)``. | entailment |
def render_templates(self, templates, filepath=None):
"""Render a collection of :class:`jinja2.Template` objects.
:param templates:
A collection of Templates to render.
:param filepath:
Optional. A file or file-like object to dump the complete template
stream into. Defaults to to ``os.path.join(self.outpath,
template.name)``.
"""
for template in templates:
self.render_template(template, filepath) | Render a collection of :class:`jinja2.Template` objects.
:param templates:
A collection of Templates to render.
:param filepath:
Optional. A file or file-like object to dump the complete template
stream into. Defaults to to ``os.path.join(self.outpath,
template.name)``. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.