Skip to content

Commit

Permalink
🧹 Jsonify() to make_response() (#5558)
Browse files Browse the repository at this point in the history
Fixes #4029 
Fixes #3616
  • Loading branch information
Annelein authored Jun 4, 2024
1 parent 254f68c commit 663a364
Show file tree
Hide file tree
Showing 75 changed files with 1,097 additions and 1,489 deletions.
81 changes: 42 additions & 39 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@

import static_babel_content
from markupsafe import Markup
from flask import (Flask, Response, abort, after_this_request, g, make_response,
redirect, request, send_file, url_for, jsonify,
from flask import (Flask, Response, abort, after_this_request, g, jsonify, make_response,
redirect, request, send_file, url_for,
send_from_directory, session)
from flask_babel import Babel, gettext
from website.flask_commonmark import Commonmark
Expand Down Expand Up @@ -423,7 +423,7 @@ def setup_language():

# Check that requested language is supported, otherwise return 404
if g.lang not in ALL_LANGUAGES.keys():
return "Language " + g.lang + " not supported", 404
return make_response(gettext("request_invalid"), 404)


if utils.is_heroku() and not os.getenv('HEROKU_RELEASE_CREATED_AT'):
Expand Down Expand Up @@ -507,34 +507,34 @@ def teardown_request_finish_logging(exc):
@app.route('/session_test', methods=['GET'])
def echo_session_vars_test():
if not utils.is_testing_request(request):
return 'This endpoint is only meant for E2E tests', 400
return jsonify({'session': dict(session)})
return make_response(gettext("request_invalid"), 400)
return make_response({'session': dict(session)})


@app.route('/session_main', methods=['GET'])
def echo_session_vars_main():
if not utils.is_testing_request(request):
return 'This endpoint is only meant for E2E tests', 400
return jsonify({'session': dict(session),
'proxy_enabled': bool(os.getenv('PROXY_TO_TEST_HOST'))})
return make_response(gettext("request_invalid"), 400)
return make_response({'session': dict(session),
'proxy_enabled': bool(os.getenv('PROXY_TO_TEST_HOST'))})


@app.route('/parse', methods=['POST'])
@querylog.timed_as('parse_handler')
def parse():
body = request.json
if not body:
return "body must be an object", 400
return make_response(gettext("request_invalid"), 400)
if 'code' not in body:
return "body.code must be a string", 400
return make_response(gettext("request_invalid"), 400)
if 'level' not in body:
return "body.level must be a string", 400
return make_response(gettext("request_invalid"), 400)
if 'adventure_name' in body and not isinstance(body['adventure_name'], str):
return "if present, body.adventure_name must be a string", 400
return make_response(gettext("request_invalid"), 400)
if 'is_debug' not in body:
return "body.is_debug must be a boolean", 400
return make_response(gettext("request_invalid"), 400)
if 'raw' not in body:
return "body.raw is missing", 400
return make_response(gettext("request_invalid"), 400)
error_check = False
if 'error_check' in body:
error_check = True
Expand Down Expand Up @@ -670,7 +670,7 @@ def parse():

if "Error" in response and error_check:
response["message"] = gettext('program_contains_error')
return jsonify(response)
return make_response(response, 200)


@app.route('/parse-by-id', methods=['POST'])
Expand All @@ -693,9 +693,9 @@ def parse_by_id(user):
)
return make_response('', 204)
except BaseException:
return {"error": "parsing error"}, 200
make_response(gettext("request_invalid"), 200)
else:
return 'this is not your program!', 400
return make_response(gettext("request_invalid"), 400)


@app.route('/parse_tutorial', methods=['POST'])
Expand All @@ -707,9 +707,10 @@ def parse_tutorial(user):
level = try_parse_int(body['level'])
try:
result = hedy.transpile(code, level, "en")
jsonify({'code': result.code}), 200
# this is not a return, is this code needed?
make_response(({'code': result.code}), 200)
except BaseException:
return "error", 400
return make_response(gettext("request_invalid"), 400)


@app.route("/generate_machine_files", methods=['POST'])
Expand Down Expand Up @@ -750,7 +751,7 @@ def prepare_files():
zip_file.write('machine_files/' + file)
zip_file.close()

return jsonify({'filename': filename}), 200
return make_response({'filename': filename}, 200)


@app.route("/download_machine_files/<filename>", methods=['GET'])
Expand Down Expand Up @@ -784,9 +785,10 @@ def generate_microbit_file():

transpile_result = hedy.transpile_and_return_python(code, level)
save_transpiled_code_for_microbit(transpile_result)
return jsonify({'filename': 'Micro-bit.py', 'microbit': True}), 200
return make_response({'filename': 'Micro-bit.py', 'microbit': True}, 200)
else:
return jsonify({'message': 'Microbit feature is disabled'}), 403
# TODO
return make_response({'message': 'Microbit feature is disabled'}, 403)


def save_transpiled_code_for_microbit(transpiled_python_code):
Expand Down Expand Up @@ -824,7 +826,8 @@ def remove_file(response):

return send_file(os.path.join(micro_bit_directory, "micropython.hex"), as_attachment=True)
else:
return jsonify({'message': 'Microbit feature is disabled'}), 403
# TODO
return make_response({'message': 'Microbit feature is disabled'}, 403)


def flash_micro_bit():
Expand Down Expand Up @@ -1084,7 +1087,7 @@ def query_logs():

(exec_id, status) = log_fetcher.query(body)
response = {'query_status': status, 'query_execution_id': exec_id}
return jsonify(response)
return make_response(response, 200)


@app.route('/logs/results', methods=['GET'])
Expand All @@ -1100,7 +1103,7 @@ def get_log_results():
data, next_token = log_fetcher.get_query_results(
query_execution_id, next_token)
response = {'data': data, 'next_token': next_token}
return jsonify(response)
return make_response(response, 200)


@app.route('/tutorial', methods=['GET'])
Expand Down Expand Up @@ -2254,6 +2257,7 @@ def change_language():
# Remove 'keyword_lang' from session, it will automatically be renegotiated from 'lang'
# on the next page load.
session.pop('keyword_lang')
# if this is changed to make_response(), it gives an error, I don't know why
return jsonify({'success': 204})


Expand Down Expand Up @@ -2286,11 +2290,11 @@ def translate_keywords():
if translated_code or translated_code == '': # empty string is False, so explicitly allow it
session["previous_keyword_lang"] = body.get("start_lang")
session["keyword_lang"] = body.get("goal_lang")
return jsonify({'success': 200, 'code': translated_code})
return make_response({'code': translated_code}, 200)
else:
return gettext('translate_error'), 400
return make_response(gettext("translate_error"), 400)
except BaseException:
return gettext('translate_error'), 400
return make_response(gettext('translate_error'), 400)


# TODO TB: Think about changing this to sending all steps to the front-end at once
Expand All @@ -2299,17 +2303,17 @@ def get_tutorial_translation(level, step):
# Keep this structure temporary until we decide on a nice code / parse structure
if step == "code_snippet":
code = hedy_content.deep_translate_keywords(gettext('tutorial_code_snippet'), g.keyword_lang)
return jsonify({'code': code}), 200
return make_response({'code': code}, 200)
try:
step = int(step)
except ValueError:
return gettext('invalid_tutorial_step'), 400
return make_response(gettext('invalid_tutorial_step'), 400)

data = TUTORIALS[g.lang].get_tutorial_for_level_step(level, step, g.keyword_lang)
if not data:
data = {'title': gettext('tutorial_title_not_found'),
'text': gettext('tutorial_message_not_found')}
return jsonify(data), 200
return make_response((data), 200)


@app.route('/store_parsons_order', methods=['POST'])
Expand Down Expand Up @@ -2557,20 +2561,20 @@ def update_public_profile(user):

# Validations
if not isinstance(body, dict):
return gettext('ajax_error'), 400
return make_response(gettext('ajax_error'), 400)
# The images are given as a "picture id" from 1 till 12
if not isinstance(body.get('image'), str) or int(body.get('image'), 0) not in [*range(1, 13)]:
return gettext('image_invalid'), 400
return make_response(gettext('image_invalid'), 400)
if not isinstance(body.get('personal_text'), str):
return gettext('personal_text_invalid'), 400
return make_response(gettext('personal_text_invalid'), 400)
if 'favourite_program' in body and not isinstance(body.get('favourite_program'), str):
return gettext('favourite_program_invalid'), 400
return make_response(gettext('favourite_program_invalid'), 400)

# Verify that the set favourite program is actually from the user (and public)!
if 'favourite_program' in body:
program = DATABASE.program_by_id(body.get('favourite_program'))
if not program or program.get('username') != user['username'] or not program.get('public'):
return gettext('favourite_program_invalid'), 400
return make_response(gettext('favourite_program_invalid'), 400)

achievement = None
current_profile = DATABASE.get_public_profile_settings(user['username'])
Expand All @@ -2595,9 +2599,8 @@ def update_public_profile(user):

DATABASE.update_public_profile(user['username'], body)
if achievement:
# Todo TB -> Check if we require message or success on front-end
return {'message': gettext('public_profile_updated'), 'achievement': achievement}, 200
return {'message': gettext('public_profile_updated')}, 200
utils.add_pending_achievement({"achievement": achievement})
return make_response(gettext("public_profile_updated"), 200)


@app.route('/translating')
Expand Down
3 changes: 3 additions & 0 deletions messages.pot
Original file line number Diff line number Diff line change
Expand Up @@ -1427,6 +1427,9 @@ msgstr ""
msgid "report_success"
msgstr ""

msgid "request_invalid"
msgstr ""

msgid "request_teacher"
msgstr ""

Expand Down
5 changes: 2 additions & 3 deletions static/js/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1573,8 +1573,7 @@ export function toggle_keyword_language(current_lang: string, new_lang: string)
goal_lang: new_lang,
level: theLevel,
});

if (response.success) {
if (response) {
const code = response.code
theGlobalEditor.contents = code;
const saveName = saveNameFromInput();
Expand Down Expand Up @@ -1620,7 +1619,7 @@ export function toggle_blur_code() {
export async function change_language(lang: string) {
await tryCatchPopup(async () => {
const response = await postJsonWithAchievements('/change_language', { lang });
if (response.success) {
if (response) {
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);

Expand Down
8 changes: 4 additions & 4 deletions static/js/appbundle.js
Original file line number Diff line number Diff line change
Expand Up @@ -60574,15 +60574,15 @@ ${o3}` : i3;
"Transpile_success": "Good job!\nAmazing!\nWell done!\nExcellent!\nYou did great!",
"Transpile_warning": "\u0412\u043D\u0438\u043C\u0430\u043D\u0438\u0435!",
"Unsaved_Changes": "You have an unsaved program. Do you want to leave without saving it?",
"adventures_restored": "The default adventures have been restored!",
"adventures_restored": "The default adventures have been restored.",
"copy_link_to_share": "Copy link to share",
"customization_deleted": "Customizations successfully deleted.",
"dice": "\u{1F3B2}",
"directly_available": "Directly open",
"disabled": "Disabled",
"fortune": "\u{1F52E}, \u2728",
"haunted": "\u{1F987}, \u{1F47B}, \u{1F383}",
"level_title": "\u041D\u0438\u0432\u043E",
"level_title": "Level",
"multiple_keywords_warning": "You are trying to use the keyword {orig_keyword}, but this keyword might have several meanings. Please choose the one you're trying to use from this list and copy paste it in your code, curly braces included: {keyword_list}",
"restaurant": "\u{1F363}, \u{1F355}, \u{1F354}",
"rock": "\u2702\uFE0F, \u{1F4DC}, \u{1F5FB}",
Expand Down Expand Up @@ -105923,7 +105923,7 @@ def note_with_error(value, err):
goal_lang: new_lang,
level: theLevel
});
if (response.success) {
if (response) {
const code = response.code;
theGlobalEditor.contents = code;
const saveName = saveNameFromInput();
Expand Down Expand Up @@ -105956,7 +105956,7 @@ def note_with_error(value, err):
async function change_language(lang) {
await tryCatchPopup(async () => {
const response = await postJsonWithAchievements("/change_language", { lang });
if (response.success) {
if (response) {
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
if (lang === "en" || urlParams.get("language") !== null) {
Expand Down
4 changes: 2 additions & 2 deletions static/js/appbundle.js.map

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions static/js/message-translations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,15 @@ export const TRANSLATIONS: Record<string, Record<MessageKey, string>> = {
"Transpile_success": "Good job!\nAmazing!\nWell done!\nExcellent!\nYou did great!",
"Transpile_warning": "Внимание!",
"Unsaved_Changes": "You have an unsaved program. Do you want to leave without saving it?",
"adventures_restored": "The default adventures have been restored!",
"adventures_restored": "The default adventures have been restored.",
"copy_link_to_share": "Copy link to share",
"customization_deleted": "Customizations successfully deleted.",
"dice": "🎲",
"directly_available": "Directly open",
"disabled": "Disabled",
"fortune": "🔮, ✨",
"haunted": "🦇, 👻, 🎃",
"level_title": "Ниво",
"level_title": "Level",
"multiple_keywords_warning": "You are trying to use the keyword {orig_keyword}, but this keyword might have several meanings. Please choose the one you're trying to use from this list and copy paste it in your code, curly braces included: {keyword_list}",
"restaurant": "🍣, 🍕, 🍔",
"rock": "✂️, 📜, 🗻",
Expand Down
2 changes: 1 addition & 1 deletion tests/cypress/e2e/feedback/feedback_modal.cy.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,6 @@ describe("Test the feedback feature", () => {
cy.getDataCy('modal_feedback_input')
.should("not.be.visible")

cy.wait("@postFeedback").should('have.nested.property', 'response.statusCode', 200)
cy.wait("@postFeedback").should('have.nested.property', 'response.statusCode', 204)
});
});
3 changes: 3 additions & 0 deletions translations/ar/LC_MESSAGES/messages.po
Original file line number Diff line number Diff line change
Expand Up @@ -1644,6 +1644,9 @@ msgstr "Are you sure you want to report this program?"
msgid "report_success"
msgstr "This program has been reported"

msgid "request_invalid"
msgstr ""

msgid "request_teacher"
msgstr "هل ترغب في التقدم بطلب للحصول على حساب المعلم؟"

Expand Down
Loading

0 comments on commit 663a364

Please sign in to comment.