Исправление мелких ошибок, добавление http error code к ответу (400 если проблема с параметрами)
This commit is contained in:
@@ -1,4 +1,6 @@
|
||||
from django.http import HttpResponse
|
||||
import json
|
||||
|
||||
from django.http import *
|
||||
from .api_params import *
|
||||
|
||||
|
||||
@@ -24,6 +26,13 @@ def api_make_response(response):
|
||||
# )
|
||||
|
||||
|
||||
def default_serializer(obj):
|
||||
try:
|
||||
return obj.to_json()
|
||||
except Exception:
|
||||
return str(obj)
|
||||
|
||||
|
||||
def api_method(func_name, doc="", params: list or None = None, returns=""):
|
||||
"""
|
||||
Декоратор для методов API, автоматически валидирует и передает параметры методам
|
||||
@@ -56,9 +65,12 @@ def api_method(func_name, doc="", params: list or None = None, returns=""):
|
||||
# print(f"errors: {errors}, args: {func_args}")
|
||||
if len(errors) > 0:
|
||||
if len(errors) == 1:
|
||||
return make_error_object(errors[0])
|
||||
obj = make_error_object(errors[0])
|
||||
else:
|
||||
return make_error_object(errors)
|
||||
obj = make_error_object(errors)
|
||||
response = HttpResponseBadRequest(json.dumps(obj, default=default_serializer, ensure_ascii=False, indent=4))
|
||||
response.headers["Content-type"] = "application/json; charset=utf-8"
|
||||
return response
|
||||
else:
|
||||
try:
|
||||
if asyncio.iscoroutinefunction(func):
|
||||
@@ -69,10 +81,16 @@ def api_method(func_name, doc="", params: list or None = None, returns=""):
|
||||
return make_error_object(ex)
|
||||
|
||||
if out is None:
|
||||
return make_error_object(Exception(API_ERROR_INTERNAL_ERROR, "method returned null object"))
|
||||
obj = make_error_object(Exception(API_ERROR_INTERNAL_ERROR, "method returned null object"))
|
||||
response = HttpResponseServerError(json.dumps(obj, default=default_serializer, ensure_ascii=False, indent=4))
|
||||
response.headers["Content-type"] = "application/json; charset=utf-8"
|
||||
return response
|
||||
|
||||
if not isinstance(out, dict) and not isinstance(out, HttpResponse):
|
||||
return make_error_object(Exception(API_ERROR_INTERNAL_ERROR, "method returned invalid object type"))
|
||||
obj = make_error_object(Exception(API_ERROR_INTERNAL_ERROR, "method returned invalid object type"))
|
||||
response = HttpResponseServerError(json.dumps(obj, default=default_serializer, ensure_ascii=False, indent=4))
|
||||
response.headers["Content-type"] = "application/json; charset=utf-8"
|
||||
return response
|
||||
|
||||
return out
|
||||
|
||||
|
||||
Reference in New Issue
Block a user