Пример #1
0
        def wrapper(request, *args, **kwargs):
            error_message = None
            try:
                if hasattr(settings, 'PROXY_API_KEYS'):
                    if request.META.get(proxy_server.HTTP_API_KEY) in settings.PROXY_API_KEYS:
                        if hasattr(settings, 'PROXY_TOKEN_VALIDATION_SERVICE'):
                            if public is True and request.META.get(proxy_server.HTTP_USER_TOKEN) is not None:
                                error_message = 'A public service cannot receive a user token'
                                raise Exception

                            elif public is False and request.META.get(proxy_server.HTTP_USER_TOKEN):
                                try:
                                    dot = settings.PROXY_TOKEN_VALIDATION_SERVICE.rindex('.')
                                except ValueError:
                                    error_message ='Token validation service not properly configured'
                                    raise Exception

                                val_module = import_module(settings.PROXY_TOKEN_VALIDATION_SERVICE[:dot])
                                val_func = getattr(val_module, settings.PROXY_TOKEN_VALIDATION_SERVICE[dot + 1:])

                                try:
                                    response = val_func(request)
                                except Exception as e:
                                    error_message = 'Could not invoke token validation service'
                                    raise Exception

                                request.META[proxy_server.HTTP_USER_TOKEN] = response[proxy_server.USER_TOKEN]
                                return api_view(methods)(view_func)(request, *args, **kwargs)

                            elif public is True and request.META.get(proxy_server.HTTP_USER_TOKEN) is None:
                                return api_view(methods)(view_func)(request, *args, **kwargs)

                        else:
                            return api_view(methods)(view_func)(request, *args, **kwargs)

                    else:
                        error_message = 'Received API KEY not found in server API KEYS set'
                        raise Exception

                else:
                    error_message = 'API KEYS not properly configured'
                    raise Exception

            except Exception as e:
                if error_message is None:
                    if e.message is not None:
                        error_message = e.message

                    else:
                        error_message = 'Server encountered an error and cannot proceed with service call'

                error = {
                    'error': {
                        'code': 500,
                        'type': 'ProxyServerError',
                        'message': error_message
                    }
                }

                return HttpResponseServerError(json.dumps(error), content_type='application/json')
Пример #2
0
 def as_view(cls, *args, **kwargs):
     view = super(DRFAuthenticatedGraphQLView, cls).as_view(*args, **kwargs)
     view = permission_classes((IsAuthenticated, ))(view)
     view = authentication_classes(
         api_settings.DEFAULT_AUTHENTICATION_CLASSES)(view)
     view = api_view(['GET', 'POST'])(view)
     return view
Пример #3
0
def add_motionActivityPerDay(request):
    payload = json.loads(request.body)
    user = request.user
    dog = Dog.objects.get(id=payload["dog"])
    activity = Activity.objects.get(activity_id=payload["activity"])
    ConvertedDate = datetime.strptime(payload['date'], "%Y-%m-%d").date()
    week = ConvertedDate.isocalendar()[1]
    month = ConvertedDate.month
    year = ConvertedDate.year
    try:
        motion = MotionActivityPerDay.objects.create(
            user=user,
            dog=dog,
            date=payload["date"],
            activity=payload["activity"],
            timePeriod=payload["timePeriod"],
            week=week,
            month=month,
            year=year)
        serializer = MotionActivityPerDaySerializer(motion)
        return JsonResponse({'motions': serializer.data},
                            safe=False,
                            status=status.HTTP_201_CREATED)
    except ObjectDoesNotExist as e:
        return JsonResponse({'error': str(e)},
                            safe=False,
                            status=status.HTTP_404_NOT_FOUND)
    except Exception:
        return JsonResponse(
            {Exception},
            safe=False,
            status=status.HTTP_500_INTERNAL_SERVER_ERROR) @ api_view(["POST"])
Пример #4
0
def tx_swap(request):
    address = request.GET['address']
    amount_beam = request.GET['amount_beam']
    amount_btc = request.GET['amount_btc']

    _redis.set('receiver', address)

    for proc in psutil.process_iter():
        if "wallet-api".lower() in proc.name().lower():
            pinfo = proc.as_dict(attrs=['pid', 'name', 'create_time'])

    os.kill(int(pinfo['pid']), signal.SIGTERM)  # or signal.SIGKILL
    process = subprocess.Popen(
        "beam-wallet --wallet_path=\"wallet.db\" "
        "-n eu-node01.masternet.beam.mw:8100 swap_coins "
        "--amount " + amount_beam + " --fee 100 -r " + address +
        " --pass=123 --swap_amount " + amount_btc +
        " --swap_beam_side --btc_node_addr 127.0.0.1:13300 "
        "--btc_pass 123 --btc_user Alice",
        shell=True,
        stdin=None,
        stdout=None,
        stderr=None,
        close_fds=True)

    _redis.set("process_id", str(process.pid))
    return Response('Completed successfully', status=HTTP_200_OK) @ api_view(
        ['GET'])
Пример #5
0
 def as_view(cls, *args, **kwargs):
     """ Set DRF attributes in the view """
     view = super(DRFAuthenticatedGraphQLView, cls).as_view(*args, **kwargs)
     view = permission_classes((AllowAny,))(view)
     view = authentication_classes(api_settings.DEFAULT_AUTHENTICATION_CLASSES)(view)
     view = api_view(["GET", "POST"])(view)
     return view
Пример #6
0
 def as_view(cls, *args, **kwargs):
     """Add the relevant DRF-view logic to the view."""
     view = super(AuthenticatedGraphQLView, cls).as_view(*args, **kwargs)
     view = permission_classes((IsUserAllowed, ))(view)
     view = authentication_classes(
         (CsrfExemptSessionAuthentication, ))(view)
     view = api_view(["GET", "POST"])(view)
     return view
Пример #7
0
 def as_view(cls, *args, **kwargs):
     backend = DepthAnalysisBackend()
     view = super(GraphQLView, cls).as_view(backend=backend,
                                            *args,
                                            **kwargs)
     view = permission_classes((permissions.AllowAny, ))(view)
     view = api_view(['GET', 'POST'])(view)
     return view
Пример #8
0
 def view(self):
     view_func = self._view_function()
     if self.permission_classes:
         view_func.permission_classes = self.permission_classes
     view = api_view([self.REQUEST_METHOD])(view_func)
     view = add_permission_classes(self.permission_classes)(view)
     view.authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES
     return view
Пример #9
0
def as_view(task):
    def view(request, *args, **kwargs):
        task_id = task_id_from_request(request)
        register_task(task_id, task, *args, **kwargs)
        return task_result_response(task_id)

    view.__name__ = task.__name__.replace('_asr', '')
    return api_view(['GET'])(view)
Пример #10
0
class ApiViewAuthenticationMixin(object):
    @method_decorator(api_view(['POST']))
    @method_decorator(authentication_classes(TokenAuthentication))
    @method_decorator(permission_classes(IsAuthenticated, ))
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(ApiViewAuthenticationMixin,
                     self).dispatch(*args, **kwargs)
Пример #11
0
 def as_view(cls, *args, **kwargs):
     view = super(PrivateGraphQLView, cls).as_view(*args, **kwargs)
     view = permission_classes((
         TokenHasReadWriteScope,
         FireBaseAuth,
     ))(view)
     view = authentication_classes((OAuth2Authentication, ))(view)
     view = api_view(['POST', 'GET'])(view)
     return view
Пример #12
0
 def as_view(cls, *args, **kwargs):
     view = super(DOTAuthenticatedGraphQLView, cls).as_view(*args, **kwargs)
     view = permission_classes((
         IsAuthenticated,
         TokenHasReadWriteScope,
     ))(view)  # add permissions to the view
     view = authentication_classes((OAuth2Authentication, ))(view)
     view = api_view(['POST'])(view)
     return view
Пример #13
0
 def as_view(cls, *args, **kwargs):
     view = super().as_view(*args, **kwargs)
     view = permission_classes((IsAuthenticated,))(view)
     view = authentication_classes(api_settings.DEFAULT_AUTHENTICATION_CLASSES)(view)
     view = parser_classes([JSONParser])(view)
     view = throttle_classes(api_settings.DEFAULT_THROTTLE_CLASSES)(view)
     view = api_view(["GET", "POST"])(view)
     view = csrf_exempt(view)
     return view
Пример #14
0
    def as_view(cls: "DRFGraphQL", schema: Schema) -> "DRFGraphQL":
        """Wraps the graphql view in the authentication_classes, permission_classes
        and api_view functions available from DRF.
        """

        view = super().as_view(graphiql=True, schema=schema)
        view = authentication_classes(api_settings.DEFAULT_AUTHENTICATION_CLASSES)(view)
        view = permission_classes(api_settings.DEFAULT_PERMISSION_CLASSES)(view)
        return api_view(http_method_names=("GET", "POST"))(view)
Пример #15
0
 def as_view(cls, *args, **kwargs):
     view = super(DRFAuthenticatedGraphQLView, cls).as_view(*args, **kwargs)
     view = permission_classes((IsAuthenticated, ))(view)
     view = authentication_classes((
         JSONWebTokenAuthentication,
         TokenAuthentication,
     ))(view)
     #view = authentication_classes((TokenAuthentication,))(view)
     view = api_view(['POST'])(view)
     return view
Пример #16
0
    def decorator(api_func):

        wrapped_func = check_authentication(func=api_func)
        if need_token:
            wrapped_func = check_token(func=wrapped_func)
        wrapped_func = pack_response(func=wrapped_func)
        wrapped_func = prepare_request_data(func=wrapped_func)
        wrapped_func = api_view(http_method_names=REQUEST_METHOD_LIST)(func=wrapped_func)
        wrapped_func = require_http_methods(request_method_list=REQUEST_METHOD_LIST)(func=wrapped_func)

        return wrapped_func
Пример #17
0
def contract_summary_data(request):
    sql = """select json_agg(row_to_json(qq)) from (select month_contract, (sum(s))::int total_price , count(*) contract_count from (SELECT 
       (to_char(start_of_contract,'YYYY-MM-01'))::date as month_contract , price_contract s
  FROM public.contracts_contract where status = 'actual' ) q group by month_contract order by month_contract)qq;"""

    with connection.cursor() as cursor:
        cursor.execute(sql)
        row = cursor.fetchone()
        return Response(row[0]) \
 \
 \
@api_view(['GET'])
Пример #18
0
    def _list_view(self):
        """
        Make and return list view function for retrieving/filtering lists of
        model instances. The view itself accepts a url parameter - `query=...`
        containing a JSON serialized query. If provided, this is handled by the
        `interface.Query` class.

        """
        def list_view(request: Request):
            query_json = request.query_params.get('query')
            fields_json = request.query_params.get('fields')
            page_num = request.query_params.get('page')
            page_size = request.query_params.get('pagesize', 25)
            queryset = self.queryset()

            # If no query is provided, all objects will be returned.
            if query_json:
                # Todo: find root cause of this.
                query_json = query_json.replace(u'\ufeff', '')
                query_data = json.loads(query_json)
                query = Query(**query_data)
                queryset = query.apply_to_queryset(queryset=queryset)

            # If fields are provided, subset the serializer fields accordingly.

            if page_num:
                paginator = Paginator(queryset, page_size)
                num_results = paginator.count
                num_pages = paginator.num_pages
                queryset = paginator.get_page(number=page_num)

            if fields_json:
                fields = json.loads(fields_json)
                serializer_cls = subset_serializer(
                    select_fields=fields, serializer_cls=self.serializer_cls)
                serializer = serializer_cls(queryset, many=True)
            else:
                serializer = self._get_serializer(queryset, many=True)

            if page_num:
                return Response({
                    'num_results': num_results,
                    'num_pages': num_pages,
                    'data': serializer.data
                })

            return Response(serializer.data, status=status.HTTP_200_OK)

        # 'Get' permissions are treated as equivalent to 'list' permissions.
        if self.get_permissions:
            list_view.permission_classes = self.get_permissions

        return api_view(['GET'])(list_view)
Пример #19
0
    def as_view(cls, *args, **kwargs):
        view = super().as_view(*args, **kwargs)
        # if settings.DEBUG is False:
        #     view = permission_classes((IsAuthenticated,))(view)
        # else:
        #     view = permission_classes((AllowAny,))(view)

        view = permission_classes((IsAuthenticated, ))(view)
        view = authentication_classes(
            api_settings.DEFAULT_AUTHENTICATION_CLASSES)(view)
        view = api_view(["GET", "POST"])(view)

        return view
Пример #20
0
def update_action_value_car(data):
    try:
        dens = float(data.GET.get("density"))
        dist = float(data.GET.get("distance"))
        time = data.GET.get("time")
        tid = int(data.GET.get("tripID"))
        isended = data.GET.get("isended")

        print(type(dist))
        return JsonResponse(dist, safe=False)
    except ValueError as e:
        return Response(e.args[0], status.HTTP_400_BAD_REQUEST) @ api_view(
            ["GET"])
Пример #21
0
    def _get_view(self):
        """
        Make and return view function for retrieving data.

        """
        def get_view(request, pk):
            instance = self.model_cls.objects.get(pk=pk)
            serializer = self._get_serializer(instance)
            return Response(serializer.data)

        if self.get_permissions:
            get_view.permission_classes = self.get_permissions

        return api_view(['GET'])(get_view)
Пример #22
0
    def _delete_view(self):
        """
        Make and return the delete view function.

        """
        def delete_view(request, pk):
            instance = self.model_cls.objects.get(pk=pk)
            instance.delete()
            return Response({}, status=status.HTTP_200_OK)

        if self.delete_permissions:
            delete_view.permission_classes = self.delete_permissions

        return api_view(['DELETE'])(delete_view)
Пример #23
0
    def as_view(cls: "RestGraphQL", schema: graphene.Schema) -> "RestGraphQL":
        """Instantiate the RestGraphQL instance and wrap the view with the DRF
        authentication_classes, permission_classes and api_view decorators.

        Args:
            cls (RestGraphQL): The RestGraphQL class object
            schema (Schema): A graphene Schema object
        
        Returns:
            A django view
        """
        view = super().as_view(graphiql=True, schema=schema)
        view = authentication_classes(api_settings.DEFAULT_AUTHENTICATION_CLASSES)(view)
        view = permission_classes(api_settings.DEFAULT_PERMISSION_CLASSES)(view)
        return api_view(http_method_names=("GET", "POST"))(view)
Пример #24
0
    def decorator(view):
        def add_cors(handler):
            @functools.wraps(handler)
            def view_with_cors(request, *args, **kw):
                request.CORS = methods
                if headers:
                    request.CORS_HEADERS = headers
                return handler(request, *args, **kw)

            return view_with_cors

        # The request.CORS attributes need to be added to the view before
        # the DRF @api_view handler executes.

        return add_cors(api_view(methods)(view))
Пример #25
0
    def _create_view(self):
        """
        Make and return view function for creating object of this Type.

        """
        def create_view(request):
            serializer = self._get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)

        if self.create_permissions:
            create_view.permission_classes = self.create_permissions

        return api_view(['POST'])(create_view)
Пример #26
0
def add_Position(request):
    payload = json.loads(request.body)
    try:
        position = Position.objects.create(
            name=payload["name"],
            position_id=payload["position_id"],

        )
        serializer = PositionSerializer(position)
        return JsonResponse({'position': serializer.data}, safe=False, status=status.HTTP_201_CREATED)
    except ObjectDoesNotExist as e:
        return JsonResponse({'error': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND)
    except Exception:
        return JsonResponse({'error': 'Something terrible went wrong'}, safe=False,
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR) @ api_view(["POST"])
Пример #27
0
    def decorator(view):

        def add_cors(handler):
            @functools.wraps(handler)
            def view_with_cors(request, *args, **kw):
                request.CORS = methods
                if headers:
                    request.CORS_HEADERS = headers
                return handler(request, *args, **kw)
            return view_with_cors

        # The request.CORS attributes need to be added to the view before
        # the DRF @api_view handler executes.

        return add_cors(api_view(methods)(view))
Пример #28
0
 def test_ok(self):
     method = 'POST'
     input_view = (api_view([method]))(self._dummy_view)
     output_view = self.decorator(input_view)
     self.assertIsInstance(output_view, Callable)
     wrapper_cls = output_view.cls
     self.assertEqual(wrapper_cls.get_serializer_class(), ExampleSerializer)
     self.assertEqual(type(wrapper_cls.get_serializer()), ExampleSerializer)
     schema = wrapper_cls().schema
     # Ensure that get_link works properly.
     self.assertIsNotNone(uritemplate)
     link = schema.get_link('/api/dummy-view/', method, None)
     self.assertEqual(len(link.fields), 1)
     self.assertEqual(link.fields[0].name, 'test_field')
     self.assertTrue(link.fields[0].required)
Пример #29
0
def reviews_list(request):
    if request.method == 'GET':
        reviews = Review.objects.all()
        serializer = ReviewSerializer2(reviews, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = ReviewSerializer2(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(
            {'error': serializer.errors},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR) @ api_view(
                ['GET', 'POST'])
Пример #30
0
    def _update_view(self):
        """
        Make and return view function for updating object of this Type.

        """
        def update_view(request, pk):
            instance = self.model_cls.objects.get(pk=pk)
            serializer = self._get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            serializer.update(instance=instance, validated_data=request.data)
            return Response(serializer.data, status=status.HTTP_200_OK)

        if self.update_permissions:
            update_view.permission_classes = self.update_permissions

        return api_view(['POST'])(update_view)
Пример #31
0
    def decorator(func):
        @wraps(func)
        def inner_func(request, *args, **kwargs):
            result = func(request, *args, **kwargs)
            if isinstance(result, Response):
                return result
            if not serializer:
                return Response(result)
            many = isinstance(result, (list, QuerySet))
            return Response(serializer(result, many=many, context=dict(request=request)).data)

        view = api_view(http_method_names)(inner_func)
        if input_serializer:
            view_class = view.view_class
            view_class.serializer_class = input_serializer
            # Reprise des méthodes d'accès au serializer pour les métadonnées de l'APIView
            from rest_framework.generics import GenericAPIView
            view_class.get_serializer = GenericAPIView.get_serializer
            view_class.get_serializer_context = GenericAPIView.get_serializer_context
            view_class.get_serializer_class = GenericAPIView.get_serializer_class

            if validation:
                # POST
                post_handler = getattr(view_class, 'post', None)
                if post_handler:
                    def handler(self, request, *args, **kwargs):
                        serializer_instance = input_serializer(data=request.data)
                        serializer_instance.is_valid(raise_exception=True)
                        request.validated_data = serializer_instance.validated_data
                        return post_handler(self, request, *args, **kwargs)
                    view_class.post = handler
                # PUT
                put_handler = getattr(view_class, 'put', None)
                if put_handler:
                    def handler(self, request, *args, **kwargs):
                        partial = kwargs.pop('partial', False)
                        instance = self.get_object()
                        serializer_instance = input_serializer(instance, data=request.data, partial=partial)
                        serializer_instance.is_valid(raise_exception=True)
                        request.validated_data = serializer_instance.validated_data
                        return post_handler(self, request, *args, **kwargs)
                    view_class.put = handler
        return view
Пример #32
0
    def test_browsable_renderer_put_render(self):
        """
        Test, that PUT method works with BrowsableAPIRenderer
        This was not working in the past, because of `_get_serializer`
        didn't allow `instance parameter.
        """
        data = {'blah': 'blah'}
        method = 'PUT'
        request = rest_request.Request(APIRequestFactory().get('blah'))
        input_view = (api_view([method]))(self._dummy_view)
        output_view = self.decorator(input_view)
        wrapper_cls = output_view.cls
        test_view_instance = wrapper_cls()

        renderer = renderers.BrowsableAPIRenderer()
        renderer.accepted_media_type = None
        renderer.renderer_context = {}
        response = renderer.get_raw_data_form(
            data, test_view_instance, method, request,
        )
        self.assertEqual(response.data, {})
Пример #33
0
    url(r'^(?P<project_id>\d+)/neurons/$', neuron.list_neurons),
    url(r'^(?P<project_id>\d+)/neurons/from-models$', neuron.get_neuron_ids_from_models),
]

# Node access
urlpatterns += [
    url(r'^(?P<project_id>\d+)/node/(?P<node_id>\d+)/reviewed$', record_view("nodes.add_or_update_review")(node.update_location_reviewer)),
    url(r'^(?P<project_id>\d+)/nodes/most-recent$', node.most_recent_treenode),
    url(r'^(?P<project_id>\d+)/nodes/location$', node.get_locations),
    url(r'^(?P<project_id>\d+)/node/nearest$', node.node_nearest),
    url(r'^(?P<project_id>\d+)/node/update$', record_view("nodes.update_location")(node.node_update)),
    url(r'^(?P<project_id>\d+)/node/list$', node.node_list_tuples),
    url(r'^(?P<project_id>\d+)/node/get_location$', node.get_location),
    url(r'^(?P<project_id>\d+)/node/user-info$', node.user_info),
    url(r'^(?P<project_id>\d+)/nodes/find-labels$', node.find_labels),
    url(r'^(?P<project_id>\d+)/nodes/$', api_view(['POST'])(node.node_list_tuples)),
]

# Treenode access
urlpatterns += [
    url(r'^(?P<project_id>\d+)/treenode/create$', record_view("treenodes.create")(treenode.create_treenode)),
    url(r'^(?P<project_id>\d+)/treenode/insert$', record_view("treenodes.insert")(treenode.insert_treenode)),
    url(r'^(?P<project_id>\d+)/treenode/delete$', record_view("treenodes.remove")(treenode.delete_treenode)),
    url(r'^(?P<project_id>\d+)/treenodes/compact-detail$', treenode.compact_detail_list),
    url(r'^(?P<project_id>\d+)/treenodes/(?P<treenode_id>\d+)/info$', treenode.treenode_info),
    url(r'^(?P<project_id>\d+)/treenodes/(?P<treenode_id>\d+)/compact-detail$', treenode.compact_detail),
    url(r'^(?P<project_id>\d+)/treenodes/(?P<treenode_id>\d+)/children$', treenode.find_children),
    url(r'^(?P<project_id>\d+)/treenodes/(?P<treenode_id>\d+)/confidence$', record_view("treenodes.update_confidence")(treenode.update_confidence)),
    url(r'^(?P<project_id>\d+)/treenodes/(?P<treenode_id>\d+)/parent$', record_view("treenodes.update_parent")(treenode.update_parent)),
    url(r'^(?P<project_id>\d+)/treenode/(?P<treenode_id>\d+)/radius$', record_view("treenodes.update_radius")(treenode.update_radius)),
    url(r'^(?P<project_id>\d+)/treenodes/radius$', record_view("treenodes.update_radius")(treenode.update_radii)),
Пример #34
0
def superuser_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME,
                       login_url=None):
    """
    Decorator for views that checks that the user is logged in and is super user,
    redirecting to the log-in page if necessary.
    """
    actual_decorator = user_passes_test(
        lambda u: u.is_authenticated() and u.is_superuser,
        login_url=login_url,
        redirect_field_name=redirect_field_name
    )
    if function:
        return actual_decorator(function)
    return actual_decorator

require_GET = api_view(["GET"])
require_POST = api_view(["POST"])
require_DELETE = api_view(["DELETE"])
require_PUT = api_view(["PUT"])


def api_enabled(enabled):

    def decorator(func):

        @wraps(func)
        def wrapped_view(*args, **kwargs):

            if enabled:
                return func(*args, **kwargs)
            else:
Пример #35
0
def api_get_view(func):
    return api_view()(func)
Пример #36
0
def api_post_view(func):
    return api_view(['POST'])(func)
Пример #37
0
@api_view(['GET'])
def image_square_name(request, width, name):
    """ Get Image by Name as Square """
    return create_Repsonse(square_image(width,Image.open(get_Photo(name))))

@api_view(['GET'])
def image_rectangle(request, width, height):
    """ Get Random Image as Rectangle """
    return create_Repsonse(rectancle_image(width,height,Image.open(random_Photo())))

@api_view(['GET'])
def image_rectangle_name(request, width, height, name):
    """ Get Image by name as Rectangle """
    return create_Repsonse(rectancle_image(width,height,Image.open(get_Photo(name))))

api_view(['GET'])
def get_random_image_category(request,category):
    """ Get Random Image from Category """
    if not (category in dict(Photo.CATEGORY)):
        raise Http404
    return create_Repsonse(Image.open(random_Photo_category(category)))

api_view(['GET'])
def get_random_image_category_square(request,category,width):
    """ Get random Square Image from Category """
    if not (category in dict(Photo.CATEGORY)):
        raise Http404
    return create_Repsonse(square_image(width,Image.open(random_Photo_category(category))))

api_view(['GET'])
def get_random_image_category_size(request,category,width,height):
Пример #38
0
 def as_view(cls, *args, **kwargs):
     view = super(GraphQLView, cls).as_view(*args, **kwargs)
     view = permission_classes((IsAuthenticated,))(view)
     view = authentication_classes(api_settings.DEFAULT_AUTHENTICATION_CLASSES)(view)
     view = api_view(['GET', 'POST'])(view)
     return view
Пример #39
0
    permission_classes = [IsAdminUser, ]


class PermissionViewSet(ModelViewSet):
    """ A permission that can be given to or revoked from a user """
    queryset = Permission.objects.all()
    serializer_class = PermissionSerializer
    permission_classes = [IsAdminUser, ]


class TokenViewSet(ModelViewSet):
    """ A token for logging in to the API """
    queryset = Token.objects.all()
    serializer_class = TokenSerializer
    permission_classes = [IsAdminUser, ]


all_views = {}

for routine_class in Routine.__subclasses__():
    def view_func(request, routine=routine_class()):
        return Response(routine.to_json())
    view_func.__name__ = routine_class.__name__
    view_func.__doc__ = routine_class.__doc__
    # We can't use `api_view` as a decorator because we can't call it until we
    # have set the __name__ and __doc__ of `view_func`. Thus, we explicitly
    # call `api_view` afterwards
    view_fun = permission_classes((IsAdminUser, ))(view_func)
    view_func = api_view()(view_func)
    all_views[slugify(routine_class.title.lower())] = view_func