Passed
Push — master ( d0e2c4...5960fc )
by Markus
02:09
created

chaoswg.get_history_user()   A

Complexity

Conditions 1

Size

Total Lines 5
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nop 1
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
1
from datetime import datetime
0 ignored issues
show
Coding Style introduced by
This module should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2
3
from flask import Flask, render_template, request, redirect, jsonify
4
from flask_babel import Babel
5
from flask_bootstrap import Bootstrap, WebCDN
6
from flask_login import LoginManager, login_user, logout_user, login_required, current_user
7
8
from chaoswg.forms import LoginForm, CreateTaskForm, CustomTaskForm
9
from chaoswg.models import init_database, create_tables, User, Task, History, insert_testdata
10
from chaoswg.admin import init_admin
11
from chaoswg.helpers import format_datetime_custom, format_timedelta_custom
12
13
# init app and load config
14
app = Flask(__name__)
0 ignored issues
show
Coding Style Naming introduced by
The name app does not conform to the constant naming conventions ((([A-Z_][A-Z0-9_]*)|(__.*__))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
15
# read config.py
16
app.config.from_pyfile('../config.py')
17
18
# init DB
19
init_database(app)
20
create_tables()
21
# TODO remove in production
0 ignored issues
show
Coding Style introduced by
TODO and FIXME comments should generally be avoided.
Loading history...
22
# insert_testdata()
23
24
# init login manager
25
login_manager = LoginManager()
0 ignored issues
show
Coding Style Naming introduced by
The name login_manager does not conform to the constant naming conventions ((([A-Z_][A-Z0-9_]*)|(__.*__))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
26
login_manager.init_app(app)
27
28
# Enable bootstrap support
29
Bootstrap(app)
30
# jQuery 3 instead of 1
31
app.extensions['bootstrap']['cdns']['jquery'] = WebCDN(
32
    '//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/'
33
)
34
35
# Enable babel support
36
app.babel = Babel(app, default_timezone='Europe/Berlin')
37
# set datetime filter for jinja2
38
app.jinja_env.filters['datetime'] = format_datetime_custom
0 ignored issues
show
Bug introduced by
The Method jinja_env does not seem to have a member named filters.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
39
app.jinja_env.filters['timedelta'] = format_timedelta_custom
0 ignored issues
show
Bug introduced by
The Method jinja_env does not seem to have a member named filters.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
40
41
# init admin interface
42
init_admin(app)
43
44
45
@app.route('/')
46
def index():
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
47
    return render_template('index.html', usernames=User.get_usernames())
48
49
50
@app.route('/login', methods=['GET', 'POST'])
51
def login():
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
52
    form = LoginForm()
53
54
    if form.validate_on_submit():
55
        user = User.get_by_name(form.name.data)
56
        if user and user.check_password(form.password.data):
57
            login_user(user, remember=True)
58
            return redirect('/tasks')
59
60
    return render_template('login.html', form=form)
61
62
63
@login_manager.user_loader
64
def load_user(user_id):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
65
    return User.get(User.id == user_id)
66
67
68
@login_manager.unauthorized_handler
69
def unauthorized():
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
70
    return redirect('/login')
71
72
73
@app.route('/logout')
74
@login_required
75
def logout():
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
76
    logout_user()
77
    return redirect('/')
78
79
80
@app.route('/users')
81
@login_required
82
def get_users():
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
83
    users = User.get_all()
84
    usernames = set()
85
    for user in users:
86
        usernames.add(user['username'])
87
    return render_template('users.html', users=users, usernames=usernames)
88
89
90
@app.route('/history')
91
@login_required
92
def get_history():
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
93
    return render_template('history.html', usernames=User.get_usernames())
94
95
96
@app.route('/history/<username>')
97
@login_required
98
def get_history_user(username):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
99
    return render_template('history_user.html', userhist=History.get_user_history(username), username=username,
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (111/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
100
                           usernames=User.get_usernames())
101
102
103
@app.route('/create_task', methods=['GET', 'POST'])
104
@login_required
105
def create_task():
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
106
    form = CreateTaskForm()
107
108
    if form.validate_on_submit():
109
        task, created = Task.get_or_create(task=form.task.data, defaults={'base_points': form.base_points.data,
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (111/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
110
                                                                          'time_factor': form.time_factor.data})
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (112/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
111
        if not created:
112
            # TODO return error message, task exists
0 ignored issues
show
Coding Style introduced by
TODO and FIXME comments should generally be avoided.
Loading history...
113
            return '', 403
114
115
        # TODO return success message
0 ignored issues
show
Coding Style introduced by
TODO and FIXME comments should generally be avoided.
Loading history...
116
        return redirect('/tasks')
117
118
    return render_template('create_task.html', form=form)
119
120
121
@app.route('/do_custom_task', methods=['GET', 'POST'])
122
@login_required
123
def do_custom_task():
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
124
    form = CustomTaskForm()
125
126
    if form.validate_on_submit():
127
        # do custom onetime task
128
        Task.do_custom_task(form.task.data, form.points.data, current_user.get_id())
129
        return redirect('/tasks')
130
131
    return render_template('do_custom_task.html', form=form)
132
133
134
@app.route('/tasks')
135
@login_required
136
def get_tasks():
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
137
    tasks = Task.get_all()
138
    backlog = [t for t in tasks if t.state == Task.BACKLOG]
139
    todo = [t for t in tasks if t.state == Task.TODO]
140
    done = [t for t in tasks if t.state == Task.DONE]
141
142
    progress = {
143
        'backlog': len(backlog) / len(tasks) * 100,
144
        'todo': len(todo) / len(tasks) * 100,
145
        'done': len(done) / len(tasks) * 100
146
    }
147
148
    return render_template('tasks.html', backlog=backlog, todo=todo, done=done, progress=progress,
149
                           usernames=User.get_usernames())
150
151
152
@app.route('/set_task_state', methods=['POST'])
153
@login_required
154
def set_task_state():
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
155
    user_id = current_user.get_id()
156
    task_id = request.form.get('id', type=int)
157
    state = request.form.get('state', type=int)
158
    if None not in (task_id, state, user_id) and state in (0, 1, 2):
159
        Task.set_state(task_id, state, user_id)
160
    else:
161
        # TODO message
0 ignored issues
show
Coding Style introduced by
TODO and FIXME comments should generally be avoided.
Loading history...
162
        return '', 403
163
    # New state was set
164
    return '', 204
165
166
167
#########################
168
# JSON endpoints for JS #
169
#########################
170
171
@app.route('/json/history/<username>')
172
@login_required
173
def get_history_user_json(username):
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
174
    return jsonify(History.get_user_history(username))
175
176
177
@app.route('/json/users')
178
@login_required
179
def get_users_json():
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
180
    return jsonify(User.get_all())
181
182
183
@app.route('/json/history')
184
@login_required
185
def get_history_json():
0 ignored issues
show
Coding Style introduced by
This function should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
186
    hist = History.get_full_history()
187
    result = {}
188
    for h in hist:
0 ignored issues
show
Coding Style Naming introduced by
The name h does not conform to the variable naming conventions ((([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
189
        if h['username'] not in result:
190
            # initial 0 points
191
            result[h['username']] = [{
192
                'time': h['time'],
193
                'points': 0
194
            }]
195
        result[h['username']].append({
196
            'time': h['time'],
197
            'points': h['points']
198
        })
199
200
    # same point count till today
201
    for user in result:
202
        result[user].append({
203
            'time': datetime.utcnow(),
204
            'points': 0
205
        })
206
207
    return jsonify(result)
208