how get the content of BrowsableAPIView in django channels (or ajax) - django

I use Django Channels to retrieve the data from Django Restful (DRF) serializer (I use channels because database is large and if I call for the data directly it results in a server timeout).
What I struggle with (perhaps I don't understand something about how DRF works), is how to get the html representation of Browsable API. So basically what I need to do is to send back as html a response based on BrowsableAPIRenderer when a person connects via WebSocket:
def connect(self, message, **kwargs):
myobj = MyObj.objects.filter(code=self.obj_code)
serializer = MyObjSerializer(myobj, many=True)
self.send(Response(serializer.data))
But that results in an error Response is not JSON serializable.

Related

Django Rest Framework: Without Model

I'm working on creating a RESTAPI using DRF(Django Rest Framework). API just receives the users twitter handle and returns his twitter data.
Here, I'm not using model here because it's not required.
Should I use a serializer here? If so why? Now I'm able to return the data without using a serializer.
Moreover, My API is not web-browsable. How should I make it web-browsable: which is one of the best features of DRF.
Edit:1
I'm using Functions in Views.
#api_view(['GET'])
#csrf_exempt
def getdetails(request):
call the twitter api
receive the data
return HttpResponse(JsonResponse( {'data': {'twitter_id':id,'tweets':count,'Followers':followers,'following':count_follow}}))
In the browser I'm just seeing JSON data like this.
{"data": {"twitter_id": 352525, "tweets": 121, "Followers": 1008, "following": 281}}
You can use Serializer for the result
class SampleSerializer(serializers.Serializer):
field1 = serializers.CharField()
field2 = serializers.IntegerField()
# ... other fields
Usage
my_data = {
"field1": "my sample",
"field2": 123456
}
my_serializer = SampleSerializer(data=my_data)
my_serializer.is_valid(True)
data = my_serializer.data
You'll get serialized data in data variable (you can use my_serializer.data directly)
Should I use a serializer here?
It's up to you, because if you wish to show the response JSON without any modification from the Twitter API, you can go without DRF serializer. And If you wish to do some formatting on the JSON, my answer will help you
My API is not web-browsable. How should I make it web-browsable?
Maybe you followed wrong procedure. Anyway we can't say more on this thing without seeing your code snippets
Update-1
from rest_framework.response import Response
#api_view(['GET'])
#csrf_exempt
def getdetails(request):
call the twitter api
twitter_api = get_response_from_twitter() # Json response
return Response(data=twitter_api)

django rest framework - You cannot access body

I'm using django 1.8 rest api as below.
#api_view(['GET', 'POST'])
#authentication_classes((TokenAuthentication, SessionAuthentication, BasicAuthentication))
#permission_classes((IsAuthenticated,))
#staff_member_required
def api(request):
print request.data
The problem with this is that it retrieves all parameters as string so I have to convert numbers and boolean manually.
I tried using:
print json.loads(request.body)
but apparently django rest framework reads from the data stream which causes this error:
Error: RawPostDataException: You cannot access body after reading from request's data stream
I also tried
json.loads(request.stream.body)
because the documentation says stream should work.
Is there a way I can retrieve the request post data with the appropriate types?
Note that I'm using ajax to send the data with JSON.stringify.
You want to use serializers in DRF. They will allow you to convert model instances to native Python datatypes which can be translated into JSON and vice versa. You can also deserialize which will convert those JSON strings to complex types.
Read more about serializers here

How to parse request in django

Hi i am making an webserver , In which I have to hit some request from html page and return the response. The URL which is generated using html is
http://192.168.2.253:8080/searchSMS/?KPImsgId=0&circle=&subId=&startDate=DD-MM-YYYY&endDate=DD-MM-YYYY&Username=ashish
but in the server side I am not able to see the request data. I am using
q = QueryDict(request.body) but it is showing <QueryDict: {}>
How to find the all the parameters coming in request.
In your case you send the data in url so access the data through request.GET as follow:
username = request.GET.get('Username')
start_date = request.GET.get('startDate')
# ... the same for all the other parameter after the `?` marque.
In fact there is a difference between request data, request.body, request.GET and request.POST:
If you are sending POST request to django function view or class based view: you access the request data in request.body or request.POST.
If you are sending POST request to Django REST Framework: you access the data in request.data. You may also find in Internet request.DATA that correct but it's deprecated in the newer version of DRF in favor of request.data.
If you send parameter in the url like in you case, you access the data form request.GET as explained above.

Forcing parsing of request with no Content-Type with Rest Framework

I'm writing a Rest Framework view for receiving a JSON POST request. However, the incoming request has no Content-Type header (valid HTTP), and as documented, Rest Framework throws an UnsupportedMediaType and returns a 415 Unsupported Media Type.
I do not control the client. How can I force the request to processed with JSONParser despite no declared content type? (perhaps I can access the underlying request before processing by the parsers?)
Here's is my current (simple) view:
class Callback(APIView):
# this doesn't help
# parser_classes = (JSONParser,)
def post(self, request, format=None):
# ...operate on request.DATA
Take a look at writing a custom content negotiation class.
http://www.django-rest-framework.org/api-guide/content-negotiation#custom-content-negotiation
You'll want to base it on the default implementation, but returning JSONParser if nothing else matches.

Django REST framework request data

Im using DJango REST framework to write my web service layer in which I want to read request payload from the request (POST). I tried the following code but I get empty set
#api_view(['POST'])
def login(request):
print request.POST
Content Type is JSON. I tried to pass data from REST Client Tool. Still am able to read header values but only Payload is not coming out.
You should use request.DATA instead of request.POST to retrieve json data.
request.DATA has been deprecated in favor of request.data since version 3.0, and has been fully removed as of version 3.2.