~homeworkprod/byceps

ref: 533662eefb314d54b168e5a46bc07c88b5f88be4 byceps/byceps/blueprints/site/user_group/views.py -rw-r--r-- 1.7 KiB
533662ee — Jochen Kupperschmidt Use Flask v2.0's `delete`/`get`/`patch`/`post` route shortcuts 2 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
"""
byceps.blueprints.site.user_group.views
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""

from flask import g, request
from flask_babel import gettext

from ....services.user_group import service as user_group_service
from ....util.framework.blueprint import create_blueprint
from ....util.framework.flash import flash_error, flash_success
from ....util.framework.templating import templated
from ....util.views import redirect_to

from .forms import CreateForm


blueprint = create_blueprint('user_group', __name__)


@blueprint.get('/')
@templated
def index():
    """List groups."""
    groups = user_group_service.get_all_groups()

    return {
        'groups': groups,
    }


@blueprint.get('/create')
@templated
def create_form(erroneous_form=None):
    """Show a form to create a group."""
    if not g.user.authenticated:
        flash_error(gettext('You have to be logged in to create a user group.'))
        return redirect_to('.index')

    form = erroneous_form if erroneous_form else CreateForm()

    return {
        'form': form,
    }


@blueprint.post('/')
def create():
    """Create a group."""
    if not g.user.authenticated:
        flash_error(gettext('You have to be logged in to create a user group.'))
        return redirect_to('.index')

    form = CreateForm(request.form)

    creator = g.user
    title = form.title.data.strip()
    description = form.description.data.strip()

    group = user_group_service.create_group(creator.id, title, description)

    flash_success(
        gettext(
            'Group "%(group_title)s" has been created.',
            group_title=group.title,
        )
    )
    return redirect_to('.index')