Return JSON field in GAE ProtoRPC - python

I want to construct an arbitrary json like this and return to the user dynamically
{
"items":[
{
"available":"2",
"capacity":"2",
"name":"name2",
"entityKey":"dkfhakshdfh"
},
{
"available":"1",
"capacity":"1",
"name":"name1",
"entityKey":"dkfhaksdfef"
}
],
"kind":"theatreManagement#show",
"etag":"\"asdfasdfasfasfahih\""w
}
But there seems to be no fields to pass in the json. The fields available are like StringField, BytesField, etc.,
How to return a json object?

OpenAPI services such as those created by the Google Cloud Endpoints Framework need to specify exactly what they return. You should define a message containing fields like 'items', 'kind', 'etag', and so on.

Related

Data manipulation in Django json response

I want to iterate over device object and add a comparison.
The json looks like below. I want to compare let's say if status is 1 to add new field for each device "status" : "available" else "status" : "Occuppied". How can i manipulate json like that?
View:
from django.core import serializers
def ApplicationDetail(request, application_id, cat):
device = Device.objects.all().filter(category=cat)
data = serializers.serialize('json', device)
return HttpResponse(data, content_type='application/json')
JSON:
[
{
"model":"applications.device",
"pk":"70b3d5d720040338",
"fields":{
"icon_name":"amr.jpg",
"application_id":13,
"status":1
}
},
{
"model":"applications.device",
"pk":"70b3d5d72004034c",
"fields":{
"icon_name":"amr.jpg",
"application_id":13,
"status":0
}
}
]
Django's built in serializers are very basic, if you are building some sort of JSON API I'd strongly recommend to check out Django REST Framework (https://www.django-rest-framework.org/). Which allows you to build custom serializers.
To answer you question, it's probably easiest to use the 'python' serializer, manipulate the data and then return a JsonResponse, something like this:
from django.http import JsonResponse
...
data = serializers.serialize('python', device)
for row in data:
row['fields']['status'] = 'available' if row['fields']['status'] else 'occupied'
return JsonResponse(data, safe=False)
In order to serialize objects other than dict you must set the safe parameter to False
https://docs.djangoproject.com/en/3.0/ref/request-response/#jsonresponse-objects

Use existing ModelSerializer with JSONResponse

I have a Twitter authentication view that doesn't use a viewset so the auth can be handled on the backend. The view takes in the oauth_token & uses Twython to get the profile & create a Twitter model.
Currently I just return status 201 on success, but to alleviate the need for another request after creation, I'd like to return the created model. I have a TwitterSerializer already which defines the fields that I want to include, so I'd like to be able to reuse this if possible.
TwitterSerializer
class TwitterSerializer(serializers.ModelSerializer):
class Meta:
model = Twitter
fields = (
"id",
"twitter_user_id",
"screen_name",
"display_name",
"profile_image_url",
)
When I try to use this, I get the error that Instance of TwitterSerializer is not JSON serializable.
serialized = TwitterSerializer(instance=twitter)
return JsonResponse({ "created": serialized })
I could return a serialized instance of the model using serializers.serialize()
serialized = serializers.serialize('json', [twitter, ])
serialized = serialized[0]
return JsonResponse({ "created": serialized })
I could pass the fields kwarg to serialize() but I don't want to have to repeat myself if I don't have to. So would it be possible to re-use my TwitterSerializer in this case? I'm having trouble finding a direct answer since most docs assume you'll be using a ViewSet when using serializerss understandably, and this feels like an edge case. I'm open to suggestions for refactoring this approach as well!
After serialization, you can get your data using data attribute of serializer like this.
serialized = TwitterSerializer(instance=twitter)
return JsonResponse({ "created": serialized.data })
You should use Django rest Response instead of JsonResponse like this
from rest_framework response
serialized = TwitterSerializer(instance=twitter)
return response.Response({ "created": serialized.data })

Django Model Table Input

I am trying to insert a data table in my current project. I was wondering if it is possible to insert one whole table inside one particular Django Model. If I let the user fill this table, like in the example below:
How could I send that data into my model after POST?
As you stated in the comment under the question, your table has got fixed fields which should correspond to your already prepared database model - each table column is a separate model attribute. So the only thing you need to do is send each row input by the user as a separate entry in the JSON POST request which your code will convert into a model class instance and save it to the database. The JSON sent in the POST request could look something like this:
{
"table_entries": [
{
"sku": "22A",
"name": "2B",
"description": "2C",
"price": "2D",
"size": "2E"
},
{
"sku": "3A",
"name": "3B",
"description": "3C",
"price": "3D",
"size": "3E"
},
...
]
}
The functionality you're asking for is quite well covered in the Django REST Framework (DRF), a toolkit to build Web APIs. The general pipeline will be:
Receive the POST request in views.py
Use a model serializer that you need to prepare to convert the request data to a Python object
Save this object in the database
So the views could look something like that (based on examples from the DRF views docs):
from myapp.models import Table
from myapp.serializers import TableSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
class TableView(APIView):
"""
Create a new entry in the Table.
"""
def post(self, request, format=None):
table_entries = request.data["table_entries"]
for entry in table_entries:
# serialize each row
serializer = TableSerializer(data=entry)
if serializer.is_valid():
# you can store the objects in some list and if the're all fine
# use serializer.save() for each of them to save them into the db
else:
# At least one of the entries data is corrupted. You probably want
# to reject the whole request
# ...
This is to show you the general workflow, because the question is quite broad. To go further into details I strongly advise to have a look into the DRF tutorial, as it covers well the topic.

Django json serialize doesn't return Object

I'm trying to write an API view for my Django REST API that takes a Location object and serializers it "by hand" -- with json.dumps. Here's an example:
class LocationDetail(APIView):
def get(self, request, location_id, format=None):
l = Location.objects.get(id=location_id)
response_dict = {
"id": l.id,
"name" : l.name,
}
json_data = json.dumps(response_dict)
return Response(json_data)
this will, quite unsurprisingly, return a json object, such as this:
{"name": "Some Place", "id" : 1, ...}
This does not return a proper API response, according to https://www.hurl.it/.
But I need the API to return an Object. Here's the version where I use the built-in REST Framework's Serializer class:
serialized_location = LocationSerializer(l)
return Response(serialized_location.data)
This throws back the "proper" response, and does not cause an error in hurl.it:
Object {id: 1, name: "Some Place", …}
I'd like to figure out how to emulate the behavior of the REST serializer -- how do I get it to return an Object of json instead of just the json?
Here is the difference in images, one is clearly correct and the other just doesn't look like an API response:
REST framework serializer:
My custom json thing:
My custom json with "object" key addition:
They're weirdly different -- I want mine to be recognized as an API response too.
SOLUTION: If anyone else is interested, what you can do is just not json dump the object. Just return:
return Response(response_dict)
that simple. That will return an object appropriate for parsing.
Maybe you should just try this:
json_data = json.dumps(dict(object=response_dict))

Swagger API documentation

I saw swagger documentation of Flask and Django. In Flask I can design and document my API hand-written.(Include which fields are required, optional etc. under parameters sections).
Here's how we do in Flask
class Todo(Resource):
"Describing elephants"
#swagger.operation(
notes='some really good notes',
responseClass=ModelClass.__name__,
nickname='upload',
parameters=[
{
"name": "body",
"description": "blueprint object that needs to be added. YAML.",
"required": True,
"allowMultiple": False,
"dataType": ModelClass2.__name__,
"paramType": "body"
}
],
responseMessages=[
{
"code": 201,
"message": "Created. The URL of the created blueprint should be in the Location header"
},
{
"code": 405,
"message": "Invalid input"
}
]
)
I can chose which parameters to include, and which not. But how do I implement the same in Django? Django-Swagger Document in
not good at all. My main issue is how do I write my raw-json in Django.
In Django it automates it which does not allows me to customize my json. How do I implement the same kind of thing on Django?
Here is models.py file
class Controller(models.Model):
id = models.IntegerField(primary_key = True)
name = models.CharField(max_length = 255, unique = True)
ip = models.CharField(max_length = 255, unique = True)
installation_id = models.ForeignKey('Installation')
serializers.py
class ActionSerializer(serializers.ModelSerializer):
class Meta:
model = Controller
fields = ('installation',)
urls.py
from django.conf.urls import patterns, url
from rest_framework.urlpatterns import format_suffix_patterns
from modules.actions import views as views
urlpatterns = patterns('',
url(r'(?P<installation>[0-9]+)', views.ApiActions.as_view()),
)
views.py
class ApiActions(APIView):
"""
Returns controllers List
"""
model = Controller
serializer_class = ActionSerializer
def get(self, request, installation,format=None):
controllers = Controller.objects.get(installation_id = installation)
serializer = ActionSerializer(controllers)
return Response(serializer.data)
My questions are
1) If I need to add a field say xyz, which is not in my models how do I add it?
2) Quiet similar to 1st, If i need to add a field which accepts values b/w 3 provided values,ie a dropdown. how do I add it?
3) How I add an optional field? (since in case of PUT request, I might only update 1 field and rest leave it blank, which means optional field).
4) Also how do I add a field that accepts the json string, as this api does?
Thanks
I can do all of these things in Flask by hardcoding my api. But in Django, it automates from my models, which does not(as I believe) gives me the access to customize my api. In Flask, I just need to write my API with hands and then integrate with the Swagger. Does this same thing exist in Django?
Like I just need to add the following json in my Flask code and it will answer all my questions.
# Swagger json:
"models": {
"TodoItemWithArgs": {
"description": "A description...",
"id": "TodoItem",
"properties": {
"arg1": { # I can add any number of arguments I want as per my requirements.
"type": "string"
},
"arg2": {
"type": "string"
},
"arg3": {
"default": "123",
"type": "string"
}
},
"required": [
"arg1",
"arg2" # arg3 is not mentioned and hence 'opional'
]
},
Would this work:
class TriggerView(APIView):
"""
This text is the description for this API
mykey -- My Key parameter
"""
authentication_classes = (BasicAuthentication,)
permission_classes = (IsAuthenticated,)
def post(self, request, format=None):
print request.DATA
return Response(status=status.HTTP_202_ACCEPTED)
the POST request:
Authorization:Basic YWRtaW46cGFzcw==
Content-Type:application/json
{"mykey": "myvalue"}

Categories