vulyk.blueprints.gamification.models package

Submodules

vulyk.blueprints.gamification.models.events module

Contains all DB models related to game events.

class vulyk.blueprints.gamification.models.events.EventModel(*args, **values)[source]

Bases: flask_mongoengine.Document

Database-specific gamification system event representation

exception DoesNotExist

Bases: mongoengine.errors.DoesNotExist

exception MultipleObjectsReturned

Bases: mongoengine.errors.MultipleObjectsReturned

acceptor_fund

A reference to a document that will be automatically dereferenced on access (lazily).

Note this means you will get a database I/O access everytime you access this field. This is necessary because the field returns a Document which precise type can depend of the value of the _cls field present in the document in database. In short, using this type of field can lead to poor performances (especially if you access this field only to retrieve it pk field which is already known before dereference). To solve this you should consider using the LazyReferenceField.

Use the reverse_delete_rule to handle what should happen if the document the field is referencing is deleted. EmbeddedDocuments, DictFields and MapFields does not support reverse_delete_rule and an InvalidDocumentError will be raised if trying to set on one of these Document / Field types.

The options are:

  • DO_NOTHING (0) - don’t do anything (default).

  • NULLIFY (1) - Updates the reference to null.

  • CASCADE (2) - Deletes the documents associated with the reference.

  • DENY (3) - Prevent the deletion of the reference object.

  • PULL (4) - Pull the reference from a ListField of references

Alternative syntax for registering delete rules (useful when implementing bi-directional delete rules)

class Org(Document):
    owner = ReferenceField('User')

class User(Document):
    org = ReferenceField('Org', reverse_delete_rule=CASCADE)

User.register_delete_rule(Org, 'owner', DENY)

Changed in version 0.5: added reverse_delete_rule

achievements

A list field that wraps a standard field, allowing multiple instances of the field to be used as a list in the database.

If using with ReferenceFields see: one-to-many-with-listfields

Note

Required means it cannot be empty - as the default for ListFields is []

classmethod amount_of_money_donated(user: Optional[vulyk.models.user.User]) → float[source]

Amount of money donated by current user or total donations if None passed.

Parameters

user (Optional[User]) – User instance

Returns

Amount of money

Return type

float

classmethod amount_of_money_earned(user: Optional[vulyk.models.user.User]) → float[source]

Amount of money earned by current user or total amount earned if None is passed.

Parameters

user (Optional[User]) – User instance

Returns

Amount of money

Return type

float

answer

A reference to a document that will be automatically dereferenced on access (lazily).

Note this means you will get a database I/O access everytime you access this field. This is necessary because the field returns a Document which precise type can depend of the value of the _cls field present in the document in database. In short, using this type of field can lead to poor performances (especially if you access this field only to retrieve it pk field which is already known before dereference). To solve this you should consider using the LazyReferenceField.

Use the reverse_delete_rule to handle what should happen if the document the field is referencing is deleted. EmbeddedDocuments, DictFields and MapFields does not support reverse_delete_rule and an InvalidDocumentError will be raised if trying to set on one of these Document / Field types.

The options are:

  • DO_NOTHING (0) - don’t do anything (default).

  • NULLIFY (1) - Updates the reference to null.

  • CASCADE (2) - Deletes the documents associated with the reference.

  • DENY (3) - Prevent the deletion of the reference object.

  • PULL (4) - Pull the reference from a ListField of references

Alternative syntax for registering delete rules (useful when implementing bi-directional delete rules)

class Org(Document):
    owner = ReferenceField('User')

class User(Document):
    org = ReferenceField('Org', reverse_delete_rule=CASCADE)

User.register_delete_rule(Org, 'owner', DENY)

Changed in version 0.5: added reverse_delete_rule

classmethod batches_user_worked_on(user: vulyk.models.user.User) → Generator[vulyk.models.tasks.Batch, None, None][source]

Returns an iterable of deduplicated batches user has worked on before.

Parameters

user (User) – User instance

Returns

Iterator over batches

Return type

Generator[Batch, None, None]

coins

Fixed-point decimal number field. Stores the value as a float by default unless force_string is used. If using floats, beware of Decimal to float conversion (potential precision loss)

Changed in version 0.8.

New in version 0.3.

classmethod count_of_tasks_done_by_user(user: vulyk.models.user.User) → int[source]

Number of tasks finished by current user

Parameters

user (User) – User instance

Returns

Count of tasks done

Return type

int

classmethod from_event(event: vulyk.blueprints.gamification.core.events.Event)[source]

Event to DB-specific model converter.

Parameters

event (Event) – Source event instance

Returns

New full-bodied model instance

Return type

EventModel

classmethod get_all_events(user: vulyk.models.user.User) → Iterator[source]

Returns aggregated and sorted generator of events (achievements & level-ups) user’d been given.

Parameters

user (User) – The user to extract events for

Returns

A generator of events in ascending chronological order.

Return type

Generator[Event, None, None]

classmethod get_unread_events(user: vulyk.models.user.User) → Generator[vulyk.blueprints.gamification.core.events.Event, None, None][source]

Returns aggregated and sorted list of generator (achievements & level-ups) user’d been given but hasn’t checked yet.

Parameters

user (User) – The user to extract events for

Returns

A generator of events in ascending chronological order.

Return type

Generator[Event, None, None]

id

A field wrapper around MongoDB’s ObjectIds.

level_given

32-bit integer field.

classmethod mark_events_as_read(user: vulyk.models.user.User) → None[source]

Mark all user events as viewed

Parameters

user (User) – The user to mark unseed events as viewed

Returns

Nothing. None. Empty. Long Gone

Return type

None

objects = []
points_given

Fixed-point decimal number field. Stores the value as a float by default unless force_string is used. If using floats, beware of Decimal to float conversion (potential precision loss)

Changed in version 0.8.

New in version 0.3.

timestamp

ComplexDateTimeField handles microseconds exactly instead of rounding like DateTimeField does.

Derives from a StringField so you can do gte and lte filtering by using lexicographical comparison when filtering / sorting strings.

The stored string has the following format:

YYYY,MM,DD,HH,MM,SS,NNNNNN

Where NNNNNN is the number of microseconds of the represented datetime. The , as the separator can be easily modified by passing the separator keyword when initializing the field.

Note: To default the field to the current datetime, use: DateTimeField(default=datetime.utcnow)

New in version 0.5.

to_event()vulyk.blueprints.gamification.core.events.Event[source]

DB-specific model to Event converter.

Returns

New Event instance

Return type

Event

user

A reference to a document that will be automatically dereferenced on access (lazily).

Note this means you will get a database I/O access everytime you access this field. This is necessary because the field returns a Document which precise type can depend of the value of the _cls field present in the document in database. In short, using this type of field can lead to poor performances (especially if you access this field only to retrieve it pk field which is already known before dereference). To solve this you should consider using the LazyReferenceField.

Use the reverse_delete_rule to handle what should happen if the document the field is referencing is deleted. EmbeddedDocuments, DictFields and MapFields does not support reverse_delete_rule and an InvalidDocumentError will be raised if trying to set on one of these Document / Field types.

The options are:

  • DO_NOTHING (0) - don’t do anything (default).

  • NULLIFY (1) - Updates the reference to null.

  • CASCADE (2) - Deletes the documents associated with the reference.

  • DENY (3) - Prevent the deletion of the reference object.

  • PULL (4) - Pull the reference from a ListField of references

Alternative syntax for registering delete rules (useful when implementing bi-directional delete rules)

class Org(Document):
    owner = ReferenceField('User')

class User(Document):
    org = ReferenceField('Org', reverse_delete_rule=CASCADE)

User.register_delete_rule(Org, 'owner', DENY)

Changed in version 0.5: added reverse_delete_rule

viewed

Boolean field type.

New in version 0.1.2.

vulyk.blueprints.gamification.models.foundations module

Contains all DB models related to foundations we donate or we rely on

class vulyk.blueprints.gamification.models.foundations.FundFilterBy[source]

Bases: enum.Enum

The intent of this enum is to represent filtering policies.

DONATABLE = 1
NON_DONATABLE = 2
NO_FILTER = 0
class vulyk.blueprints.gamification.models.foundations.FundModel(*args, **values)[source]

Bases: flask_mongoengine.Document

Database-specific foundation representation

exception DoesNotExist

Bases: mongoengine.errors.DoesNotExist

exception MultipleObjectsReturned

Bases: mongoengine.errors.MultipleObjectsReturned

description

A unicode string field.

donatable

Boolean field type.

New in version 0.1.2.

email

A field that validates input as an email address.

New in version 0.4.

classmethod find_by_id(fund_id: str) → Optional[vulyk.blueprints.gamification.core.foundations.Fund][source]

Convenience method that returns an optional fund by its ID.

Parameters

fund_id (str) – Fund’s ID

Returns

Found instance or none.

Return type

Optional[Fund]

classmethod from_fund(fund: vulyk.blueprints.gamification.core.foundations.Fund)[source]

Fund to DB-specific model converter.

Parameters

fund (Fund) – Current Fund instance

Returns

New FundModel instance

Return type

FundModel

classmethod get_funds(filter_by: vulyk.blueprints.gamification.models.foundations.FundFilterBy = <FundFilterBy.NO_FILTER: 0>) → Iterator[vulyk.blueprints.gamification.core.foundations.Fund][source]

Returns an enumeration of funds available using the filtering policy passed.

Parameters

filter_by (FundFilterBy) – Filtering policy

Returns

Lazy enumeration of funds available.

Return type

Iterator[Fund]

id

A unicode string field.

A Image File storage field.

Parameters
  • size – max size to store images, provided as (width, height, force) if larger, it will be automatically resized (ex: size=(800, 600, True))

  • thumbnail_size – size to generate a thumbnail, provided as (width, height, force)

New in version 0.6.

name

A unicode string field.

objects = []
site

A unicode string field.

to_fund()vulyk.blueprints.gamification.core.foundations.Fund[source]

DB-specific model to Fund converter.

Returns

New Fund instance

Return type

Fund

vulyk.blueprints.gamification.models.rules module

class vulyk.blueprints.gamification.models.rules.RuleModel(*args, **values)[source]

Bases: flask_mongoengine.Document

Database-specific rule representation

exception DoesNotExist

Bases: mongoengine.errors.DoesNotExist

exception MultipleObjectsReturned

Bases: mongoengine.errors.MultipleObjectsReturned

badge

A unicode string field.

bonus

32-bit integer field.

days_number

32-bit integer field.

description

A unicode string field.

classmethod from_rule(rule: vulyk.blueprints.gamification.core.rules.Rule)[source]

Rule to DB-specific model converter.

Parameters

rule (Rule) – Current Rule instance

Returns

New RuleModel instance

Return type

RuleModel

classmethod get_actual_rules(skip_ids: List[str], rule_filter: vulyk.blueprints.gamification.models.rules.RuleFilter, is_weekend: bool) → Iterator[vulyk.blueprints.gamification.core.rules.Rule][source]

Prepare the list of rules to apply. Cutting off is possible by using different tiny yet smart heuristics.

Parameters
  • skip_ids (List[str]) – A list of rules to be skipped for any reason

  • rule_filter (RuleFilter) – Prepared query container.

  • is_weekend (bool) – If today is a working day, there is no reason to check for rules that are weekend-backed.

Returns

An array of rules to be checked and assigned.

Return type

Iterator[Rule]

id

A unicode string field.

is_adjacent

Boolean field type.

New in version 0.1.2.

is_weekend

Boolean field type.

New in version 0.1.2.

name

A unicode string field.

objects = []
task_type_name

A unicode string field.

tasks_number

32-bit integer field.

to_rule()vulyk.blueprints.gamification.core.rules.Rule[source]

DB-specific model to Rule converter.

Returns

New Rule instance

Return type

Rule

class vulyk.blueprints.gamification.models.rules.AllRules[source]

Bases: vulyk.blueprints.gamification.models.rules.RuleFilter

Should return all rules.

to_query() → mongoengine.queryset.visitor.Q[source]

Prepares a filtering query.

Returns

Prepared query instance.

Return type

Q

class vulyk.blueprints.gamification.models.rules.ProjectAndFreeRules(task_type_name: str)[source]

Bases: vulyk.blueprints.gamification.models.rules.RuleFilter

Should return all rules related to a certain project along with project-agnostic ones.

to_query() → mongoengine.queryset.visitor.Q[source]

Prepares a filtering query.

Returns

Prepared query instance.

Return type

Q

class vulyk.blueprints.gamification.models.rules.StrictProjectRules(task_type_name: str)[source]

Bases: vulyk.blueprints.gamification.models.rules.RuleFilter

Should return all rules related only to a certain project.

to_query() → mongoengine.queryset.visitor.Q[source]

Prepares a filtering query.

Returns

Prepared query instance.

Return type

Q

vulyk.blueprints.gamification.models.state module

Contains all DB models related to aggregated user state within the game

class vulyk.blueprints.gamification.models.state.StateSortingKeys[source]

Bases: enum.Enum

The intent of this enum is to keep different sorting options shortcuts.

ACTUAL_COINS = 1
LEVEL = 3
POINTS = 0
POTENTIAL_COINS = 2
class vulyk.blueprints.gamification.models.state.UserStateModel(*args, **values)[source]

Bases: flask_mongoengine.Document

exception DoesNotExist

Bases: mongoengine.errors.DoesNotExist

exception MultipleObjectsReturned

Bases: mongoengine.errors.MultipleObjectsReturned

achievements

A list field that wraps a standard field, allowing multiple instances of the field to be used as a list in the database.

If using with ReferenceFields see: one-to-many-with-listfields

Note

Required means it cannot be empty - as the default for ListFields is []

actual_coins

Fixed-point decimal number field. Stores the value as a float by default unless force_string is used. If using floats, beware of Decimal to float conversion (potential precision loss)

Changed in version 0.8.

New in version 0.3.

classmethod from_state(state: vulyk.blueprints.gamification.core.state.UserState)[source]

UserState to DB-specific model converter.

Parameters

state (UserState) – Source user state

Returns

New model instance

Return type

UserStateModel

classmethod get_or_create_by_user(user: vulyk.models.user.User)vulyk.blueprints.gamification.core.state.UserState[source]

Returns an existing UserStateModel instance bound to the user, or a new one if didn’t exist before.

Parameters

user (User) – Current User model instance

Returns

UserState instance

Return type

UserState

classmethod get_top_users(limit: int, sort_by: vulyk.blueprints.gamification.models.state.StateSortingKeys) → Iterator[vulyk.blueprints.gamification.core.state.UserState][source]

Enumerates over top users basing on passed sorting criteria and limiting number. The yield sorting is descending.

Parameters
  • limit (int) – Top limit

  • sort_by (StateSortingKeys) – Criteria enumeration item

Returns

An iterator

Return type

Iterator[UserState]

id

A field wrapper around MongoDB’s ObjectIds.

last_changed

ComplexDateTimeField handles microseconds exactly instead of rounding like DateTimeField does.

Derives from a StringField so you can do gte and lte filtering by using lexicographical comparison when filtering / sorting strings.

The stored string has the following format:

YYYY,MM,DD,HH,MM,SS,NNNNNN

Where NNNNNN is the number of microseconds of the represented datetime. The , as the separator can be easily modified by passing the separator keyword when initializing the field.

Note: To default the field to the current datetime, use: DateTimeField(default=datetime.utcnow)

New in version 0.5.

level

32-bit integer field.

objects = []
points

Fixed-point decimal number field. Stores the value as a float by default unless force_string is used. If using floats, beware of Decimal to float conversion (potential precision loss)

Changed in version 0.8.

New in version 0.3.

potential_coins

Fixed-point decimal number field. Stores the value as a float by default unless force_string is used. If using floats, beware of Decimal to float conversion (potential precision loss)

Changed in version 0.8.

New in version 0.3.

to_state()vulyk.blueprints.gamification.core.state.UserState[source]

DB-specific model to UserState converter.

It isn’t supposed to dig out what’s been buried once, yet this method is really useful for tests.

Returns

New UserState instance

Return type

UserState

classmethod transfer_coins_to_actual(uid: bson.objectid.ObjectId, amount: decimal.Decimal) → bool[source]
Parameters
  • uid (ObjectId) – Current user ID

  • amount (Decimal) – Money amount

Returns

True if success

Return type

bool

classmethod update_state(diff: vulyk.blueprints.gamification.core.state.UserState) → None[source]

Prepares and conducts an atomic update query from passed diff.

Parameters

diff (UserState) – State object contains values that are to be changed only.

Return type

None

user

A reference to a document that will be automatically dereferenced on access (lazily).

Note this means you will get a database I/O access everytime you access this field. This is necessary because the field returns a Document which precise type can depend of the value of the _cls field present in the document in database. In short, using this type of field can lead to poor performances (especially if you access this field only to retrieve it pk field which is already known before dereference). To solve this you should consider using the LazyReferenceField.

Use the reverse_delete_rule to handle what should happen if the document the field is referencing is deleted. EmbeddedDocuments, DictFields and MapFields does not support reverse_delete_rule and an InvalidDocumentError will be raised if trying to set on one of these Document / Field types.

The options are:

  • DO_NOTHING (0) - don’t do anything (default).

  • NULLIFY (1) - Updates the reference to null.

  • CASCADE (2) - Deletes the documents associated with the reference.

  • DENY (3) - Prevent the deletion of the reference object.

  • PULL (4) - Pull the reference from a ListField of references

Alternative syntax for registering delete rules (useful when implementing bi-directional delete rules)

class Org(Document):
    owner = ReferenceField('User')

class User(Document):
    org = ReferenceField('Org', reverse_delete_rule=CASCADE)

User.register_delete_rule(Org, 'owner', DENY)

Changed in version 0.5: added reverse_delete_rule

classmethod withdraw(user: vulyk.models.user.User, amount: decimal.Decimal) → bool[source]

Reflects money withdrawal from current account.

Parameters
  • user (User) – User to perform the action on.

  • amount (Decimal) – Money amount (ONLY positive)

Raise
  • RuntimeError – if amount is negative

Returns

True if needed amount was successfully withdrawn

Return type

bool

vulyk.blueprints.gamification.models.task_types module

class vulyk.blueprints.gamification.models.task_types.AbstractGamifiedTaskType(settings: Dict[str, Any])[source]

Bases: vulyk.models.task_types.AbstractTaskType

to_dict() → Dict[str, Union[str, Dict, None]][source]

Prepare simplified dict that contains basic info about the task type + information on next open batch

Returns

distilled dict with basic info

Return type

Dict[str, Union[str, Optional[Dict]]]

Module contents