GithubHelp home page GithubHelp logo

adrf's People

Contributors

cfra avatar em1208 avatar johnthagen avatar kartava avatar shepherd1530 avatar spanishpy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

adrf's Issues

About Async Relational Fields

Defining relational fields in a serializer may incur additional database queries, but Django does not natively support asynchronous many-to-one or one-to-one queries. Django will report an error if you try to do many-to-one or one-to-one queries in an async context.

In fact, the best practice is to use select_related or prefetch_related to query all the data that needs to be used at once when defining the queryset, so as to avoid additional database queries in the future.

I want to try to implement a simple asynchronous serializer, but my confusion is that when the user does a many-to-one or one-to-one query and does not use select_related or prefetch_related, should Django report an error or take some way to achieve async many-to-one or one-to-one queries?

I would like to ask what is your take on this matter? Thank you.

ViewSet incorrectly checks if ordinary properties and members on a class are async

I configured a viewset to include a content_negotiation_class, as follows:

from adrf.viewsets import ViewSet as AsyncViewSet

class MyViewSet(AsyncViewSet):
    content_negotiation_class = MyContentNegotiation
    
    ...

And the viewset fails with:

django.core.exceptions.ImproperlyConfigured: MyViewSet action handlers must either be all sync or all async.

I confirmed it's because this check is too coarse and including non-callable members.

if callable(function) and not name.startswith("__")

I quickly attempted to override and perform a more precise check to no avail. I think checking isinstance(function, types.FunctionType) is promising but adding it on it's own was not enough.

My workaround is to override view_is_async in the viewset to return True and just be very careful.

caching issue

the traditional caching feature on django/ drf is not compatible with adrf

Writing tests for async views

Currently, I'm using rest_framework.test.APIClient for tests on my sync viewes. Is there a way I can easily adopt this for the async views I have thanks to this package?

ViewSets

@em1208 thanks for the great effort on this so far.
is there any examples or thoughts on how the ViewSets should be created / updated?
have you had any success with this or are any calls to the database out of the question currently

Require CSRF when api_view(('POST')) on 0.1.5, but not in 0.1.4

https://github.com/Artasov/xlartas
My project work correctly in version 0.1.4. In 0.1.5 csrf is required for any post requests. Why?. What has changed in these versions.
An example of a controller... 1 of... I checked several times, changed the versions, and everything breaks on 0.1.5.
In apps/shop/controllers/software/software_test_activate_current_user.

@api_view(('POST',))
@permission_classes([IsAuthenticated])
async def software_test_activate_current_user(request) -> Response:
     pass

If you are interested in testing, then it is enough to start the project:

python --version
> python 3.11.6
python -m vev venv
venv/Scripts/activate
git clone https://github.com/Artasov/xlartas

rename THE TEMPLATE .env.prod > .env.prod
change
DEBUG=1
DEV=1
HTTPS=0


cd xlartas
cd frontend
npm install
npm run build
cd ..
cd backend
pip install -r requirements.txt
python manage.py migrate
python manage.py runserver

ModelViewSet implementation

Are there any plans, technical designs, or research for add support for ModelViewSets?

I can take a crack at it if not, just wanted to check!

Authentication error with 0.1.3 release

REST API interface GET access as "GET /services/p/p/" got complain :

{
    "detail": "Authentication credentials were not provided."
}

Here is the setup of view and URL conf

from adrf.views import APIView as AsyncAPIView
@authentication_classes([authentication.SessionAuthentication, ExpiringTokenAuthentication])
@permission_classes([permissions.IsAuthenticated])
class DummyView(AsyncAPIView):
    async def get(self, request, category, slug): pass 
path('services/<str:category>/<str:slug>/', DummyView.as_view()

It's fine with 0.1.2, but starts fail with 0.1.3.

Synchronous Exception when using ModelSerializer

I am trying this extension for the first time. I have executed the examples in the ReadMe successfully. Currently I am trying to create a sample async CRUD API but this time instead of Using Serializer I am using ModelSerializer. When I call

serializer.is_valid(raise_exeception=True) inside my API I receive the below exception

django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
Here is my API code

class OyCreateRubricAPIView(APIView):
    async def post(self, request):
        data = request.data
        print(data)
        serializer = CreateSerializer(data=data)
        serializer.is_valid(raise_exception=True)
        await serializer.asave()
        return Response({"message": "Success"})

Handle review comments from DRF

There's a few review comments on the DRF PR that never got marked as completed. For example, support for async fields on serializers.

Mark them as completed over there if needed, or create issues on this repo to handle those tasks.

Error with decorators in method

I am using this ViewSet:

from adrf.viewsets import ViewSet
from drf_yasg.utils import swagger_auto_schema
from rest_framework.response import Response

def user_permission(permission: str, status: int = 403):
    def int_permission(func):
        def function(self, request, **kwargs):
            if permission == "superuser" and not request.user.is_superuser:
                return Response([_("You don't have access to the resource")], status=status)
            if not request.user.has_perm(permission):
                return Response([_("You don't have access to the resource")], status=status)
            return func(self, request, **kwargs)

        return function

    return int_permission

class Testing(ViewSet):
    @swagger_auto_schema(request_body=AcceptRequestDTO, responses={"200": ResponseShortDTO()})
    @user_permission("orders.change_requests")
    async def accept(self, request):
        return Response({"complete": , "message": "", "data": ""}, status=200)

And the error is:

assert isinstance(response, HttpResponseBase), (
AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'coroutine'>`

Does `adrf` support `django`(version 4.2)?

According to README.md, the Requirements are Python 3.8+ and Django 4.1.

However, the Async Views section says:

When using Django 4.1 and above, this package allows you to work with async class and function based views.

So, I have a question about:

Does adrf support django(version 4.2)?

Add license file

Currently, no license is attached to this repo.

If this repo ever gets merged back into DRF, having no license would make this fairly hard.

Best practices for partial async implementation in DRF

I have currently a Django API project built with DRF.
I would like to use async for some endpoints to optimize long API calls.
What are the best practices in terms of performance ?
I suppose that I have to change my server for Uvicorn ?
Will the normal sync views still work correctly ?
Thanks.

ModelSerializer with SerializerMethodField and overriding to_representation

I have a ModelSerializer that contains some SerializerMethodFields and I need to override the to_representation method as well.
for instance:

from adrf.serializers import ModelSerializer as AsyncModelSerializer

class SampleSerializer(AsyncModelSerializer):
    remaining = serializers.SerializerMethodField(read_only=True)
    class Meta:
        model = MyModel
        fields = "__all__"
    def to_representation(self, instance):
        representation = super().to_representation(instance)
        # do some stuff here
        return representation

this is the APIView I have:

from adrf.views import APIView as AsyncAPIView

class SampleView(AsyncAPIView):
    permission_classes = [IsAuthenticated]
    user = request.user
        myObj = MyModel.objects.filter(
            userpackage_package__user=user,
            purchase_start_time__lte=timezone.localtime(),
            end_date__gte=timezone.localdate(),
        )
        serializer = SampleSerializer(
            myObj, many=True, context={"user": user}
        )
        return Response({"data": await serializer.adata}, status=status.HTTP_200_OK)

but I get this error: 'SerializerMethodField' object has no attribute 'ato_representation'

Generics support

Is there any support for Generics View like ListCreateAPIView/UpdateAPIView etc ?
Is support, how can i use that? i cannot see any example to use on online.

how can i write async serializers to go with my async ViewSet?

this framework looks very interesting in the sense of turning my DRF application to async. the snag i am running into right now is how to serialize the data.

the example on the README use direct fields from the models. is there a way to make a serializer in, that would not through an error about not being sync or corotines not being serializable, or is it necessary to manually serialize every model?

something along:

class AsyncViewSet(ViewSet):

    async def list(self, request):
        users_list = []
        async for user in User.objects.all():
            s = await UserSerializer(user, many=False)
            users_list.append(s.data)
        return Response(user_list)

    async def retrieve(self, request, pk):
        user = await User.objects.filter(pk=pk).afirst()
        s = await UserSerializer(user, many=False)
        return Response(user)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.