Refactor code for generating choices lists.

This commit is contained in:
2019-03-13 20:32:55 +01:00
parent 749d20127d
commit f6a38cc2db
2 changed files with 32 additions and 14 deletions

View File

@@ -22,23 +22,41 @@ def player_choice():
return [(p.id, p.name) for p in players] return [(p.id, p.name) for p in players]
class SeasonChoicesIterable: def drink_choice():
"""
Query database for a list of all available drinks to select from
"""
sql, args = db.load_drinks()
drinks = db.query_db(sql, args, cls=models.Drink)
choices = [(d.id, d.name) for d in drinks]
choices.insert(0, (-1, "None"))
return choices
class IterableBase:
""" """
This is used to declare choices for WTForms SelectFields at class definition time. This is used to declare choices for WTForms SelectFields at class definition time.
Be aware that this uses an undocumented WTForms feature and is not guaranteed to work. Be aware that this uses an undocumented WTForms feature and is not guaranteed to work.
""" """
def __iter__(self): _loader = None
for choice in season_choices():
yield choice
class PlayerChoiceIterable:
"""
This is used to declare choices for WTForms SelectFields at class definition time.
Be aware that this uses an undocumented WTForms feature and is not guaranteed to work.
"""
def __iter__(self): def __iter__(self):
for choice in player_choice(): if self._loader:
yield choice for choice in self._loader():
yield choice
class SeasonChoiceIterable(IterableBase):
def __init__(self):
self._loader = season_choices
class PlayerChoiceIterable(IterableBase):
def __init__(self):
self._loader = player_choice
class DrinkChoiceIterable(IterableBase):
def __init__(self):
self._loader = drink_choice

View File

@@ -58,7 +58,7 @@ class DrinkForm(FlaskForm):
class EnemyForm(FlaskForm): class EnemyForm(FlaskForm):
enemy_id = HiddenField("Enemy ID", render_kw={"readonly": True}) enemy_id = HiddenField("Enemy ID", render_kw={"readonly": True})
season_id = SelectField( season_id = SelectField(
"Season", choices=choices.SeasonChoicesIterable(), coerce=int "Season", choices=choices.SeasonChoiceIterable(), coerce=int
) )
name = StringField("Name", validators=[DataRequired()]) name = StringField("Name", validators=[DataRequired()])
is_boss = BooleanField("Is Boss") is_boss = BooleanField("Is Boss")