from flask import Flask
from flask.json import JSONEncoder
class CustomJSONEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(obj, date):
return obj.strftime('%Y-%m-%d')
else:
return JSONEncoder.default(self, obj)
app = Flask(__name__)
app.json_encoder = MyJSONEncoder
报错:ImportError: cannot import name 'JSONEncoder' from 'flask.json'
原因:'JSONEncoder' is deprecated and will be removed in Flask 2.3. Use 'Flask.json' to provide an alternate JSON implementation instead.
Flask 2.3.版本以上版本,JSONEncoder类被弃用了。这通常意味着在新版本中,原来用于处理JSON编码的类已经不再被推荐使用,并且在未来的版本中可能会被移除。
解决:
from flask import Flask from flask.json.provider import DefaultJSONProviderclass CustomJSONEncoder(DefaultJSONProvider): def default(self, obj): if isinstance(obj, datetime): return obj.strftime('%Y-%m-%d %H:%M:%S') elif isinstance(obj, date): return obj.strftime('%Y-%m-%d') else: return DefaultJSONProvider.default(obj) app = Flask(__name__) app.json = CustomJSONEncoder(app) app.json.ensure_ascii = False