endi.views package

Subpackages

Submodules

endi.views.auth module

endi.views.auth.includeme(config)

endi.views.commercial module

Commercial Management module

class endi.views.commercial.DisplayCommercialHandling(context, request)

Bases : BaseView

Commercial handling view Allows to get commercial informations by year through GET Allows to set turnover projections through POST

customers()

Return the number of real customers (with invoices) for the current year

estimations()

Query for estimations

form_schema = <endi.forms.commercial.CommercialSetFormSchema object at 140624215313936 (named )>
get_year_form()

Return the year selection form

submit_success(appstruct)

Add/Edit a turnover projection in the database

submit_year()

Validate the year form datas

property title
turnover_projections()

Return a query for turnover projections

turnovers()

Return the realised turnovers

validated_estimations()

Query for estimations where an invoice has been generated

year_form_schema = <endi.forms.commercial.CommercialFormSchema object at 140624215313744 (named )>
endi.views.commercial.compute_turnover_difference(index, projections, turnovers)

Compute the difference beetween the projection and the real value

endi.views.commercial.compute_turnover_percent(index, projections, turnovers)

Compute the percent the difference represents

endi.views.commercial.get_current_url(request)

return the current url with arguments

endi.views.commercial.get_form(counter)

Return the form for turnover projection configuration

endi.views.commercial.get_month_range(month, year)

Return month range enclosing the current month

endi.views.commercial.get_year_range(year)

Return year range enclosing the current year

endi.views.commercial.includeme(config)

endi.views.competence module

Competence evaluation module

1- Choose a deadline (if manager choose also a contractor) 2- Fill the displayed grid 3- Display a printable version

class endi.views.competence.RestCompetenceGrid(context, request=None)

Bases : BaseView

Json api for competence grid handling

get()
class endi.views.competence.RestCompetenceGridItem(context, request=None)

Bases : BaseRestView

Rest view for Item handling

Provides :

  • get collection

  • edit element

collection_get()

Return list of items for a given grid context is a grid

property schema
class endi.views.competence.RestCompetenceGridSubItem(context, request=None)

Bases : BaseRestView

Rest view for Sub item handling:

Provides:

  • get collection

  • edit element

collection_get()

Return list of subitems for a given item context is an item

property schema
endi.views.competence.add_routes(config)

Add module related routes

endi.views.competence.competence_form_options(context, request)

Returns datas used to build the competence form page

endi.views.competence.competence_grid_view(context, request)

The competence grid base view

endi.views.competence.competence_index_view(context, request)

Index view to go to a competence grid

Both admin and user view

Paramètres:

request (obj) – The pyramid request

endi.views.competence.competence_radar_chart_datas(context, request)

Return the datas used to show a radar / spider chart of a user’s competences context : CompetenceGrid

endi.views.competence.competence_radar_chart_view(context, request)

Competence radar chart view

Paramètres:

context (obj) – a user model

endi.views.competence.get_competence_grid(request, contractor_id, deadline_id)

Return a competence grid record for the given user and deadline

endi.views.competence.includeme(config)

Pyramid’s inclusion mechanism

endi.views.competence.redirect_to_competence_grid(request, appstruct)

Redirect to the appropriate competence grid

endi.views.competence.validate_competence_grid_query(request)

Validate datas posted to access a competence grid

Paramètres:

request (obj) – The pyramid request

endi.views.csv_import module

endi.views.holiday module

Simple stuff for handling holidays declaration/view

class endi.views.holiday.AdminHolidayView(request)

Bases : BaseFormView

Holiday search/consultation views

schema = <endi.forms.holiday.SearchHolidaysSchema object at 140624478881744 (named )>

Colander schema instance to be used to create the form instance. Provide your schema in your derived class.

submit_success(appstruct)
title = 'Les congés des entrepreneurs'
class endi.views.holiday.HolidayJson(model, bind_params=None)

Bases : RestJsonRepr

Wraps a holiday to a json representation

schema = <endi.forms.holiday.HolidaySchema object at 140624233330192 (named )>
class endi.views.holiday.RestHoliday(context, request=None)

Bases : BaseView

Json-Rest api for holidays handling /holidays/{id}

delete()

Rest delete method : delete a line

factory

alias de Holiday

get()

Rest get method : return a line

getOne()

get an holiday entry

model_wrapper

alias de HolidayJson

post()

Rest post method : add a line

put()

Rest put method : update a line

property schema
endi.views.holiday.add_routes(config)

Add module’s related routes

endi.views.holiday.get_holidays(start_date=None, end_date=None, user_id=None)

Return the user’s declared holidays

endi.views.holiday.holidays_json(request)

json view for holidays

endi.views.holiday.includeme(config)
endi.views.holiday.user_holidays_index(request)

Base view for holidays editing

endi.views.index module

Index view

endi.views.index.includeme(config)

Adding the index view on module inclusion

endi.views.index.index(request)

Index page

endi.views.indicators module

endi.views.indicators.includeme(config)

endi.views.job module

Job related pages

class endi.views.job.JobList(*args, **kwargs)

Bases : BaseListView

default_direction = 'desc'
default_sort = 'created_at'
filter_status(query, appstruct)
filter_type(query, appstruct)
query()

The main query, should be overrided by a subclass

schema = <endi.forms.lists.BaseListsSchema object at 140624215001680 (named )>
sort_columns = {'created_at': <sqlalchemy.orm.attributes.InstrumentedAttribute object>}
title = 'Historique des tâches'
endi.views.job.includeme(config)
endi.views.job.job_json_model_view(context, request)

Return a job as json datas, check if the job should be cancelled or not

endi.views.job.job_view(context, request)
Paramètres:
  • context (obj) – The job we want to watch

  • request (obj) – The pyramid request object

endi.views.job.make_stream_csv_by_key(job_key, filename)

Build a view streaming the key attr of the current context as a csv file

Paramètres:
  • job_key (str) – an attribute of the associated context

  • filename (str) – A filename used to stream the datas

endi.views.job.populate_actionmenu(request)

endi.views.json module

Json API views DEPRECATED

endi.views.json.includeme(config)

Configure the views for this module

endi.views.json.json_model_view(request)

Return a json representation of a model

endi.views.manage module

Manage view :
  • last documents page

class endi.views.manage.ShortcutButton(url, icon, text, title)

Bases : tuple

property icon

Alias for field number 1

property text

Alias for field number 2

property title

Alias for field number 3

property url

Alias for field number 0

endi.views.manage.includeme(config)
endi.views.manage.manage(request)

The manage view

endi.views.payment module

endi.views.payment.includeme(config)

endi.views.render_api module

render api, usefull functions usable inside templates

class endi.views.render_api.Api(context, request)

Bases : object

Api object passed to the templates hosting all commands we will use

static cancelinvoice_get_major_status(cinvoice)

Return the most significant status for the given task

static cancelinvoice_status_icon(cinvoice)

Return the name of the icon matching the status

static clean_html(text)

Return a sanitized version of an html code keeping essential html tags and allowing only a few attributes

static compile_template_str(template_string, template_context)

Compile the template string and merge the context

Paramètres:
  • template_string (str) – The string to templatize

  • template (dict) – templating context

Type renvoyé:

str

static custom_indicator_icon(indicator_name: str) str

Returns an icon identifier representing the type of the custom indicator

static doctype_icon(node)
static estimation_get_major_status(estimation)

Return the most significant status for the given task

static estimation_status_icon(estimation)

Return the name of the icon matching the status

file_url(fileobj)

Return the url to access the given fileobj

static format_account(account, reverse=True, upper=True)

return {firstname} {lastname}

static format_activity_status(activity)

Return a formatted status string for the given activity

static format_amount(amount, trim=True, grouping=True, precision=2, display_precision=None, html=True, currency=False)

return a pretty printable amount

Paramètres:
  • amount (int) – The amount to display

  • trim (bool) – Should the amount be trimmed

  • grouping (bool) – Should the amount be grouped (grouping form depends

on locales) :param int precision: The decimal precision to convert the amount to (Decimal amounts are stored as BigInteger in the database to avoid float precision conflicts and facilitate computation, here precision indicates with which 10**precision the conversion is made) :param int display_precision: The precision used to display the amount (trimming strategy)

static format_cancelinvoice_status(cinvoice, full=True)

Return a string representing the state of this cancelinvoice

Paramètres:

cinvoice (obj) – A CancelInvoice instance

static format_civilite(civilite_str)

Shorten the civilite string

Paramètres:

civilite_str (str) – Monsieur/Madame

Renvoie:

Mr/Mme

Type renvoyé:

str

static format_date(date, short=True)

return a pretty print version of the date object

static format_datetime(datetime_object, timeonly=False)

format a datetime object

static format_duration(duration, short=True)

return a pretty print version of a duration.

Paramètres:
  • duration ((int,int)) – hours,minutes tuple to convert.

  • short (bool) – if True, hide minutes part when it equals zero.

static format_estimation_status(estimation, full=True)

Return a formatted string for estimation specific status

static format_expense_status(expense, full=True)
static format_float(value, precision=None, grouping=True, html=True, wrap_decimals=False)
Format a float value :
  • Localized version with grouped values

  • trim datas to precision if asked for

Paramètres:
  • value (float) – The value to format

  • precision (int) – If set, the value will be trimmed to that precision

  • grouping (bool) – Should the datas be grouped (by thousands)

  • html (bool) – Should the resulting string be html-friendly (using

&nbsp;) :returns: A formatted string that can be used in html outputs :rtype: str

static format_indicator_main_status(indicator) str

Returns the main status of the given status

static format_indicator_status(status: str) str

Return a formatted status string for the given indicator

static format_invoice_status(invoice, full=True)

Return a formatted string for invoice specific status

Paramètres:

invoice (obj) – An invoice instance

static format_long_date(date: date, include_dayname: bool = True) str

Convert a date to a localized string

>>> import datetime
>>> d = datetime.date.today()
>>> format_long_date(d, include_name=True)
Jeudi 22 juin 2023
static format_long_date_with_name(date: date, include_dayname: bool = True) str

Convert a date to a localized string

>>> import datetime
>>> d = datetime.date.today()
>>> format_long_date(d, include_name=True)
Jeudi 22 juin 2023
static format_long_datetime(datetime_object: date, include_dayname: bool = True) str

Convert a datetime to a localized string

>>> import datetime
>>> d = datetime.datetime.now()
>>> format_long_datetime(d, include_dayname=True)
Jeudi 22 juin 2023 à 10h22
static format_name(firstname, lastname, reverse=True, upper=True)

format firstname and lastname in a common format

static format_paymentmode(paymentmode)

format payment modes for display Since #662 ( Permettre la configuration des modes de paiement ) no formatting is necessary

static format_quantity(quantity)

format the quantity

static format_short_date(date)

return a short printable version of the date obj

static format_status(element, full=True)
static format_status_sentence(element)

Same as format status but with a full sentence.

E.g.: « Cette note de dépenses a été validée. »

static format_status_string(status: StatusLogEntry, genre='')

Return a label for the given status

Paramètres:
  • code (str) – StatusLogEntry

  • genre (str) – “” or “e”

static format_supplier_invoice_status(supplier_invoice, full=True)
static format_task_type(task)
static groupby(elements: Iterable, attrname: str) Tuple[Any, Iterable]

Specialized version of itertools.groupby grouping on attribute

Note that for this to work, elements should be already ordered to allow grouping ; see itertools.groupby doc.

has_permission(perm_name, context=None)
static human_readable_filesize(size)

Return a human readable file size

icon(icon_name, css_classes='')

Crafts the HTML to include the named icon. :param icon_name: see https://endi.sophieweb.com/html/icones.html

img_url(fileobj)

Return the url to access the given fileobj as an image

static indicator_status_css(indicator) str

Return an icon representing the indicator status

static indicator_status_icon(indicator) str

Return an icon representing the indicator status

static invoice_get_major_status(invoice)

Return the most significant status for the given task

static invoice_status_icon(invoice)

Return the name of the icon matching the status

static major_status(element)
static month_name(index, capitalize=False)

Return the name of the month number « index »

overridable_label(label_key: str, context: Node) str

Gets a label, possibly overriden by db setting and/or frozen setting

static pluralize(collection, plural_mark='s', singular_mark='')

Helps handling the singular/plural forms of a word

>>> 'Simpson' + pluralize(['bart'])
'Simpson'
>>> 'Simpson' + pluralize(['homer', 'bart'])
'Simpsons'
>>> pluralize(['Jolly Jumper'], 'chevaux', 'cheval')
'cheval'
>>> 'chou' + 'pluralize(['rave'], 'x')
'chou'
Paramètres:

collection – list-like object

static remove_kms_training_zeros(amount)

Removed unnecessary kms amount training zeros :param amount: :return: amount

route_exists(module_name)

Check if a route is enabled/exists

Paramètres:

route_name (str) – The route name (first argument of add_route)

static short_month_name(index)

Return the short name of the month number « index »

static status_css_class(element)

Return a status css class for the element

Paramètres:

element (obj) – An instance of a SQLA model

static status_icon(element, status=None)
task_url(*args, **kwargs)

Build an url to access a task

Paramètres:
  • task – Task instance

  • _query (dict) – Query parameters

  • suffix (str) – Suffix to add after the id (.pdf or /move …)

  • api (bool) – Do we ask for api url

urlupdate(args_dict={})

Return the current url with updated GET params It allows to keep url params when : * sorting * searching * moving from one page to another

if current url ends with :

<url>?foo=1&bar=2

when passing {“foo”:5}, we get :

<url>?foo=5&bar=2

write_js_app_option(option_key: str, option_value: any) str

Build a js string for setting an AppOption key/value

Handle different value types so that they be set in the right format in js

>>> print(api.write_js_app_option("key", "value"))
AppOption["key"] = "value";
>>> print(api.write_js_app_option("key", 5))
AppOption["key"] = 5;
>>> print(api.write_js_app_option("key", True))
AppOption["key"] = true;
endi.views.render_api.build_icon_str(request, icon_name: str, css_classes: str = '') str

Crafts the HTML to include the named icon. :param icon_name: see https://endi.sophieweb.com/html/icones.html

endi.views.render_api.cancelinvoice_status_icon(cinvoice)

Return the name of the icon matching the status

endi.views.render_api.custom_indicator_icon(indicator_name: str) str

Returns an icon identifier representing the type of the custom indicator

endi.views.render_api.estimation_status_icon(estimation)

Return the name of the icon matching the status

endi.views.render_api.expense_status_css_class(expense)
endi.views.render_api.expense_status_icon(expense)

Return the name of the icon matching the status

endi.views.render_api.indicator_status_css(indicator) str

Return an icon representing the indicator status

endi.views.render_api.indicator_status_icon(indicator) str

Return an icon representing the indicator status

endi.views.render_api.invoice_status_icon(invoice)

Return the name of the icon matching the status

endi.views.render_api.sale_doctype_icon(node)
endi.views.render_api.status_css_class(element)

Return a status css class for the element

Paramètres:

element (obj) – An instance of a SQLA model

endi.views.render_api.status_icon(element, status=None)
endi.views.render_api.status_log_entry_icon(status_log_entry)
endi.views.render_api.supplier_invoice_status_icon(supplier_invoice)
endi.views.render_api.supplier_order_status_icon(supplier_order)

endi.views.rest_consts module

endi.views.rest_consts.config_rest_view(request)
endi.views.rest_consts.country_rest_view(request)
endi.views.rest_consts.department_rest_view(request)
endi.views.rest_consts.includeme(config)
endi.views.rest_consts.street_number_complements_rest_view(request)
endi.views.rest_consts.street_type_rest_view(request)

endi.views.static module

Custom views for dynamic static datas

endi.views.static.includeme(config)
endi.views.static.make_root_static_view(filename, ctype)

Return a static view rendering given file with headers set to the ctyp Content-Type

endi.views.tests module

endi.views.treasury_files module

Module contents

Base views with commonly used utilities

class endi.views.AsyncJobMixin

Bases : object

Helpers for the views launching and watching celery tasks

Handles popup views as well as regular views

initialize_job_result(job_class, **kwargs) Job

Record the empty job result to database

Paramètres:
  • job_class

  • kwargs – any kwargs, are passed to Job constuctor

is_celery_alive() Optional[Response]
redirect_to_job_watch(job, job_result)
show_error(msg: str, show_refresh_button=False) Response

Shows fatal error to user, and leaving/close page/popup

A refresh button may be shown (popup only).

class endi.views.BaseAddView(context, request=None)

Bases : BaseFormView

Admin view that should be subclassed adding a colanderalchemy schema

class AdminModel(BaseAddView):

schema = SQLAlchemySchemaNode(MyModel) model = MyModel

add_template_vars = ('title', 'help_msg')
create_instance()

Initiate a new instance

factory = None
property help_msg
merge_appstruct(appstruct, model)

Merge the appstruct with the newly create model

Paramètres:
  • appstruct (dict) – Validated form datas

  • model (obj) – A new instance of the object we create

Renvoie:

The model this view is supposed to add

msg = 'Vos modifications ont bien été enregistrées'
redirect_route = None
submit_success(appstruct)
class endi.views.BaseCsvView(*args, **kwargs)

Bases : BaseListClassWithForm

Base Csv view

A list view that returns a streamed file

A subclass should implement :

  • a query method

  • filename property

To be able to handle the rows that are streamed:

  • a _stream_rows method

If this view should support the GET params filtering method (export associated to a list view), a subclass should provide:

property filename

To be implemented by the subclass

model = None
writer

alias de SqlaCsvExporter

class endi.views.BaseEditView(context, request=None)

Bases : BaseFormView

ColanderAlchemy schema based view

class AdminModel(BaseEditView):

schema = SQLAlchemySchemaNode(MyModel)

Methods and attributes you can set

Form Schema related hooks

attribute schema

Form Schema to use in this form view Can be

a callable a class an instance of a schema

get_schema

add_template_vars = ('title', 'help_msg')
before(form)

Performs some processing on the form prior to rendering.

By default, this method does nothing. Override this method in your dervived class to modify the form. Your function will be executed immediately after instansiating the form instance in __call__() (thus before obtaining widget resources, considering buttons, or rendering).

cancel_success(appstruct)
get_context_model()

Return the model we’re editing, by default it’s the current context but in case of OneToOne relationship, it can be that the context is a related model, Overriding this method we can provide the model to edit

Renvoie:

The model that will be edited by this view

get_default_appstruct()

Collect datas that will initially populate the form

property help_msg
merge_appstruct(appstruct, model)

Merge the appstruct with current model

Paramètres:
  • appstruct (dict) – Validated form datas

  • model (obj) – A new instance of the object we create

Renvoie:

The model this view is supposed to add

msg = 'Vos modifications ont bien été enregistrées'
on_edit(appstruct, model)

Hook launched before the session is flushed

redirect_route = None
submit_success(appstruct)
class endi.views.BaseFormView(context, request=None)

Bases : FormView, PopupMixin

Allows to easily build form views

Attributes that you may override

add_template_vars

List of attribute names (or properties) that will be added to the result dict object and that you will be able to use in your templates ((“title”,) by default)

buttons

list or tupple of deform.Button objects (or strings), only a submit button is added by default

schema

colander form schema to be used to render our form you may also want to override get_schema method instead

form_class

form class to use (deform.Form by default)

Methods that your should implement

<button_name>_success(appstruct)

Is called when the form has been submitted and validated with the button called button_name.

appstruct : the colander validated datas (a dict)

Methods that you may implement

before(form)

Allows to execute some code before the validation process e.g: add datas to the form that will be rendered Will typically be overrided in an edit form.

form : the form object that’s used in our view

get_schema(): return the unbound schema to be used ; may be
preferred to schema attribute if you want something dynamic.
<button_name>_failure(e)

Is called when the form has been submitted the button called button_name and the datas have not been validated.

edeform.exception.ValidationFailure that has

been raised by colander

class MyFormView(BaseFormView):
    title = "My form view"
    schema = MyColanderSchema

    def before(self, form):
        form.set_appstruct(self.request.context.appstruct())

    def submit_success(self, appstruct):
        # Handle the filtered appstruct
add_template_vars = ()
before(form)

Performs some processing on the form prior to rendering.

By default, this method does nothing. Override this method in your dervived class to modify the form. Your function will be executed immediately after instansiating the form instance in __call__() (thus before obtaining widget resources, considering buttons, or rendering).

buttons = (<deform.form.Button object>,)

Tuple of buttons or strings to pass to the form instance. Override in your derived class.

form_label() str

Usefull optionnal tool used in multiform views (when we can add an element in different ways

Renvoie:

The name of the submitted form

Type renvoyé:

str

get_schema() Union[Schema, SQLAlchemySchemaNode]
schema = None

Colander schema instance to be used to create the form instance. Provide your schema in your derived class.

submit_failure(e)

Called by default when we failed to submit the values We add a token here for forms that are collapsed by default to keep them open if there is an error

title = None
use_csrf_token = False
class endi.views.BaseListClass(context, request=None)

Bases : BaseView

Base class for list related views (list view and exports)

  • It launches a query to retrieve records

  • Validates GET params regarding the given schema

  • filter the query with the provided filter_* methods

@param schema: Schema used to validate the GET params provided in the

url, the schema should inherit from endi.views.forms.lists.BaseListsSchema to preserve most of the processed automation

@param sort_columns: dict of {“sort_column_key”:”sort_column”…}.

Allows to generate the validator for the sort availabilities and to automatically add a order_by clause to the query. sort_column may be equal to Table.attribute if join clauses are present in the main query.

@default_sort: the default sort_column_key to be used @default_direction: the default sort direction (one of [“asc”, “desc”])

Subclass should provide
  • a view callable (either __call__() or a named method).

  • a _collect_appstruct() method

default_direction = 'asc'
default_sort = 'name'
query()

The main query, should be overrided by a subclass

schema = None
sort_columns = {'name': 'name'}
class endi.views.BaseListClassWithForm(*args, **kwargs)

Bases : BaseListClass

A list view, handling a search/filter form.

A subclass shoud provide at least a schema and a query method

dbsession: <sqlalchemy.orm.scoping.scoped_session object at 0x7fe5b76f0350>
filter_button_css = 'btn btn-primary icon only'
filter_button_icon = 'search'
filter_button_label = 'Lancer la recherche avec ces critères'
get_filter_button()

Return the definition of the filter button

get_form(schema)

Return the search form that should be used for this view

Paramètres:

schema (obj) – The form’s colander.Schema

Renvoie:

The form object

Type renvoyé:

obj

grid = None
request: Request
session: <InterfaceClass pyramid.interfaces.ISession>
set_form_widget(form)

Attach a custom widget to the given form

Paramètres:

form (obj) – The deform.Form instance

Renvoie:

The deform.Form instance

Type renvoyé:

obj

class endi.views.BaseListView(*args, **kwargs)

Bases : BaseListClassWithForm

A base list view used to provide an easy way to build list views Uses the BaseListClass and add the templating datas :

  • Provide a pagination object

  • Provide a search form based on the given schema

  • Launches complementary methods to populate request vars like popup

or actionmenu

@param add_template_vars: list of attributes (or properties)

that will be automatically added

add_template_vars = ()
dbsession: <sqlalchemy.orm.scoping.scoped_session object at 0x7fe5b76f0350>
grid = None
more_template_vars(response_dict)

Add template vars to the response dict List the attributes configured in the add_template_vars attribute and add them

populate_actionmenu(appstruct)

Used to populate an actionmenu (if there’s one in the page) actionmenu is a request attribute used to automate the integration of actionmenus in pages

request: Request
session: <InterfaceClass pyramid.interfaces.ISession>
use_paginate = True
class endi.views.BaseOdsView(*args, **kwargs)

Bases : BaseCsvView

dbsession: <sqlalchemy.orm.scoping.scoped_session object at 0x7fe5b76f0350>
request: Request
session: <InterfaceClass pyramid.interfaces.ISession>
writer

alias de SqlaOdsExporter

class endi.views.BaseRestView(context, request=None)

Bases : BaseView

A base rest view

provides the base structure for a rest view for sqlalchemy model access

it handles :

get delete put post requests

thanks to the colanderalchemy tools, we dynamically build the resulting model

Main Add/edit process:

1- get_schema 2- Hook : pre_format 3- create/update model 4- Hook : post_format 5- session.merge/session.add 6- Hook : after_flush

Following datas should be provided :

  • Attributes

    schema

    A colanderalchemy schema, it can be provided through a property or a simple attribute. For on the fly schema handling, you can also override the get_schema method that returns self.schema by default

The following could be provided

Methods

get_schema

See above comment

pre_format

Preformat submitted values before passing them to the form schema

post_format

Launched after the model has been created/updated and before add/merge

after_flush

Launched after the entry was added / merged in the session and flushed

For get method :

a « fields » parameter can be passed to get a subset of the context’s json data

GET /api/v1/estimations/125?fields=attachments&fields=description

NB : - Only attributes and properties can be retrieved that way - Unless what is done in the __json__ method, the data are returned without any

formatting

after_flush(entry, edit, attributes)

Allows to modify datas after the main entry was flushed

HTTP POST and PUT calls

Paramètres:
  • entry – The instance added/edited

  • edit (bool) – Is it an edition view ?

  • attributes (dict) – The validated submitted data

delete()

HTTP DELETE api endpoint

format_item_result(model) Union[dict, object]

Build the data to be returned by the api endpoint

Paramètres:

item – The current sqlalchemy Model

Renvoie:

An object with a __json__ method or a dict that can be json serialized

get()

End point for HTTP GET calls

get_editted_element(attributes)

Returns the element we edit

HTTP PUT calls

Paramètres:

attributes (dict) – The validated submitted data

get_posted_data()

Returns the data passed for a PUT/POST request Handle the case where we send multipart/form-data formatted data (case we send a file through ajax calls)

get_schema(submitted: dict) Union[SQLAlchemySchemaNode, Schema]

Build the colander schema to be used

Paramètres:

submitted – Data submitted to the api endpoint

Renvoie:

A form schema used to validate the submitted data

on_delete()
post()

HTTP POST api endpoint

post_format(entry, edit, attributes)

Allows to apply post formatting to the model before flushing it

HTTP POST and PUT calls

Paramètres:
  • entry – The instance added/edited

  • edit (bool) – Is it an edition view ?

  • attributes (dict) – The validated submitted data

pre_delete()
pre_format(datas, edit=False)

Allows to apply pre-formatting to the submitted datas

HTTP POST and PUT calls

Paramètres:
  • datas (dict) – The submitted datas

  • edit (bool) – Is it an edition view ?

put()

HTTP PUT api endpoint

schema = None
class endi.views.BaseView(context, request=None)

Bases : object

class endi.views.BaseXlsView(*args, **kwargs)

Bases : BaseCsvView

dbsession: <sqlalchemy.orm.scoping.scoped_session object at 0x7fe5b76f0350>
request: Request
session: <InterfaceClass pyramid.interfaces.ISession>
writer

alias de SqlaXlsExporter

class endi.views.DeleteView(context, request=None)

Bases : BaseView, PopupMixin

Deletion view deletes the current context

Class Attributes

delete_msg

The message poped to the end user after the element is deleted

redirect_route

The name of the route we redirect after deletion

Following methods can be overriden if needed

on_before_delete

Run before the deletion

on_delete

Run after the object has been deleted

redirect

Data that will be returned by the view (default is HTTPFound but can also be json data)

class MyDeleteView(DeleteView):
    delete_msg = "L'élément a bien été supprimé"
    redirect_route = "templates"
delete()
delete_msg = "L'élément a bien été supprimé"
on_before_delete()
on_delete()
redirect()
redirect_route = None
class endi.views.DisableView(context, request=None)

Bases : BaseView

Main view for enabling/disabling elements

Support following attributes/methods

Attributes

enable_msg

Message flashed when enabled

disable_msg

Message flashed when disabled

redirect_route

The name of a route to redirect to

Methods

redirect

Return a dynamicallay created HTTPFound instance

on_disable

Launched on item disable

on_enable

Launched on item enable

class MyDisableView(DisableView):

enable_msg = « Has been enabled » disabled_msg = « Has been disabled » redirect_route = « The route name »

active_key = 'active'
disable_msg = None
enable_msg = None
redirect_route = None
class endi.views.DuplicateView(context, request=None)

Bases : BaseView

Base Duplication view

calls the duplicate method on the view’s context flash a link to the duplicated item redirect to the redirect route

Attr str route_name:

The route_name used to generate the link to the

duplication view (implement _link to override default generation)

Attr str collection_route_name:

optionnal collection route name to which

redirect (default set to route_name + “s”), implement a _redirect method to override the redirection mechanism

Attr str message:

The duplication message, take a single formatting value

(the link to the new item)

collection_route_name = None
message = None
redirect(item)

Default redirect implementation

Paramètres:

item (obj) – The newly created element (flushed)

Renvoie:

The url to redirect to

Type renvoyé:

str

route_name = None
class endi.views.JsAppViewMixin

Bases : object

For views having a JS app Using REST API requiring

Helps building AppOption JS object for JS app use a consistent way accross enDi.

Conventions: - context resource URL is given by context_url() implementation - form_config_url is context url + form_config=1 (this route has to exist)

Usage: - implement context_url() - call get_js_app_options() to build context with context_url/form_config_url keys - don’t forget to initialize AppOption object in your mako template.

context_url(_query: Dict[str, str] = {})
form_config_url()
get_js_app_options() dict
more_js_app_options()

Add options passed to the AppOption object

class endi.views.PopupMixin

Bases : object

Provide methods for handling popup related actions

add_popup_response()
Add custom response string to the request :

Pop message or Refresh parent page

regarding the options if a message was set in the queue, it’s shown with a refresh link else we fully reload the page

class endi.views.RestListMixinClass(context, request=None)

Bases : BaseListClass

Base mixin for rest list views with pagination

  • It launches a query to retrieve records

  • Validates GET params regarding the given schema

  • filter the query with the provided filter_* methods

  • orders the query

  • sorts the query

@param list_schema: Schema used to validate the GET params provided in the

url, the schema should inherit from endi.views.forms.lists.BaseListsSchema to preserve most of the processed automation list_schema can be either a callable or an instance

@param sort_columns: dict of {“sort_column_key”:”sort_column”…}.

Allows to generate the validator for the sort availabilities and to automatically add a order_by clause to the query. sort_column may be equal to Table.attribute if join clauses are present in the main query.

@default_sort: the default sort_column_key to be used @default_direction: the default sort direction (one of [“asc”, “desc”])

you must implement method :

query()

Returns an iterable of items

you must implement property :

list_schema (see above)

you can implement methods

filter_*(self, query, appstruct)

Allows to provide several filters Should act on the query and returns it

_sort_by_<sort_key>(self, query, appstruct)

Handles sorting stuff if the given sort_key is used Should act on the query and returns it

format_collection(self, query)

Builds the data returned to the end user when calling the collection GET api endpoint

collection_get()

Collection HTTP GET method endpoint

dbsession: <sqlalchemy.orm.scoping.scoped_session object at 0x7fe5b76f0350>
default_sort = None
format_collection(query)

Format the collection returned to the end user

result of HTTP GET call on the collection endpoint

get_list_schema()
list_schema

alias de BaseListsSchema

request: Request
session: <InterfaceClass pyramid.interfaces.ISession>
sort_columns = {}
class endi.views.TreeMixin

Bases : object

Mixin adding tree structure to views

class MyView(BaseView, TreeMixin):

route_name = « /myviewroute »

Inherit from the TreeMixin and attach views to parent views

route_name

current route_name

children

class attribute in list format registering all view children

parent

weakref to the parent view

classmethod add_child(view_class)
property breadcrumb
children = []
description = ''
classmethod get_back_url(request)
classmethod get_breadcrumb(request, is_leaf=False)

Collect breadcrumb entries

Paramètres:
  • request (obj) – The Pyramid request

  • is_leaf (bool) – Do we ask the leaf node

Renvoie:

A generator of 2-uples (title, url)

classmethod get_me_as_back_url(request)

Collect the back url pointing to the current view, ask the parent if needed

classmethod get_navigation(request)
classmethod get_title(request)
classmethod get_url(request)
property navigation
parent_view = None
populate_navigation()
route_name = None
title = ''
class endi.views.TreeMixinMetaClass(clsname, bases, attrs)

Bases : type

Metaclasse qui attache un attribut children spécifique à chaque classe fille créée

LE problème d’origine :

class A:

children = []

class B(A):

pass

B.children.append(“o”) A.children [“o”]

Avec cette métaclasse

A.children = []

endi.views.add_panel_page_view(config, panel_name, **kwargs)
endi.views.add_panel_view(config, panel_name, **kwargs)

Add a panel view to the current configuration

endi.views.add_tree_view_directive(config, *args, **kwargs)

Custom add view directive specific to views using the TreeMixin class It allows to pass a parent parameter matching the parent view

This way views can display a breadcrumb for navigation

endi.views.endi_add_route(config, route_name, **kwargs)

Utility to add route, transforming the route name into a regex pattern.

endi.views.get_page_url(request, page)

Page url generator to be used with webob.paginate’s tool

Note : default Webob pagination tool doesn’t respect query_params order and breaks mapping order, so we can’t preserve search params in list views

endi.views.make_panel_wrapper_view(panel_name, js_resources=())

Return a view wrapping the given panel

Paramètres:

panel_name (str) – The name of the panel

endi.views.redirect_to_index_view(request, context)

Vue redirigeant l’utilisateur vers l’index d’enDI (utilisée lorsque l’on remappe les urls)