예제 #1
0
def create_cases(request):
    try:
        body = request.body.decode(request.charset)
    except UnicodeDecodeError:
        return JsonResponse(
            {"error": f"Couldn't decode body as {request.charset}."},
            status=400)

    with io.StringIO(body, newline='') as csvfile:
        reader = csv.DictReader(csvfile)

        ids = []
        for row in reader:
            data = {key: [value] for key, value in row.items()}

            try:
                ids.append(CaseApi.create_case(data))
            except RequestException:
                return JsonResponse(
                    {
                        "error": "Error while using external Zaaksysteem API.",
                        "result": ids
                    },
                    status=500,
                )

    return JsonResponse({"result": ids})
예제 #2
0
파일: handlers.py 프로젝트: tolsac/restae
 def destroy(self, request, key=None):
     """
     :return: :py:class:`restae.response.JsonResponse`
     """
     self.pre_delete(key)
     key.delete()
     return JsonResponse()
예제 #3
0
def path_cat(a, b):
    r = {'a': a}

    if b is not None:
        r['b'] = b

    return JsonResponse(r)
예제 #4
0
 def post(self):
     data_dict = request.get_json()
     report = Report(**data_dict)
     report.position = [float(s) for s in data_dict["position"]]
     report.save()
     url = url_for(".report_detail", id=str(report.id))
     response = {"report": report.as_dict(), "url": url}
     return JsonResponse(response, status=200)
예제 #5
0
파일: handlers.py 프로젝트: tolsac/restae
 def partial_update(self, request, key=None):
     try:
         obj = key.get()
         obj.update(self.get_body())
         obj.put()
         self.post_save(obj, created=False)
         return JsonResponse(data=self.get_serializer()(obj).data)
     except Exception as err:
         raise BadRequest(str(err))
예제 #6
0
파일: handlers.py 프로젝트: tolsac/restae
    def create(self, request):
        """

        :return: :py:class:`restae.response.JsonResponse`
        """
        _model = get_model_class_from_query(self.get_queryset())
        obj = _model(**self.get_serializer()(data=self.get_body()).data)
        obj.put()
        self.post_save(obj, created=True)
        return JsonResponse(data=self.get_serializer()(obj).data)
예제 #7
0
파일: handlers.py 프로젝트: tolsac/restae
    def apply_dispatch(self):
        """
        Does the hole mechanism of dispatch.

        Loops over all middlewares before and after the dispatch method call


        .. code-block:: python

            for middleware in self.middlewares:
                middleware.process_request(self.request)

            self.route_args = self.get_route_args()
            response = self.do_dispatch()

            for middleware in self.middlewares:
                middleware.process_response(self.request, response)

        :return: :py:class:`webob.Response`
        """
        try:
            self.query_params = dict(self.request.GET)
            self.env = self.request.GET.env

            for middleware in self.middlewares:
                if middleware.activate_on_method(self.request.method.upper()):
                    middleware.process_request(self.request)

            self.route_args = self.get_route_args()
            response = self.do_dispatch()

            for middleware in self.middlewares:
                if middleware.activate_on_method(self.request.method.upper()):
                    middleware.process_response(self.request, response)

            return response
        except NotFound as nf:
            return JsonResponse(status=404, data=str(nf) or 'Not found')
        except NotAuthorized as na:
            return JsonResponse(status=403, data=str(na) or 'Not authorized')
        except Forbidden as fo:
            return JsonResponse(status=401, data=str(fo) or 'Forbidden')
        except MissingParameter as mp:
            return JsonResponse(status=400,
                                data=str(mp) or 'Missing parameter')
        except BadRequest as br:
            return JsonResponse(status=400, data=str(br) or 'Bad request')
        except MissingBody as mb:
            return JsonResponse(status=400,
                                data=str(mb) or 'Request is missing a body')
        except ValueError as ve:
            return JsonResponse(status=400, data=str(ve) or 'Value error')
        except DispatchError:
            return Response(status=404)
        except Exception as err:
            logging.error('%s: %s', err.__class__.__name__, str(err))
            logging.error(traceback.format_exc())
            return self.handle_exception(err, self.app.debug)
예제 #8
0
파일: handlers.py 프로젝트: tolsac/restae
    def retrieve(self, request, key=None):
        """

        :return: :py:class:`restae.response.JsonResponse`
        """
        try:
            obj = key.get()
            if obj is None:
                raise NotFound
        except Exception:
            raise NotFound

        return JsonResponse(data=self.get_serializer()(obj).data)
예제 #9
0
파일: handlers.py 프로젝트: tolsac/restae
    def do_dispatch(self):
        """
        Dispatches the request.

        This will first check if there's a handler_method defined in the
        matched route, and if not it'll use the method correspondent to the
        request method (``get()``, ``post()`` etc).
        """

        if self.request.method.upper() == 'OPTIONS':
            return CorsResponse()

        route_args = self.get_route_args()
        route_kwargs = {}
        matched_url = None

        for url in getattr(self, 'urls', []):
            if re.match(url.regex, self.request.path_info):
                matched_url = url
                break

        if matched_url is None:
            raise NotFound('URL not found on this server')

        if matched_url.route.detail is True:
            try:
                route_kwargs['key'] = self.get_object(
                    urlsafe=route_args['urlsafe'])
            except Exception:
                return JsonResponse(status=400,
                                    data='Given urlsafe is invalid')

        if self.request.method.lower() not in matched_url.route.mapping.keys():
            raise DispatchError('Invalid method {}'.format(
                self.request.method))

        self.action = matched_url.route.mapping[self.request.method.lower()]
        method = getattr(self, self.action, None)
        # The handler only receives *args if no named variables are set.
        args, kwargs = route_args, route_kwargs
        if kwargs:
            args = ()

        if self.check_action_permissions() is False:
            raise NotAuthorized()
        return method(self, *args, **kwargs)
예제 #10
0
 def _send_500(connection, message):
     response = JsonResponse()
     response.status = 500
     response.content = {'message': message}
     http_response = response.get_http()
     connection.send(http_response)
예제 #11
0
def qs_cat(querystring):
    return JsonResponse(querystring)
예제 #12
0
def form_cat(form):
    return JsonResponse(form)
예제 #13
0
def json_cat(json):
    return JsonResponse(json)
예제 #14
0
 def get(self, id):
     report = Report.objects.get_or_404(id=id)
     response = {"report": report.as_dict()}
     return JsonResponse(response, status=200)
예제 #15
0
 def get(self):
     fields = "address", "position", "severity", "noise_type"
     reports = Report.objects.only(*fields).all()
     response = {"reports": [r.as_dict() for r in reports]}
     return JsonResponse(response, status=200)
예제 #16
0
 def _send_404(connection):
     response = JsonResponse()
     response.status = 404
     response.content = {'message': '404 Not Found'}
     http_response = response.get_http()
     connection.send(http_response)
예제 #17
0
 def get(self):
     reports = Report.objects.all()
     response = {"reports": [r.as_dict() for r in reports]}
     return JsonResponse(response, status=200)