-
Notifications
You must be signed in to change notification settings - Fork 196
/
submissions_actions.py
383 lines (331 loc) · 13.6 KB
/
submissions_actions.py
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
"""
Base stateless API actions for acting upon learner submissions
"""
import json
import logging
import os
from opaque_keys.edx.keys import CourseKey
from submissions.api import Submission, SubmissionError, SubmissionRequestError
from openassessment.fileupload.exceptions import FileUploadError
from openassessment.workflow.errors import AssessmentWorkflowError
from openassessment.xblock.apis.submissions.errors import (
DeleteNotAllowed,
EmptySubmissionError,
NoTeamToCreateSubmissionForError,
DraftSaveException,
OnlyOneFileAllowedException,
SubmissionValidationException,
AnswerTooLongException,
StudioPreviewException,
MultipleSubmissionsException,
SubmitInternalError,
UnsupportedFileTypeException
)
from openassessment.xblock.utils.notifications import send_staff_notification
from openassessment.xblock.utils.validation import validate_submission
from openassessment.xblock.utils.data_conversion import (
format_files_for_submission,
prepare_submission_for_serialization,
)
logger = logging.getLogger(__name__) # pylint: disable=invalid-name
def submit(text_responses, block_config_data, block_submission_data, block_workflow_data):
"""
Submit response for a student.
Args:
* text_responses - List of text responses for submission
* block_config_data - ORAConfigAPI
* block_submission_data - SubmissionAPI
* block_workflow_data - WorkflowAPI
"""
success, msg = validate_submission(
text_responses,
block_config_data.prompts,
block_config_data.translate,
block_config_data.text_response,
)
if not success:
raise SubmissionValidationException(msg)
student_item_dict = block_config_data.student_item_dict
# Short-circuit if no user is defined (as in Studio Preview mode)
# Since students can't submit, they will never be able to progress in the workflow
if block_config_data.in_studio_preview:
raise StudioPreviewException()
if block_submission_data.has_submitted:
raise MultipleSubmissionsException()
try:
# a submission for a team generates matching submissions for all members
if block_config_data.is_team_assignment():
return create_team_submission(
student_item_dict,
text_responses,
block_config_data,
block_submission_data,
block_workflow_data
)
else:
return create_submission(
student_item_dict,
text_responses,
block_config_data,
block_submission_data,
block_workflow_data
)
except SubmissionRequestError as err:
# Handle the case of an answer that's too long as a special case,
# so we can display a more specific error message.
# Although we limit the number of characters the user can
# enter on the client side, the submissions API uses the JSON-serialized
# submission to calculate length. If each character submitted
# by the user takes more than 1 byte to encode (for example, double-escaped
# newline characters or non-ASCII unicode), then the user might
# exceed the limits set by the submissions API. In that case,
# we display an error message indicating that the answer is too long.
answer_too_long = any(
"maximum answer size exceeded" in answer_err.lower()
for answer_err in err.field_errors.get("answer", [])
)
if answer_too_long:
logger.exception(f"Response exceeds maximum allowed size: {student_item_dict}")
max_size = f"({int(Submission.MAXSIZE / 1024)} KB)"
base_error = block_config_data.translate("Response exceeds maximum allowed size.")
extra_info = block_config_data.translate(
"Note: if you have a spellcheck or grammar check browser extension, "
"try disabling, reloading, and reentering your response before submitting."
)
raise AnswerTooLongException(f"{base_error} {max_size} {extra_info}") from err
msg = (
"The submissions API reported an invalid request error "
"when submitting a response for the user: {student_item}"
).format(student_item=student_item_dict)
logger.exception(msg)
raise
except EmptySubmissionError:
msg = (
"Attempted to submit submission for user {student_item}, "
"but submission contained no content."
).format(student_item=student_item_dict)
logger.exception(msg)
raise
except (
SubmissionError,
AssessmentWorkflowError,
NoTeamToCreateSubmissionForError,
) as e:
msg = (
"An unknown error occurred while submitting "
"a response for the user: {student_item}"
).format(
student_item=student_item_dict
)
logger.exception(msg)
raise SubmitInternalError from e
def create_submission(
student_item_dict,
submission_data,
block_config_data,
block_submission_data,
block_workflow_data
):
"""Creates submission for the submitted assessment response or a list for a team assessment."""
# Import is placed here to avoid model import at project startup.
from submissions import api
# Serialize the submission
submission_dict = prepare_submission_for_serialization(submission_data)
# Add files
uploaded_files = block_submission_data.files.get_uploads_for_submission()
submission_dict.update(format_files_for_submission(uploaded_files))
# Validate
if block_submission_data.submission_is_empty(submission_dict):
raise EmptySubmissionError
# Create submission
submission = api.create_submission(student_item_dict, submission_dict)
block_workflow_data.create_workflow(submission["uuid"])
# Set student submission_uuid
block_config_data._block.submission_uuid = submission["uuid"] # pylint: disable=protected-access
has_staff_step = block_workflow_data.workflow_requirements.get('staff', {}).get('required', False)
if has_staff_step:
if block_config_data.course:
course_id = block_config_data.course.id
else:
course_id = CourseKey.from_string(student_item_dict.get("course_id"))
send_staff_notification(
course_id,
student_item_dict.get("item_id"),
block_config_data._block.display_name # pylint: disable=protected-access
)
# Emit analytics event...
block_config_data.publish_event(
"openassessmentblock.create_submission",
{
"submission_uuid": submission["uuid"],
"attempt_number": submission["attempt_number"],
"created_at": submission["created_at"],
"submitted_at": submission["submitted_at"],
"answer": submission["answer"],
},
)
return submission
def create_team_submission(
student_item_dict,
submission_data,
block_config_data,
block_submission_data,
block_workflow_data
):
"""A student submitting for a team should generate matching submissions for every member of the team."""
if not block_config_data.has_team:
student_id = student_item_dict["student_id"]
course_id = block_config_data.course_id
msg = f"Student {student_id} has no team for course {course_id}"
logger.exception(msg)
raise NoTeamToCreateSubmissionForError(msg)
# Import is placed here to avoid model import at project startup.
from submissions import team_api
team_info = block_config_data.get_team_info()
# Serialize the submission
submission_dict = prepare_submission_for_serialization(submission_data)
# Add files
uploaded_files = block_submission_data.files.get_uploads_for_submission()
submission_dict.update(format_files_for_submission(uploaded_files))
# Validate
if block_submission_data.submission_is_empty(submission_dict):
raise EmptySubmissionError
submitter_anonymous_user_id = block_config_data.get_anonymous_user_id_from_xmodule_runtime()
user = block_config_data.get_real_user(submitter_anonymous_user_id)
anonymous_student_ids = block_config_data.get_anonymous_user_ids_for_team()
submission = team_api.create_submission_for_team(
block_config_data.course_id,
student_item_dict["item_id"],
team_info["team_id"],
user.id,
anonymous_student_ids,
submission_dict,
)
block_workflow_data.create_team_workflow(submission["team_submission_uuid"])
# Emit analytics event...
block_config_data.publish_event(
"openassessmentblock.create_team_submission",
{
"submission_uuid": submission["team_submission_uuid"],
"team_id": team_info["team_id"],
"attempt_number": submission["attempt_number"],
"created_at": submission["created_at"],
"submitted_at": submission["submitted_at"],
"answer": submission["answer"],
},
)
return submission
def save_submission_draft(student_submission_data, block_config_data, block_submission_data):
"""
Save the current student's response submission.
If the student already has a response saved, this will overwrite it.
Args:
data (dict): Data should have a single key 'submission' that contains
the text of the student's response. Optionally, the data could
have a 'file_urls' key that is the path to an associated file for
this submission.
suffix (str): Not used.
Returns:
dict: Contains a bool 'success' and unicode string 'msg'.
"""
success, msg = validate_submission(
student_submission_data,
block_config_data.prompts,
block_config_data.translate,
block_config_data.text_response,
)
if not success:
raise SubmissionValidationException(msg)
try:
block_submission_data.saved_response = json.dumps(prepare_submission_for_serialization(student_submission_data))
block_submission_data.has_saved = True
# Emit analytics event...
block_config_data.publish_event(
"openassessmentblock.save_submission",
{"saved_response": block_submission_data.saved_response},
)
except Exception as e: # pylint: disable=broad-except
raise DraftSaveException from e
def append_file_data(file_data, block_config, submission_info):
"""
Appends a list of file data to the current block state
Args:
block_config (ORAConfigAPI)
submission_info (SubmissionAPI)
files_to_append (list of {
'description': (str)
'name': (str)
'size': (int)
})
"""
try:
new_files = submission_info.files.file_manager.append_uploads(*file_data)
except FileUploadError as exc:
logger.exception(
"append_file_data: file description for data %s failed with error %s", file_data, exc, exc_info=True
)
raise
except Exception as exc: # pylint: disable=broad-except
logger.exception(
"append_file_data: unhandled exception for data %s. Error: %s", file_data, exc, exc_info=True
)
raise FileUploadError(exc) from exc
# Emit analytics event...
block_config.publish_event(
"openassessmentblock.save_files_descriptions",
{"saved_response": submission_info.files.saved_files_descriptions},
)
return new_files
def remove_uploaded_file(file_index, block_config, submission_info):
"""
Removes uploaded user file.
"""
file_key = submission_info.files.get_file_key(file_index)
if not submission_info.files.can_delete_file(file_index):
raise DeleteNotAllowed()
try:
submission_info.files.delete_uploaded_file(file_index)
# Emit analytics event...
block_config.publish_event(
"openassessmentblock.remove_uploaded_file",
{"student_item_key": file_key},
)
logger.debug("Deleted file %s", file_key)
except FileUploadError as exc:
logger.exception(
"FileUploadError: Error when deleting file %s : %s",
file_key,
exc,
exc_info=True,
)
raise
except Exception as exc: # pylint: disable=broad-except
logger.exception(
"FileUploadError: unhandled exception for %s. Error: %s",
file_key,
exc,
exc_info=True,
)
raise FileUploadError(exc) from exc
def get_upload_url(content_type, file_name, file_index, block_config, submission_info):
"""
Request a URL to be used for uploading content for a given file
Returns:
A URL to be used to upload content associated with this submission.
"""
if not block_config.allow_multiple_files:
if submission_info.files.has_any_file_in_upload_space():
raise OnlyOneFileAllowedException()
_, file_ext = os.path.splitext(file_name)
file_ext = file_ext.strip(".") if file_ext else None
# Validate that there are no data issues and file type is allowed
if not submission_info.files.is_supported_upload_type(file_ext, content_type):
raise UnsupportedFileTypeException(file_ext)
# Attempt to upload
try:
key = submission_info.files.get_file_key(file_index)
url = submission_info.files.get_upload_url(key, content_type)
return url
except FileUploadError:
logger.exception("FileUploadError:Error retrieving upload URL")
raise