Refactor code for generating choices lists.
This commit is contained in:
38
choices.py
38
choices.py
@@ -22,23 +22,41 @@ def player_choice():
|
||||
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.
|
||||
Be aware that this uses an undocumented WTForms feature and is not guaranteed to work.
|
||||
"""
|
||||
|
||||
_loader = None
|
||||
|
||||
def __iter__(self):
|
||||
for choice in season_choices():
|
||||
if self._loader:
|
||||
for choice in self._loader():
|
||||
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.
|
||||
"""
|
||||
class SeasonChoiceIterable(IterableBase):
|
||||
def __init__(self):
|
||||
self._loader = season_choices
|
||||
|
||||
def __iter__(self):
|
||||
for choice in player_choice():
|
||||
yield choice
|
||||
|
||||
class PlayerChoiceIterable(IterableBase):
|
||||
def __init__(self):
|
||||
self._loader = player_choice
|
||||
|
||||
|
||||
class DrinkChoiceIterable(IterableBase):
|
||||
def __init__(self):
|
||||
self._loader = drink_choice
|
||||
|
||||
2
forms.py
2
forms.py
@@ -58,7 +58,7 @@ class DrinkForm(FlaskForm):
|
||||
class EnemyForm(FlaskForm):
|
||||
enemy_id = HiddenField("Enemy ID", render_kw={"readonly": True})
|
||||
season_id = SelectField(
|
||||
"Season", choices=choices.SeasonChoicesIterable(), coerce=int
|
||||
"Season", choices=choices.SeasonChoiceIterable(), coerce=int
|
||||
)
|
||||
name = StringField("Name", validators=[DataRequired()])
|
||||
is_boss = BooleanField("Is Boss")
|
||||
|
||||
Reference in New Issue
Block a user