Skip to content

Commit

Permalink
Move depend_on_either_json_or_form_data function from tool_shed to ga…
Browse files Browse the repository at this point in the history
…laxy
  • Loading branch information
heisner-tillman committed Feb 8, 2024
1 parent 58f27cd commit e6d144c
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 30 deletions.
27 changes: 27 additions & 0 deletions lib/galaxy/webapps/galaxy/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import inspect
from enum import Enum
from json import JSONDecodeError
from string import Template
from typing import (
Any,
Expand All @@ -26,6 +27,7 @@
APIRouter,
Form,
Header,
HTTPException,
Query,
Request,
Response,
Expand Down Expand Up @@ -105,6 +107,8 @@ async def get_app_with_request_session() -> AsyncGenerator[StructuredApp, None]:

T = TypeVar("T")

B = TypeVar("B", bound=BaseModel)


class GalaxyTypeDepends(Depends):
"""Variant of fastapi Depends that can also work on WSGI Galaxy controllers."""
Expand Down Expand Up @@ -588,3 +592,26 @@ def search_query_param(model_name: str, tags: list, free_text_fields: list) -> O
title="Search query.",
description=description,
)


# TODO: mypy complains that Depends(get_body) is returned B is expected.
# def depend_on_either_json_or_form_data(model: Type[B]) -> B:
def depend_on_either_json_or_form_data(model: Type[B]):
async def get_body(request: Request):
content_type = request.headers.get("Content-Type")
if content_type is None:
raise HTTPException(status_code=400, detail="No Content-Type provided!")
elif content_type == "application/json":
try:
return model(**await request.json())
except JSONDecodeError:
raise HTTPException(status_code=400, detail="Invalid JSON data")
elif content_type == "application/x-www-form-urlencoded" or content_type.startswith("multipart/form-data"):
try:
return model(**await request.form())
except Exception:
raise HTTPException(status_code=400, detail="Invalid Form data")
else:
raise HTTPException(status_code=400, detail="Content-Type not supported!")

return Depends(get_body)
28 changes: 0 additions & 28 deletions lib/tool_shed/webapp/api2/__init__.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
import logging
from json import JSONDecodeError
from typing import (
AsyncGenerator,
cast,
List,
Optional,
Type,
TypeVar,
)

from fastapi import (
Depends,
HTTPException,
Path,
Query,
Request,
Expand All @@ -23,7 +20,6 @@
APIKeyHeader,
APIKeyQuery,
)
from pydantic import BaseModel
from starlette_context import context as request_context

from galaxy.exceptions import AdminRequiredException
Expand Down Expand Up @@ -159,34 +155,10 @@ class Router(FrameworkRouter):
admin_user_dependency = AdminUserRequired


B = TypeVar("B", bound=BaseModel)


# async def depend_on_either_json_or_form_data(model: Type[T]):
# return Depends(get_body)


def depend_on_either_json_or_form_data(model: Type[B]) -> B:
async def get_body(request: Request):
content_type = request.headers.get("Content-Type")
if content_type is None:
raise HTTPException(status_code=400, detail="No Content-Type provided!")
elif content_type == "application/json":
try:
return model(**await request.json())
except JSONDecodeError:
raise HTTPException(status_code=400, detail="Invalid JSON data")
elif content_type == "application/x-www-form-urlencoded" or content_type.startswith("multipart/form-data"):
try:
return model(**await request.form())
except Exception:
raise HTTPException(status_code=400, detail="Invalid Form data")
else:
raise HTTPException(status_code=400, detail="Content-Type not supported!")

return Depends(get_body)


UserIdPathParam: str = Path(..., title="User ID", description="The encoded database identifier of the user.")

RequiredRepoOwnerParam: str = Query(
Expand Down
6 changes: 4 additions & 2 deletions lib/tool_shed/webapp/api2/repositories.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@

from galaxy.exceptions import InsufficientPermissionsException
from galaxy.model.base import transaction
from galaxy.webapps.galaxy.api import as_form
from galaxy.webapps.galaxy.api import (
as_form,
depend_on_either_json_or_form_data,
)
from tool_shed.context import SessionRequestContext
from tool_shed.managers.repositories import (
can_manage_repo,
Expand Down Expand Up @@ -62,7 +65,6 @@
from . import (
ChangesetRevisionPathParam,
CommitMessageQueryParam,
depend_on_either_json_or_form_data,
depends,
DependsOnTrans,
DownloadableQueryParam,
Expand Down

0 comments on commit e6d144c

Please sign in to comment.