Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling own API endpoints in django command

I'd like to call the endpoint of my own app in a django.core.management.base.BaseCommand pretty much like this with rest_framework.test.APIClient:

client = APIClient()
client.credentials(HTTP_AUTHORIZATION='Token ' + auth_token.key)

url = reverse('myurl-viewset')
res = client.post(url, data=payload, format='json')

The problem I have with APIClient is that it seems to be using its own testing database and so everything I do within my views to modify the db actually doesn't get inserted into the real database. I need to find a way to call my views/endpoints from a django.core.management.base.BaseCommand class handle function.

Using requests with:

url = reverse('myurl-viewset')
res = requests.post(url, data=payload, headers={'Authorization': 'Token ' + auth_token.key})

I get:

requests.exceptions.MissingSchema: Invalid URL '/api/myurl/viewset/': No schema supplied. Perhaps you meant http:///api/myurl/viewset/?

In theory, I shouldn't be able to call endpoints this way anyways since my django server isn't started from running a django.core.management.base.BaseCommand. Now the question is: How can I call my endpoints directly from my views, from the command? Thanks.

like image 442
E-Kami Avatar asked Oct 27 '25 11:10

E-Kami


1 Answers

I found a way to solve my problem by using:

from django.test.client import RequestFactory
from rest_framework.test import force_authenticate

view = MyViewSet.as_view({'post': 'myurl'})

request = factory.post(url, data=payload, content_type='application/json')
force_authenticate(request, user=user)
response = view(request)

With that, the main database is used.

like image 50
E-Kami Avatar answered Oct 29 '25 06:10

E-Kami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!