MultiStepWizard._setfields()   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
c 1
b 0
f 0
dl 0
loc 6
rs 9.4285
1
"""A simple multi-step wizard that uses the flask application session.
2
3
Creating multi-step forms of arbitrary length is simple and intuitive.
4
5
Example usage:
6
7
```
8
from flask.ext.wtf import FlaskForm
9
10
class MultiStepTest1(FlaskForm):
11
    field1 = StringField(validators=[validators.DataRequired()],)
12
    field2 = StringField(validators=[validators.DataRequired()],)
13
14
15
class MultiStepTest2(FlaskForm):
16
    field3 = StringField(validators=[validators.DataRequired()],)
17
    field4 = StringField(validators=[validators.DataRequired()],)
18
19
20
class MyCoolForm(MultiStepWizard):
21
    __forms__ = [
22
        MultiStepTest1,
23
        MultiStepTest2,
24
    ]
25
```
26
"""
27
28
from flask import session
29
from flask_wtf import FlaskForm
30
31
32
class MultiStepWizard(FlaskForm):
33
    """Generates a multi-step wizard.
34
35
    The wizard uses the app specified session backend to store both
36
    form data and current step.
37
38
    TODO: make sure all the expected features of the typical form
39
    are exposed here, but automatically determining the active form
40
    and deferring to it. See __iter__ and data for examples.
41
    """
42
43
    __forms__ = []
44
45
    def __iter__(self):
46
        """Get the specific forms' fields for standard WTForm iteration."""
47
        _, form = self.get_active()
48
        return form.__iter__()
49
50
    def __len__(self):
51
        """Override the len method to emulate standard wtforms."""
52
        return len(self.__forms)
53
54
    def __getitem__(self, key):
55
        """Override getitem to emulate standard wtforms."""
56
        return self.active_form.__getitem__(key)
57
58
    def __contains__(self, item):
59
        """Override contains to emulate standard wtforms."""
60
        return self.active_form.__contains__(item)
61
62
    def __init__(self, *args, **kwargs):
63
        """Do all the required setup for managing the forms."""
64
        super(MultiStepWizard, self).__init__(*args, **kwargs)
65
        # Store the name and session key by a user specified kwarg,
66
        # or fall back to this class name.
67
        self.name = kwargs.get('session_key', self.__class__.__name__)
68
        # Get the sessions' current step if it exists.
69
        curr_step = session.get(self.name, {}).get('curr_step', 1)
70
        # if the user specified a step, we'll use that instead. Form validation
71
        # will still occur, but this is useful for when the user may need
72
        # to go back a step or more.
73
        if 'curr_step' in kwargs:
74
            curr_step = int(kwargs.pop('curr_step'))
75
        if curr_step > len(self.__forms__):
76
            curr_step = 1
77
        self.step = curr_step
78
        # Store forms in a dunder because we want to avoid conflicts
79
        # with any WTForm objects or third-party libs.
80
        self.__forms = []
81
        self._setup_session()
82
        self._populate_forms()
83
        invalid_forms_msg = 'Something happened during form population.'
84
        assert len(self.__forms) == len(self.__forms__), invalid_forms_msg
85
        assert len(self.__forms) > 0, 'Need at least one form!'
86
        self.active_form = self.get_active()[1]
87
        # Inject the required fields for the active form.
88
        # The multiform class will always be instantiated once
89
        # on account of separate POST requests, and so the previous form
90
        # values will no longer be attributes to be concerned with.
91
        self._setfields()
92
93
    def _setfields(self):
94
        """Dynamically set fields for this particular form step."""
95
        _, form = self.get_active()
96
        for name, val in vars(form).items():
97
            if repr(val).startswith('<UnboundField'):
98
                setattr(self, name, val)
99
100
    def alldata(self, combine_fields=False, flush_after=False):
101
        """Get the specific forms data."""
102
        _alldata = dict()
103
        # Get all session data, combine if specified,
104
        # and delete session if specified.
105
        if self.name in session:
106
            _alldata = session[self.name].get('data')
107
            if combine_fields:
108
                combined = dict()
109
                for formname, data in _alldata.items():
110
                    if data is not None:
111
                        combined.update(data)
112
                _alldata = combined
113
        if flush_after:
114
            self.flush()
115
        return _alldata
116
117
    @property
118
    def data(self):
119
        """Get the specific forms data."""
120
        _, form = self.get_active()
121
        return form.data
122
123
    @property
124
    def forms(self):
125
        """Get all forms."""
126
        return self.__forms
127
128
    def _setup_session(self):
129
        """Setup session placeholders for later use."""
130
        # We will populate these values as the form progresses,
131
        # but only if it doesn't already exist from a previous step.
132
        if self.name not in session:
133
            session[self.name] = dict(
134
                curr_step=self.curr_step,
135
                data={f.__name__: None for f in self.__forms__})
136
137
    def _populate_forms(self):
138
        """Populate all forms with existing data for validation.
139
140
        This will only be done if the session data exists for a form.
141
        """
142
        # We've already populated these forms, don't do it again.
143
        if len(self.__forms) > 0:
144
            return
145
        for form in self.__forms__:
146
            data = session[self.name]['data'].get(form.__name__)
147
            init_form = form(**data) if data is not None else form()
148
            self.__forms.append(init_form)
149
150
    def _update_session_formdata(self, form):
151
        """Update session data for a given form key."""
152
        # Add data to session for this current form!
153
        name = form.__class__.__name__
154
        data = form.data
155
        # Update the session data for this particular form step.
156
        # The policy here is to always clobber old data.
157
        session[self.name]['data'][name] = data
158
159
    @property
160
    def active_name(self):
161
        """Return the nice name of this form class."""
162
        return self.active_form.__class__.__name__
163
164
    def next_step(self):
165
        """Set the step number in the session to the next value."""
166
        next_step = session[self.name]['curr_step'] + 1
167
        self.curr_step = next_step
168
        if self.name in session:
169
            session[self.name]['curr_step'] += 1
170
171
    @property
172
    def step(self):
173
        """Get the current step."""
174
        if self.name in session:
175
            return session[self.name]['curr_step']
176
177
    @step.setter
178
    def step(self, step_val):
179
        """Set the step number in the session."""
180
        self.curr_step = step_val
181
        if self.name in session:
182
            session[self.name]['curr_step'] = step_val
183
184
    def validate_on_submit(self, *args, **kwargs):
185
        """Override validator and setup session updates for persistence."""
186
        # Update the step to the next form automagically for the user
187
        step, form = self.get_active()
188
        self._update_session_formdata(form)
189
        if not form.validate_on_submit():
190
            self.step = step - 1
191
            return False
192
        # Update to next form if applicable.
193
        if step - 1 < len(self.__forms):
194
            self.curr_step += 1
195
            self.active_form = self.__forms[self.curr_step - 1]
196
            self.next_step()
197
        # Mark the current step as -1 to indicate it has been
198
        # fully completed, if the current step is the final step.
199
        elif step - 1 == len(self.__forms):
200
            self.step = -1
201
        return True
202
203
    @property
204
    def remaining(self):
205
        """Get the number of steps remaining."""
206
        return len(self.__forms[self.curr_step:]) + 1
207
208
    @property
209
    def total_steps(self):
210
        """Get the number of steps for this form in a (non-zero index)."""
211
        return len(self.__forms)
212
213
    @property
214
    def steps(self):
215
        """Get a list of the steps for iterating in views, html, etc."""
216
        return range(1, self.total_steps + 1)
217
218
    def get_active(self):
219
        """Get active step."""
220
        form_index = self.curr_step - 1 if self.curr_step > 0 else 0
221
        return self.curr_step + 1, self.__forms[form_index]
222
223
    def flush(self):
224
        """Clear data and reset."""
225
        del session[self.name]
226
227
    def is_complete(self):
228
        """Determine if all forms have been completed."""
229
        if self.name not in session:
230
            return False
231
        # Make the current step index something unique for being "complete"
232
        completed = self.step == -1
233
        if completed:
234
            # Reset.
235
            self.curr_step = 1
236
        return completed
237