Serialization is returning each character as object - python

I have a simple view, in which I need to return JSON data but when using django serialize and JsonResponse it returns each character as an object. Here is the snippet:
def query(request):
data = serializers.serialize('json', Post.objects.all())
response = JsonResponse(data, safe=False)
return response
The problem is that if I want to print response.content[0] it returns some random number as it's the first character of the response.
Is there any way I can make the response to be accessed like a simple dictionary (JSON)?

Once you have a JSON, it's basically a string - so you can not access it like a dictionary/list or any Python type.
If you need to access it like a dictionary or a list, you should operate on the non serialized data:
def query(request):
posts = Post.objects.all()
print(posts[0]) # You can now use it as a list of objects
data = serializers.serialize('json', posts)
response = JsonResponse(data, safe=False)
return response

Related

problem with 'QueryDict' object is not callable

class PreUpdateDeleteAPIView(APIView):
serializer_class = PreEditSerializer
queryset = Reserve.objects.all()
def post(self, request):
code = request.data()
"""''.join(code)"""
data = {
reverse('update-delete', args = [code] ,request=request)
}
return Response(data)
hello. i have an problem for converting querydict to string. what should i do now?
i have tried json.dump and several answers in SOF. but i didnt get my answer yet!
request.data is a property that returns a QueryDict, so you work with:
code = request.data
It however makes no sense to specify args=[code], since code is a dictionary-like structure.
Likely you need some value that corresponds to some key from the request.data, so something like:
code = request.data['code']

How to deserialize base64-encoded data and use it with DRF

My goal is to come up with an endpoint that gets a base64-decoded string.
This is based described by an example
My input JSON looks like this:
{
"encoded_data": "a2F0aWUsIGpvaG5zLCBrYXRpZUBnbWFpbC5jb20KdG9tbXksbGVlLHRvbW15QGdtYWlsLmNvbQ=="
}
I have tried to implement it the following way, but I end up with the following error message:
JSON parse error - Expecting value: line 1 column 1 (char 0)
Looks like I've messed up the concepts. Really need help on this:
class UsersFileUpload(APIView):
#parser_classes = (MultiPartParser,)
def post(self, request):
stream = base64.b64decode(request.data['encoded_data'])
stream = io.BytesIO(stream)
data = JSONParser().parse(stream)
serializer = UsersSerializer(data=data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
I don't think you're decoding your text correctly, you shouldn't need to use BytesIO.
You should decode the byte string returned from b64decode and then pass it to the JSONParser.
b64decoded_data = base64.b64decode(request.data['encoded_data']).decode('UTF-8')
data = JSONParser().parse(b64decoded_data)

Implement Github API in Python

I'm working on a project using Python(3.6) in which I need to implement GitHub API.
I have tried by using JSON apis as:
from views.py:
class GhNavigator(CreateView):
def get(self, request, *args, **kwargs):
term = request.GET.get('search_term')
username = 'arycloud'
token = 'API_TOKEN'
login = requests.get('https://api.github.com/search/repositories?q=' + term, auth=(username, token))
print(login)
return render(request, 'navigator/template.html', {'login': login})
but it simply returns status 200, I want to get a list of repositories for term which is passed by the user.
How can I achieve that?
Help me, please!
Thanks in advance!
The requests library will return a Response object if you perform a .get(..), .post(..) or anything like that. Since responses can be very huge (hundreds of lines), it does not print the content by default.
But the developers attached some convenient functions to it, for example to interpet the answer as a JSON object. A response object has a .json() function that aims to interpret the content as a JSON string, and returns its Vanilla Python counterpart.
So you can access the response (and render it the way you want), by calling .json(..) on it:
class GhNavigator(CreateView):
def get(self, request, *args, **kwargs):
term = request.GET.get('search_term')
username = 'arycloud'
token = 'API_TOKEN'
response = requests.get('https://api.github.com/search/repositories?q=' + term, auth=(username, token))
login = response.json() # obtain the payload as JSON object
print(login)
return render(request, 'navigator/template.html', {'login': login})
Now of course it is up to you to interpret that object according to your specific "business logic", and render a page that you think contains the required information.

Python convert python-amazon-simple-product-api results to json using Django

I am writing an API in Python Django and rest framework. I am using a python packaged called python-amazon-simple-product-api to access amazon advertising API. I am trying to feed the results into the rest framework and return the results as JSON Here is my code so far.
class AmazonProductsViewSet(viewsets.ViewSet):
def list(self, request, format=None):
products = amazon.search(Brand="Microsoft", SearchIndex="Software",
ResponseGroup="Images,ItemAttributes,Accessories,Reviews,VariationSummary,Variations")
products = list(products)
With this code I get the following error;
TypeError: Object of type 'AmazonProduct' is not JSON serializable
So I am trying to find a way of making the AmazonProduct object serializable or a better solution.
Not JSON serializable means that your response is an object not a primitive data that can be sent over a network.
You need to write a serializer for that model. Something like this:
class AmazonProductSerializer(serializers.Serializer):
color = serializers.CharField()
title = serializers.CharField()
and use it like this:
products = amazon.search(Brand="Microsoft", SearchIndex="Software", ResponseGroup="Images,ItemAttributes,Accessories,Reviews,VariationSummary,Variations")
data = AmazonProductSerializer(products, many=True).data
return Response(data, status=status.HTTP_200_OK)
Hope it helps!
Probably the best approach is to use the bottlenose [ https://github.com/lionheart/bottlenose ] instead if you just want to get the amazon results as they're and convert to JSON. Here is how I have done it;
amazon = bottlenose.Amazon(access_key_id, secret_key, associate_tag)
class AmazonProductsViewSet(viewsets.ViewSet):
def list(self, request, format=None):
response = amazon.ItemSearch(Keywords="Kindle 3G", SearchIndex="All")
return Response(xmltodict.parse(response)) #json.dumps(xmltodict.parse(response))
Now I get the entire XML document as JSON.

is not JSON serializable

I have the following ListView
import json
class CountryListView(ListView):
model = Country
def render_to_response(self, context, **response_kwargs):
return json.dumps(self.get_queryset().values_list('code', flat=True))
But I get following error:
[u'ae', u'ag', u'ai', u'al', u'am',
u'ao', u'ar', u'at', u'au', u'aw',
u'az', u'ba', u'bb', u'bd', u'be', u'bg',
u'bh', u'bl', u'bm', u'bn', '...(remaining elements truncated)...']
is not JSON serializable
Any ideas ?
It's worth noting that the QuerySet.values_list() method doesn't actually return a list, but an object of type django.db.models.query.ValuesListQuerySet, in order to maintain Django's goal of lazy evaluation, i.e. the DB query required to generate the 'list' isn't actually performed until the object is evaluated.
Somewhat irritatingly, though, this object has a custom __repr__ method which makes it look like a list when printed out, so it's not always obvious that the object isn't really a list.
The exception in the question is caused by the fact that custom objects cannot be serialized in JSON, so you'll have to convert it to a list first, with...
my_list = list(self.get_queryset().values_list('code', flat=True))
...then you can convert it to JSON with...
json_data = json.dumps(my_list)
You'll also have to place the resulting JSON data in an HttpResponse object, which, apparently, should have a Content-Type of application/json, with...
response = HttpResponse(json_data, content_type='application/json')
...which you can then return from your function.
class CountryListView(ListView):
model = Country
def render_to_response(self, context, **response_kwargs):
return HttpResponse(json.dumps(list(self.get_queryset().values_list('code', flat=True))),mimetype="application/json")
fixed the problem
also mimetype is important.

Categories

Resources