From 4538ecc169e1ed7c4b797643e3cbac430d8ec350 Mon Sep 17 00:00:00 2001 From: CyberFlame Date: Thu, 19 Oct 2023 23:11:37 +1300 Subject: [PATCH] fix: get json POST handling functional Signed-off-by: CyberFlame --- .eslintrc.json | 5 ++++ .idea/DTSCodingDB.iml | 6 ++++ .idea/codeStyles/Project.xml | 2 +- .idea/cssdialects.xml | 6 ++++ .idea/jsLibraryMappings.xml | 1 - .idea/misc.xml | 2 +- .idea/runConfigurations/Run_project.xml | 16 +++++++++++ .jshintrc | 3 +- .prettierrc | 3 +- .stylelintrc.json | 1 - app.py | 25 +++++++--------- pdm.lock | 20 ++++++------- static/js/utils.js | 38 ++++++++++++++++++++++++- templates/games.html | 18 ++---------- templates/register.html | 32 +++++++-------------- 15 files changed, 111 insertions(+), 67 deletions(-) create mode 100644 .eslintrc.json create mode 100644 .idea/cssdialects.xml create mode 100644 .idea/runConfigurations/Run_project.xml diff --git a/.eslintrc.json b/.eslintrc.json new file mode 100644 index 0000000..846d999 --- /dev/null +++ b/.eslintrc.json @@ -0,0 +1,5 @@ +{ + "rules": { + "space-before-function-paren": "off" + } +} diff --git a/.idea/DTSCodingDB.iml b/.idea/DTSCodingDB.iml index fad2ecd..dccc140 100644 --- a/.idea/DTSCodingDB.iml +++ b/.idea/DTSCodingDB.iml @@ -13,6 +13,12 @@ + + + + diff --git a/.idea/runConfigurations/Run_project.xml b/.idea/runConfigurations/Run_project.xml new file mode 100644 index 0000000..d64287c --- /dev/null +++ b/.idea/runConfigurations/Run_project.xml @@ -0,0 +1,16 @@ + + + + \ No newline at end of file diff --git a/.jshintrc b/.jshintrc index 711f4c4..1876015 100644 --- a/.jshintrc +++ b/.jshintrc @@ -1,3 +1,4 @@ { - "esversion": 11 + "esversion": 11, + "browser": true } diff --git a/.prettierrc b/.prettierrc index e698378..2d393b3 100644 --- a/.prettierrc +++ b/.prettierrc @@ -2,5 +2,6 @@ "trailingComma": "es5", "tabWidth": 4, "semi": true, - "singleQuote": true + "singleQuote": true, + "bracketSpacing": false } diff --git a/.stylelintrc.json b/.stylelintrc.json index 48e96fe..3e6d5c3 100644 --- a/.stylelintrc.json +++ b/.stylelintrc.json @@ -3,6 +3,5 @@ "stylelint-config-standard" ], "rules": { - } } diff --git a/app.py b/app.py index 9332d4c..4fc2cde 100644 --- a/app.py +++ b/app.py @@ -39,6 +39,7 @@ class Endpoint(Enum): """ Enum of endpoints """ + GAMES = "games" LOGIN = "login" REGISTER = "register" @@ -90,8 +91,8 @@ async def home(request: Request): @app.post("/token", response_model=Token) async def authenticate( - form_data: Annotated[OAuth2PasswordRequestForm, Depends()], - session: Session, + form_data: Annotated[OAuth2PasswordRequestForm, Depends()], + session: Session, ): user = await Auth.authenticate_user(session, form_data.username, form_data.password) if not user: @@ -101,23 +102,17 @@ async def authenticate( headers={"WWW-Authenticate": "Bearer"}, ) access_token_expires = timedelta(minutes=Auth.ACCESS_TOKEN_EXPIRE_MINUTES) - access_token = Auth.create_access_token( - data={"sub": user.username}, expires_delta=access_token_expires - ) + access_token = Auth.create_access_token(data={"sub": user.username}, expires_delta=access_token_expires) return {"access_token": access_token, "token_type": "bearer"} @app.get("/users/me/", response_model=PydanticUser) -async def read_users_me( - current_user: Current_Active_User -): +async def read_users_me(current_user: Current_Active_User): return current_user @app.get("/users/me/items/") -async def read_own_items( - current_user: Current_Active_User -): +async def read_own_items(current_user: Current_Active_User): return [{"item_id": "Foo", "owner": current_user.username}] @@ -132,7 +127,7 @@ async def records_list(request: Request, session: Session, endpoint: str): """ model, endpoint_type = classify(endpoint) if model is None: - return Response(status_code = status.HTTP_404_NOT_FOUND) + return Response(status_code=status.HTTP_404_NOT_FOUND) context: dict = { "request": request, } @@ -173,7 +168,7 @@ async def new_record(request: Request, session: Session, endpoint: str): first_name=form.get("first_name"), last_name=form.get("last_name"), year_level=form.get("year_level"), - house=form.get("house") + house=form.get("house"), ) case _: return Response(status_code=status.HTTP_404_NOT_FOUND) @@ -181,7 +176,9 @@ async def new_record(request: Request, session: Session, endpoint: str): await db.insert(session, model_instance) except IntegrityError: return Response(status_code=status.HTTP_409_CONFLICT) - return JSONResponse(content={"redirectUrl": f"/{endpoint}"}, status_code=status.HTTP_303_SEE_OTHER) + if endpoint_type == Endpoint.REGISTER: + return JSONResponse(content={"redirectUrl": f"/"}, status_code=status.HTTP_303_SEE_OTHER) + return JSONResponse(content={"redirectUrl": f"/{endpoint_type.value}"}, status_code=status.HTTP_303_SEE_OTHER) @app.patch("/{endpoint}/{identifier}", response_class=HTMLResponse) diff --git a/pdm.lock b/pdm.lock index d57883d..45d1cdf 100644 --- a/pdm.lock +++ b/pdm.lock @@ -226,29 +226,29 @@ files = [ [[package]] name = "fastapi" -version = "0.103.2" -requires_python = ">=3.7" +version = "0.104.0" +requires_python = ">=3.8" summary = "FastAPI framework, high performance, easy to learn, fast to code, ready for production" dependencies = [ "anyio<4.0.0,>=3.7.1", "pydantic!=1.8,!=1.8.1,!=2.0.0,!=2.0.1,!=2.1.0,<3.0.0,>=1.7.4", "starlette<0.28.0,>=0.27.0", - "typing-extensions>=4.5.0", + "typing-extensions>=4.8.0", ] files = [ - {file = "fastapi-0.103.2-py3-none-any.whl", hash = "sha256:3270de872f0fe9ec809d4bd3d4d890c6d5cc7b9611d721d6438f9dacc8c4ef2e"}, - {file = "fastapi-0.103.2.tar.gz", hash = "sha256:75a11f6bfb8fc4d2bec0bd710c2d5f2829659c0e8c0afd5560fdda6ce25ec653"}, + {file = "fastapi-0.104.0-py3-none-any.whl", hash = "sha256:456482c1178fb7beb2814b88e1885bc49f9a81f079665016feffe3e1c6a7663e"}, + {file = "fastapi-0.104.0.tar.gz", hash = "sha256:9c44de45693ae037b0c6914727a29c49a40668432b67c859a87851fc6a7b74c6"}, ] [[package]] name = "fastapi" -version = "0.103.2" +version = "0.104.0" extras = ["all"] -requires_python = ">=3.7" +requires_python = ">=3.8" summary = "FastAPI framework, high performance, easy to learn, fast to code, ready for production" dependencies = [ "email-validator>=2.0.0", - "fastapi==0.103.2", + "fastapi==0.104.0", "httpx>=0.23.0", "itsdangerous>=1.1.0", "jinja2>=2.11.2", @@ -261,8 +261,8 @@ dependencies = [ "uvicorn[standard]>=0.12.0", ] files = [ - {file = "fastapi-0.103.2-py3-none-any.whl", hash = "sha256:3270de872f0fe9ec809d4bd3d4d890c6d5cc7b9611d721d6438f9dacc8c4ef2e"}, - {file = "fastapi-0.103.2.tar.gz", hash = "sha256:75a11f6bfb8fc4d2bec0bd710c2d5f2829659c0e8c0afd5560fdda6ce25ec653"}, + {file = "fastapi-0.104.0-py3-none-any.whl", hash = "sha256:456482c1178fb7beb2814b88e1885bc49f9a81f079665016feffe3e1c6a7663e"}, + {file = "fastapi-0.104.0.tar.gz", hash = "sha256:9c44de45693ae037b0c6914727a29c49a40668432b67c859a87851fc6a7b74c6"}, ] [[package]] diff --git a/static/js/utils.js b/static/js/utils.js index e957914..6bd3fe6 100644 --- a/static/js/utils.js +++ b/static/js/utils.js @@ -2,13 +2,49 @@ export default class ResourceManager { // The methods in this class are designed to have one point return for readability purposes. // This is noted here to explain the redundant-looking code in the methods below. + static handleFormSubmission(formId, conflictMessage) { + // This particular method has status codes hard-coded on purpose. + const HTTP_409_CONFLICT = 409; + const HTTP_303_SEE_OTHER = 303; + // Store reference to "this" context + const that = this; + document + .getElementById(formId) + .addEventListener('submit', async function (e) { + e.preventDefault(); + const form = this; + try { + const response = await that.sendRequest( + form.action, + 'POST', + new FormData(form) + ); + if (response.status === HTTP_409_CONFLICT) { + alert(conflictMessage); + } else if (response.status === HTTP_303_SEE_OTHER) { + const data = await response.json(); + console.log(data); + const redirectUrl = await data['redirectUrl']; // jshint ignore:line + console.log(redirectUrl); + if (redirectUrl) { + window.location.href = redirectUrl; + } + } + } catch (error) { + console.error('Error:', error); + } + }); + } + static async sendRequest(url, httpMethod, body) { const options = { method: httpMethod, headers: {}, }; - if (body) { + if (body instanceof FormData) { + options.body = body; + } else if (body) { options.body = JSON.stringify(body); options.headers['Content-Type'] = 'application/json'; } diff --git a/templates/games.html b/templates/games.html index a14a12c..9627f0c 100644 --- a/templates/games.html +++ b/templates/games.html @@ -63,21 +63,9 @@ } } }; - - {% endblock %} diff --git a/templates/register.html b/templates/register.html index 37f2dbd..d34b453 100644 --- a/templates/register.html +++ b/templates/register.html @@ -1,22 +1,12 @@ {% extends 'base.html' %} {% block head %} - {% endblock %} @@ -26,22 +16,22 @@

User Registration

-
+
-
+
-
+

-
+
-
+