em1208 / adrf Goto Github PK
View Code? Open in Web Editor NEWAsync support for Django REST framework
License: Other
Async support for Django REST framework
License: Other
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.
Both GenericViewSet and ModelViewSet are very useful, it would be nice to have an implementation of it.
I'm trying to build a quick POC but it currently fails because I'm inheriting the views methods from a Mixin. The fix would be something like #36, but it is still failing after teaching View.view_is_async (that comes from django) about viewsets methods. Any hint?
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)
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)?
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'>`
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.
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?
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"})
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.
the traditional caching feature on django/ drf is not compatible with adrf
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.
@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
Any plans to implement custom authentication_classes methods?
Something like this project did https://github.com/hisdream86/drf-async-view
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.
Line 147 in 153b89c
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.
I have a ModelSerializer that contains some SerializerMethodField
s 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'
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.
I'd like to know if already exists a way to implement pagination in an async way
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.
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!
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
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.