Commit 607776e5 authored by Anthony Jacob's avatar Anthony Jacob
Browse files

advance on api and format with black

parent 7b9011f3
Loading
Loading
Loading
Loading
+2 −0
Original line number Diff line number Diff line
@@ -25,3 +25,5 @@ class Config:
    POSTGRES_DB = os.getenv("POSTGRES_DB")
    POSTGRES_USER = os.getenv("POSTGRES_USER")
    POSTGRES_PASSWORD = os.getenv("POSTGRES_PASSWORD")

    LOGO_DIR = os.getenv("LOGO_DIR")
+295 −0
Original line number Diff line number Diff line
from datetime import date, datetime
import os
import traceback
from flask import Blueprint, request, jsonify, current_app
from app.helpers.file import deleteFile, get_unique_filename
from helpers.security import require_auth
from helpers.limiter import limiter
from model.about.about import (
    insertUpdateAbout,
    getAbouts,
    getAboutsFull,
    getAbout,
    deleteAbout,
    updateAboutPicture,
)
from model.language.language import isLanguagCodeExists

about_bp = Blueprint("about", __name__)


@about_bp.route("/abouts", methods=["GET"])
@require_auth
@limiter.limit("1/second", override_defaults=False)
def get_abouts():
    about_ids = getAbouts()

    if about_ids is False:
        return jsonify({"error": "Database error"}), 500

    return jsonify({"abouts": about_ids})


@about_bp.route("/abouts/full", methods=["GET"])
@require_auth
@limiter.limit("1/second", override_defaults=False)
def get_abouts_full():
    abouts = getAboutsFull()

    if abouts is False:
        return jsonify({"error": "Database error"}), 500

    return jsonify({"abouts": abouts})


@about_bp.route("/abouts/<int:id>", methods=["GET"])
@require_auth
@limiter.limit("1/second", override_defaults=False)
def get_about(id):
    try:
        if not id:
            return jsonify({"error": "Missing About id"}), 400
        else:
            result = getAbout(id)
            if result == -1:
                return jsonify({"message": "about not found", "id": id}), 404
            elif result:
                return jsonify(result)
            else:
                return jsonify({"error": "Failed to get about"}), 500

    except Exception as e:
        return jsonify({"error": str(e)}), 500


@about_bp.route("/abouts", methods=["PUT" , "POST"])
@require_auth
@limiter.limit("1/second", override_defaults=False)
def create_update_about():
    try:
        data = request.get_json()
        translations = data.get("translations")


        if (not translations):
            return (
                    jsonify(
                        {
                            "error": "you must provide translations"
                        }
                    ),
                    400,
                )

        translationToUpdate: list = []
        for aboutTranslation in translations:

            if "content" not in aboutTranslation:
                return (
                    jsonify(
                        {
                            "error": "you must provide a content for each translations"
                        }
                    ),
                    400,
                )

            if "language_code" not in aboutTranslation:
                return (
                    jsonify(
                        {
                            "error": "you must provide a language_code for each translations"
                        }
                    ),
                    400,
                )
            elif not aboutTranslation["language_code"].strip():
                return jsonify({"error": "language_code can't be empty"}), 400
            elif not isLanguagCodeExists(aboutTranslation["language_code"]):
                return (
                    jsonify(
                        {
                            "error": f"language_code is not existing ({aboutTranslation['language_code']})"
                        }
                    ),
                    400,
                )
            else:
                translationToUpdate.append(aboutTranslation["language_code"])

        if len(translationToUpdate) != len(list(set(translationToUpdate))):
            return (
                jsonify(
                    {"error": "you provided multiple times the same language_code"}
                ),
                400,
            )

        about_id = insertUpdateAbout(translations)

        if about_id > 0:
            return (
                jsonify(
                    {"message": "About inserted/updated", "about_id": about_id}
                ),
                201,
            )
        else:
            return jsonify({"error": "Failed to insert about"}), 500

    except Exception as e:
        return jsonify({"error": str(e)}), 500


@about_bp.route("/abouts/<int:id>", methods=["DELETE"])
@require_auth
@limiter.limit("1/second", override_defaults=False)
def delete_about(id):
    try:
        if not id:
            return jsonify({"error": "Missing About id"}), 400
        else:
            about = getAbout(id)
            if about == -1:
                return jsonify({"message": "about not found", "id": id}), 404
            elif about:
                if deleteAbout(id):
                    return jsonify({"message": "about deleted", "id": id})
                else:
                    return jsonify({"error": "Failed to delete about"}), 500
            else:
                return jsonify({"error": "Failed to retrieve about"}), 500

    except Exception as e:
        return jsonify({"error": str(e)}), 500


@about_bp.route("/abouts/<int:id>/picture", methods=["DELETE"])
@require_auth
@limiter.limit("1/second", override_defaults=False)
def delete_about_picture(id):
    try:
        if not id:
            return jsonify({"error": "Missing About id"}), 400
        else:
            ExistingAbout = getAbout(id)
            if ExistingAbout == -1:
                return jsonify({"message": "about not found", "id": id}), 404
            elif ExistingAbout:

                updatedAbout = updateAboutPicture(id, None)

                fileDeleted = True
                if ExistingAbout["picture"]:
                    fileDeleted = deleteFile(
                        os.path.join(
                            current_app.config["LOGO_DIR"], ExistingAbout["picture"]
                        )
                    )

                if updatedAbout and fileDeleted:
                    return (
                        jsonify(
                            {
                                "message": "About picture deleted",
                                "id": 1,
                            }
                        ),
                        200,
                    )
                elif updatedAbout and not fileDeleted:
                    return (
                        jsonify(
                            {
                                "message": "About picture updated in db but file not deleted",
                                "id": 1,
                            }
                        ),
                        200,
                    )
                else:
                    return jsonify({"error": "Failed to delete about picture"}), 500
            else:
                return jsonify({"error": "Failed to delete about picture"}), 500

    except Exception as e:
        return jsonify({"error": str(e)}), 500


@about_bp.route("/abouts/<int:id>/picture", methods=["POST"])
@require_auth
@limiter.limit("1/second", override_defaults=False)
def upload_about_picture(id):
    try:
        if not id:
            return jsonify({"error": "Missing About id"}), 400
        else:
            ExistingAbout = getAbout(id)
            if ExistingAbout == -1:
                return jsonify({"message": "about not found", "id": id}), 404
            elif ExistingAbout:
                if not request.files["file"]:
                    return jsonify({"error": "you have to provide a picture"}), 400

                file = request.files["file"]
                unique_filename = get_unique_filename(
                    current_app.config["LOGO_DIR"], file.filename
                )
                file_path = os.path.join(
                    current_app.config["LOGO_DIR"], unique_filename
                )
                file.save(file_path)

                updatedAbout = updateAboutPicture(id, unique_filename)

                fileDeleted = True
                if (
                    ExistingAbout["picture"]
                    and ExistingAbout["picture"] != unique_filename
                ):
                    fileDeleted = deleteFile(
                        os.path.join(
                            current_app.config["LOGO_DIR"], ExistingAbout["picture"]
                        )
                    )

                if updatedAbout and fileDeleted:
                    return (
                        jsonify(
                            {
                                "message": "About picture updated",
                                "id": 1,
                            }
                        ),
                        200,
                    )
                elif updatedAbout and not fileDeleted:
                    return (
                        jsonify(
                            {
                                "message": "About picture updated but file not deleted",
                                "id": 1,
                            }
                        ),
                        200,
                    )
                else:
                    return jsonify({"error": "Failed to update about picture"}), 500
            else:
                return jsonify({"error": "Failed to update about picture"}), 500

    except Exception as e:
        # Capture full traceback for debugging
        error_details = traceback.format_exc()

        return (
            jsonify(
                {
                    "error": f"""
                    - Exception: {type(e).__name__} - {str(e)}
                                - Traceback: {error_details}
                                """
                }
            ),
            500,
        )
+30 −10
Original line number Diff line number Diff line
from datetime import date, datetime
from gettext import translation
from flask import Blueprint, request, jsonify, current_app
from helpers.security import require_auth
from helpers.limiter import limiter
from model.diploma.diploma import (
    deleteDiplomaTranslation,
    insertDiploma,
    getDiplomas,
    getDiplomasFull,
    getDiploma,
    deleteDiploma,
    isDiplomaTranslationExists,
    updateDiploma,
)
from model.language.language import isLanguagCodeExists
@@ -120,17 +121,14 @@ def create_diploma():
            else:
                translationToUpdate.append(diplomaTranslation["language_code"])

        if(len(translationToUpdate) != len(list(set(translationToUpdate)))):
        if len(translationToUpdate) != len(list(set(translationToUpdate))):
            return (
                jsonify(
                        {
                            "error": "you provided multiple times the same language_code"
                        }
                    {"error": "you provided multiple times the same language_code"}
                ),
                400,
            )


        diploma_id = insertDiploma(start_date, end_date, translations)

        if diploma_id > 0:
@@ -246,3 +244,25 @@ def delete_diploma(id):

    except Exception as e:
        return jsonify({"error": str(e)}), 500

@diploma_bp.route("/diplomas/<int:id>/<language_code>", methods=["DELETE"])
@require_auth
@limiter.limit("1/second", override_defaults=False)
def delete_diploma_translation(id, language_code):
    try:
        if not id:
            return jsonify({"error": "Missing Diploma id"}), 400
        elif not language_code:
            return jsonify({"error": "Missing Diploma language_code"}), 400
        else:
            diploma = isDiplomaTranslationExists(id, language_code)
            if not diploma:
                return jsonify({"message": "diploma not found", "id": id}), 404
            elif diploma:
                if deleteDiplomaTranslation(id, language_code):
                    return jsonify({"message": "diploma translation deleted", "id": id})
                else:
                    return jsonify({"error": "Failed to delete diploma translation"}), 500

    except Exception as e:
        return jsonify({"error": str(e)}), 500
+456 −0

File added.

Preview size limit exceeded, changes collapsed.

+37 −56
Original line number Diff line number Diff line
@@ -12,7 +12,7 @@ from model.keyword.keyword import (
    deleteKeyword,
    updateKeyword,
    getLastPosition,
    isKeywordExists
    isKeywordExists,
)

keyword_bp = Blueprint("keyword", __name__)
@@ -62,7 +62,6 @@ def get_keyword(id):
        return jsonify({"error": str(e)}), 500



@keyword_bp.route("/keywords", methods=["PUT"])
@require_auth
@limiter.limit("1/second", override_defaults=False)
@@ -78,49 +77,32 @@ def create_keyword():

        if "language_code" not in data:
            return (
                    jsonify(
                        {
                            "error": "you must provide a language_code for the keyword"
                        }
                    ),
                jsonify({"error": "you must provide a language_code for the keyword"}),
                400,
            )
        elif not language_code.strip():
            return jsonify({"error": "language_code can't be empty"}), 400
        elif not isLanguagCodeExists(language_code):
            return (
                jsonify(
                    {
                        "error": f"language_code is not existing ({language_code})"
                    }
                ),
                jsonify({"error": f"language_code is not existing ({language_code})"}),
                400,
            )


        if "position" in data and isinstance(data.get("position"), int):
            position = data.get("position")
        elif "position" in data:
            return (
                jsonify(
                    {
                        "error": "if you provide position, it must be an integer"
                    }
                ),
                jsonify({"error": "if you provide position, it must be an integer"}),
                400,
            )

        if(isKeywordExists(keyword, language_code)):
        if isKeywordExists(keyword, language_code):
            return (
                jsonify(
                    {
                        "error": "The keyword already exists for this language"
                    }
                ),
                jsonify({"error": "The keyword already exists for this language"}),
                400,
            )

        if(position is None):
        if position is None:
            position = getLastPosition(language_code) + 1

        languageID = getLanguageByCode(language_code)["id"]
@@ -158,7 +140,6 @@ def update_keyword(id):
                language_code = data.get("language_code")
                position = data.get("position")


                if "keyword" not in data:
                    return jsonify({"error": "Missing keyword"}), 400

@@ -186,25 +167,25 @@ def update_keyword(id):
                if "position" not in data:
                    return (
                        jsonify(
                                {
                                    "error": "you must provide a position for the keyword"
                                }
                            {"error": "you must provide a position for the keyword"}
                        ),
                        400,
                    )
                elif not isinstance(data.get("position"), int):
                    return (
                        jsonify(
                            {
                                "error": "if you provide position, it must be an integer"
                            }
                            {"error": "if you provide position, it must be an integer"}
                        ),
                        400,
                    )

                existingKeyword = getKeywordByCode(keyword, language_code)
                print(existingKeyword)
                if(existingKeyword and existingKeyword != -1 and existingKeyword["id"] != id ):
                if (
                    existingKeyword
                    and existingKeyword != -1
                    and existingKeyword["id"] != id
                ):
                    return (
                        jsonify(
                            {
@@ -214,7 +195,6 @@ def update_keyword(id):
                        400,
                    )


                languageID = getLanguageByCode(language_code)["id"]
                updatedKeyword = updateKeyword(id, keyword, languageID, position)
                # updatedKeyword = -2
@@ -222,13 +202,17 @@ def update_keyword(id):
                if updatedKeyword == -2:
                    return (
                        jsonify(
                            {"error": "keyword code is already used by another keyword Id"}
                            {
                                "error": "keyword code is already used by another keyword Id"
                            }
                        ),
                        500,
                    )
                elif updatedKeyword:
                    return (
                        jsonify({"message": "Keyword updated", "keyword": updatedKeyword}),
                        jsonify(
                            {"message": "Keyword updated", "keyword": updatedKeyword}
                        ),
                        200,
                    )
                else:
@@ -238,10 +222,7 @@ def update_keyword(id):
        error_message = str(e)
        stack_trace = traceback.format_exc()  # Capture full stack trace as a string

        return jsonify({
            "error": error_message,
            "stack_trace": stack_trace
        }), 500
        return jsonify({"error": error_message, "stack_trace": stack_trace}), 500


@keyword_bp.route("/keywords/<int:id>", methods=["DELETE"])
Loading