back to OpenHands summary
OpenHands: flask
Failed to run pytests for test tests
ImportError while loading conftest '/testbed/tests/conftest.py'.
tests/conftest.py:8: in <module>
from flask import Flask
src/flask/__init__.py:6: in <module>
from .app import Flask as Flask
src/flask/app.py:25: in <module>
from . import cli
src/flask/cli.py:60: in <module>
version_option = click.Option(['--version'], help='Show the Flask version.', expose_value=False, callback=get_version, is_flag=True, is_eager=True)
E NameError: name 'get_version' is not defined
Patch diff
diff --git a/src/flask/json/__init__.py b/src/flask/json/__init__.py
index c0941d04..898aa49d 100644
--- a/src/flask/json/__init__.py
+++ b/src/flask/json/__init__.py
@@ -4,7 +4,7 @@ import json as _json
import typing as t
from ..globals import current_app
-from .provider import _default
+from .utils import _default
if t.TYPE_CHECKING: # pragma: no cover
from ..wrappers import Response
diff --git a/src/flask/json/provider.py b/src/flask/json/provider.py
index d5710af5..0753aea7 100644
--- a/src/flask/json/provider.py
+++ b/src/flask/json/provider.py
@@ -1,16 +1,14 @@
from __future__ import annotations
-import dataclasses
-import decimal
import json
import typing as t
-import uuid
import weakref
-from datetime import date
-from werkzeug.http import http_date
if t.TYPE_CHECKING:
from werkzeug.sansio.response import Response
from ..sansio.app import App
+from .utils import _default as _default_fn
+
+
class JSONProvider:
"""A standard set of JSON operations for an application. Subclasses
of this can be used to customize JSON behavior or use different
@@ -49,7 +47,7 @@ class JSONProvider:
encoding to be valid JSON.
:param kwargs: May be passed to the underlying JSON library.
"""
- pass
+ fp.write(self.dumps(obj, **kwargs))
def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:
"""Deserialize data as JSON.
@@ -65,7 +63,7 @@ class JSONProvider:
:param fp: A file opened for reading text or UTF-8 bytes.
:param kwargs: May be passed to the underlying JSON library.
"""
- pass
+ return self.loads(fp.read(), **kwargs)
def response(self, *args: t.Any, **kwargs: t.Any) -> Response:
"""Serialize the given arguments as JSON, and return a
@@ -84,6 +82,7 @@ class JSONProvider:
"""
pass
+
class DefaultJSONProvider(JSONProvider):
"""Provide JSON operations using Python's built-in :mod:`json`
library. Serializes the following additional data types:
@@ -97,7 +96,7 @@ class DefaultJSONProvider(JSONProvider):
- :class:`~markupsafe.Markup` (or any object with a ``__html__``
method) will call the ``__html__`` method to get a string.
"""
- default: t.Callable[[t.Any], t.Any] = staticmethod(_default)
+ default: t.Callable[[t.Any], t.Any] = staticmethod(_default_fn)
'Apply this function to any object that :meth:`json.dumps` does\n not know how to serialize. It should return a valid JSON type or\n raise a ``TypeError``.\n '
ensure_ascii = True
'Replace non-ASCII characters with escape sequences. This may be\n more compatible with some clients, but can be disabled for better\n performance and size.\n '
@@ -118,7 +117,10 @@ class DefaultJSONProvider(JSONProvider):
:param obj: The data to serialize.
:param kwargs: Passed to :func:`json.dumps`.
"""
- pass
+ kwargs.setdefault("default", self.default)
+ kwargs.setdefault("ensure_ascii", self.ensure_ascii)
+ kwargs.setdefault("sort_keys", self.sort_keys)
+ return json.dumps(obj, **kwargs)
def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:
"""Deserialize data as JSON from a string or bytes.
@@ -126,7 +128,9 @@ class DefaultJSONProvider(JSONProvider):
:param s: Text or UTF-8 bytes.
:param kwargs: Passed to :func:`json.loads`.
"""
- pass
+ if isinstance(s, bytes):
+ s = s.decode()
+ return json.loads(s, **kwargs)
def response(self, *args: t.Any, **kwargs: t.Any) -> Response:
"""Serialize the given arguments as JSON, and return a
@@ -144,4 +148,34 @@ class DefaultJSONProvider(JSONProvider):
treat as a list to serialize.
:param kwargs: Treat as a dict to serialize.
"""
- pass
\ No newline at end of file
+ if args and kwargs:
+ raise TypeError("Cannot pass both args and kwargs.")
+
+ indent = None
+ separators = (",", ":")
+
+ if self.compact is None:
+ compact = not self._app.debug
+ else:
+ compact = self.compact
+
+ if not compact:
+ indent = 2
+ separators = (", ", ": ")
+
+ if args:
+ if len(args) == 1:
+ obj = args[0]
+ else:
+ obj = list(args)
+ elif kwargs:
+ obj = kwargs
+ else:
+ obj = None
+
+ dump_args = {"indent": indent, "separators": separators}
+ from ..wrappers import Response
+ return Response(
+ self.dumps(obj, **dump_args),
+ mimetype=self.mimetype
+ )
\ No newline at end of file
diff --git a/src/flask/json/utils.py b/src/flask/json/utils.py
new file mode 100644
index 00000000..b6399c6d
--- /dev/null
+++ b/src/flask/json/utils.py
@@ -0,0 +1,19 @@
+from __future__ import annotations
+import dataclasses
+import decimal
+import typing as t
+import uuid
+from datetime import date
+from werkzeug.http import http_date
+
+def _default(o: t.Any) -> t.Any:
+ """Default JSON serializer for types that aren't supported by default."""
+ if isinstance(o, date):
+ return http_date(o)
+ if isinstance(o, (decimal.Decimal, uuid.UUID)):
+ return str(o)
+ if dataclasses.is_dataclass(o):
+ return dataclasses.asdict(o)
+ if hasattr(o, "__html__"):
+ return str(o.__html__())
+ raise TypeError(f"Object of type {type(o).__name__} is not JSON serializable")
\ No newline at end of file