Completed
Push — master ( f245e3...e307dd )
by Chris
01:13
created

MultiStepWizard.__len__()   A

Complexity

Conditions 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
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.ext.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 __init__(self, *args, **kwargs):
55
        """Do all the required setup for managing the forms."""
56
        super(MultiStepWizard, self).__init__(*args, **kwargs)
57
        # Store the name and session key by a user specified kwarg,
58
        # or fall back to this class name.
59
        self.name = kwargs.get('session_key', self.__class__.__name__)
60
        # Get the sessions' current step if it exists.
61
        curr_step = session.get(self.name, {}).get('curr_step', 1)
62
        # if the user specified a step, we'll use that instead. Form validation
63
        # will still occur, but this is useful for when the user may need
64
        # to go back a step or more.
65
        if 'curr_step' in kwargs:
66
            curr_step = int(kwargs.pop('curr_step'))
67
        if curr_step > len(self.__forms__):
68
            curr_step = 1
69
        self.step = curr_step
70
        # Store forms in a dunder because we want to avoid conflicts
71
        # with any WTForm objects or third-party libs.
72
        self.__forms = []
73
        self._setup_session()
74
        self._populate_forms()
75
        invalid_forms_msg = 'Something happened during form population.'
76
        assert len(self.__forms) == len(self.__forms__), invalid_forms_msg
77
        assert len(self.__forms) > 0, 'Need at least one form!'
78
        self.active_form = self.get_active()[1]
79
        # Inject the required fields for the active form.
80
        # The multiform class will always be instantiated once
81
        # on account of separate POST requests, and so the previous form
82
        # values will no longer be attributes to be concerned with.
83
        self._setfields()
84
85
    def _setfields(self):
86
        """Dynamically set fields for this particular form step."""
87
        _, form = self.get_active()
88
        for name, val in vars(form).items():
89
            if repr(val).startswith('<UnboundField'):
90
                setattr(self, name, val)
91
92
    def alldata(self, combine_fields=False, flush_after=False):
93
        """Get the specific forms data."""
94
        _alldata = dict()
95
        # Get all session data, combine if specified,
96
        # and delete session if specified.
97
        if self.name in session:
98
            _alldata = session[self.name].get('data')
99
            if combine_fields:
100
                combined = dict()
101
                for formname, data in _alldata.items():
102
                    if data is not None:
103
                        combined.update(data)
104
                _alldata = combined
105
        if flush_after:
106
            self.flush()
107
        return _alldata
108
109
    @property
110
    def data(self):
111
        """Get the specific forms data."""
112
        _, form = self.get_active()
113
        return form.data
114
115
    @property
116
    def forms(self):
117
        """Get all forms."""
118
        return self.__forms
119
120
    def _setup_session(self):
121
        """Setup session placeholders for later use."""
122
        # We will populate these values as the form progresses,
123
        # but only if it doesn't already exist from a previous step.
124
        if self.name not in session:
125
            session[self.name] = dict(
126
                curr_step=self.curr_step,
127
                data={f.__name__: None for f in self.__forms__})
128
129
    def _populate_forms(self):
130
        """Populate all forms with existing data for validation.
131
132
        This will only be done if the session data exists for a form.
133
        """
134
        # We've already populated these forms, don't do it again.
135
        if len(self.__forms) > 0:
136
            return
137
        for form in self.__forms__:
138
            data = session[self.name]['data'].get(form.__name__)
139
            init_form = form(**data) if data is not None else form()
140
            self.__forms.append(init_form)
141
142
    def _update_session_formdata(self, form):
143
        """Update session data for a given form key."""
144
        # Add data to session for this current form!
145
        name = form.__class__.__name__
146
        data = form.data
147
        # Update the session data for this particular form step.
148
        # The policy here is to always clobber old data.
149
        session[self.name]['data'][name] = data
150
151
    @property
152
    def active_name(self):
153
        """Return the nice name of this form class."""
154
        return self.active_form.__class__.__name__
155
156
    def next_step(self):
157
        """Set the step number in the session to the next value."""
158
        next_step = session[self.name]['curr_step'] + 1
159
        self.curr_step = next_step
160
        if self.name in session:
161
            session[self.name]['curr_step'] += 1
162
163
    @property
164
    def step(self):
165
        """Get the current step."""
166
        if self.name in session:
167
            return session[self.name]['curr_step']
168
169
    @step.setter
170
    def step(self, step_val):
171
        """Set the step number in the session."""
172
        self.curr_step = step_val
173
        if self.name in session:
174
            session[self.name]['curr_step'] = step_val
175
176
    def validate_on_submit(self, *args, **kwargs):
177
        """Override validator and setup session updates for persistence."""
178
        # Update the step to the next form automagically for the user
179
        step, form = self.get_active()
180
        self._update_session_formdata(form)
181
        if not form.validate_on_submit():
182
            self.step = step - 1
183
            return False
184
        # Update to next form if applicable.
185
        if step - 1 < len(self.__forms):
186
            self.curr_step += 1
187
            self.active_form = self.__forms[self.curr_step - 1]
188
            self.next_step()
189
        # Mark the current step as -1 to indicate it has been
190
        # fully completed, if the current step is the final step.
191
        elif step - 1 == len(self.__forms):
192
            self.step = -1
193
        return True
194
195
    @property
196
    def remaining(self):
197
        """Get the number of steps remaining."""
198
        return len(self.__forms[self.curr_step:]) + 1
199
200
    @property
201
    def total_steps(self):
202
        """Get the number of steps for this form in a (non-zero index)."""
203
        return len(self.__forms)
204
205
    @property
206
    def steps(self):
207
        """Get a list of the steps for iterating in views, html, etc."""
208
        return range(1, self.total_steps + 1)
209
210
    def get_active(self):
211
        """Get active step."""
212
        form_index = self.curr_step - 1 if self.curr_step > 0 else 0
213
        return self.curr_step + 1, self.__forms[form_index]
214
215
    def flush(self):
216
        """Clear data and reset."""
217
        del session[self.name]
218
219
    def is_complete(self):
220
        """Determine if all forms have been completed."""
221
        if self.name not in session:
222
            return False
223
        # Make the current step index something unique for being "complete"
224
        completed = self.step == -1
225
        if completed:
226
            # Reset.
227
            self.curr_step = 1
228
        return completed
229