Retrieve data from Django API and store it in database - django

I created an API with django
What I want to do is to fetch data from my django API and store it in my database.
serializers.py
from rest_framework import serializers, generics
from Usersapi.models import Userdata
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Userdata
fields = '__all__'
viewsets.py
from Usersapi.models import Userdata
from .serializers import UserSerializer
from rest_framework import viewsets
class UserViewSet(viewsets.ModelViewSet):
queryset = Userdata.objects.all()
serializer_class = UserSerializer
main--> urls.py
from django.contrib import admin
from django.urls import include, path
from rest_framework.urlpatterns import format_suffix_patterns
from .router import router
urlpatterns = [
path('admin/', admin.site.urls),
# path('',include('Usersapi.urls')),
path('client/',include('clientside.urls')),
path('api/', include(router.urls))
]
This is where I am trying to retrieve data from API
clientside--> views.py
from django.shortcuts import render
import coreapi
import json
from django.views import generic
import io
from rest_framework.parsers import JSONParser
def home(request):
client = coreapi.Client()
response = client.get('http://127.0.0.1:8000/api/Usersapi/1/')
stream = io.BytesIO(response)
data = JSONParser().parse(stream)
name = data.get("name")
age = data.get("age")
gender = data.get("gender")
user = UserReceived.objects.create( name = name, age= age, gender = gender)
user.save()
return render(request, 'books.html')
This code is not working. How do I retrieve the data from ('http://127.0.0.1:8000/api/Usersapi/1/')
and store it in my models.py i.e database
clientside --> models.py
from django.db import models
class UserReceived(models.Model):
name = models.CharField(max_length=100)
age = models.PositiveIntegerField()
gender = models.CharField(max_length=50)

Your problem is that the corapi client already returns an ordered dict.
This will work:
def home(request):
client = coreapi.Client()
data = client.get('http://127.0.0.1:8000/api/usersapi/1/')
name = data.get("name")
age = data.get("age")
gender = data.get("gender")
user = UserReceived.objects.create(name=name, age=age, gender=gender)
user.save()
return HttpResponse(f"OKAY, got and saved user {name}")
I created a minimal working example here:
https://github.com/CarliJoy/MWE_SO_59668515

Related

Django - Object of type FloatField is not JSON serializable

I have a service in django, and I am trying to get the list of all vital signs, but when I run it, it throws me the following error.
This is the model "SignoVital".
from django.db import models
from .paciente import Paciente
class SignoVital(models.Model):
oximetria = models.FloatField()
frecuenciaRespiratoria = models.FloatField()
frecuenciaCardiaca = models.FloatField()
temperatura = models.FloatField()
presionArterial = models.FloatField()
glicemia = models.FloatField(),
paciente = models.ForeignKey(
Paciente,
on_delete=models.CASCADE,
unique=False,
blank=True,
null=True
)
This is serializer "SignoVitalSerializer".
from rest_framework import serializers
from hospiApp.models.signoVital import SignoVital
class SignoVitalSerializer(serializers.ModelSerializer):
class Meta:
model = SignoVital
fields = ['oximetria', 'frecuenciaRespiratoria', 'frecuenciaCardiaca', 'temperatura', 'presionArterial', 'glicemia', 'paciente']
This is View "SignoVitalTodosView".
from rest_framework import generics,status, views
from rest_framework.response import Response
from rest_framework.views import APIView
from hospiApp.models.signoVital import SignoVital
from hospiApp.serializers.signoVitalSerializer import SignoVitalSerializer
class SignoVitalTodosView(generics.ListCreateAPIView):
queryset = SignoVital.objects.all()
serializer_class = SignoVitalSerializer
def get(self, request, *args, **kwargs):
return super().get(request, *args, **kwargs)
This is urls.py
from django.contrib import admin
from django.urls import path
from hospiApp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('signoVitalTodos/', views.SignoVitalTodosView.as_view()),
]
Remove the comma after the glicemia = models.FloatField(), line in the SignoVital model and then create the migrations again and apply them using the following commands.
python manage.py makemigrations
python manage.py migrate
This will fix the issue.

In Django how to delete, retrieve, and update a table when calling an external API

I was wondering what the correct way is to delete one table in the database and update it with new information from an external API every time that is called.
Basically, whenever the API would be called, the information saved in the table should be substituted by new one.
my views.py
from rest_framework import generics
from .serializers import TickerSerializer
from ticker.models import Ticker
import requests
import logging
logger = logging.getLogger(__name__)
class TickerList(generics.ListAPIView):
serializer_class = TickerSerializer
queryset = Ticker.objects.all()
class TickerRetrieve(generics.RetrieveUpdateDestroyAPIView):
serializer_class = TickerSerializer
queryset = Ticker.objects.all()
lookup_field = 'id'
def get_object(request):
url = 'https://api.kraken.com/0/public/Ticker?pair=1INCHEUR,1INCHUSD'
response = requests.get(url)
data = response.json()
for key in data['result']:
if isinstance(data['result'][key], int):
continue
crypto_data =data['result'][key]
ticker_data = Ticker(crypto = (key),
crypto = (key),
a_0 = (crypto_data.get('a')[0]),
)
ticker_data.save()
my models.py
from django.db import models
class Ticker(models.Model):
id = models.AutoField(primary_key=True) # auto increment field
crypto = models.CharField(blank=True, null=True, max_length=25)
a_0 = models.FloatField(null=True, blank=True, default=None)
my serializers.py
from rest_framework import serializers
from ticker.models import Ticker
class TickerSerializer(serializers.ModelSerializer):
class Meta:
model = Ticker
fields = (
'id',
'crypto',
'a_0',
)
my urls.py
from .views import TickerList, TickerRetrieve
from django.urls import path
app_name = 'ticker'
urlpatterns = [
path('', TickerList().as_view(), name='ticker'),
path('tickerretrieve/', TickerRetrieve().as_view(), name='tickerretrieve'),
]
Every time that i invoke the API tickerretrieve/ it adds more info to the table, while i need to first delete the existing one.
I researched and tried thoroughly many similar cases here, but none had the example of an an external API with RetrieveUpdateDestroy.

django rest_framework caches sql queries

I am new to Django and React. I am taking over a Django / React project and have an issue where an api url is called:
GET /api/admin/parents/
but the underlying sql statement:
from django.http import HttpResponseRedirect
from django.db.models import Q
from .models import *
from rest_framework import permissions, status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import ListAPIView, ListCreateAPIView, CreateAPIView, RetrieveUpdateAPIView, DestroyAPIView
from .serializers import *
from twilio.rest import Client
class AdminAllParentsView(ListAPIView):
serializer_class = UserSerializer
queryset = User.objects.filter(is_staff=False, is_parent=True, is_active=True)
does not get re-executed each time the GET /api/admin/parents/ call is performed.
Say for instance.. a sql record is changed so that there are fewer records matching the is_parent=True part of the api call / query... the results returned by the api call don't reflect the real / current status of the query. The GET /api/admin/parents/ still returns the data from a previous, sql query ( a cached version I assume ) and does not re-execute the query.
The urls.py part of this is:
from django.urls import path
from rest_framework_jwt.views import obtain_jwt_token
from .views import *
urlpatterns = [
path('admin/parents/', AdminAllParentsView.as_view())
So how to I get current sql data from this each time I do a api call?
jack
... I see in the browser that the /api/admin/parents/ request goes out and returns the old data via json data. It's not a cached browser html thing.
and
... here is the user serializer code... someone said that this might be important too.
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
from .models import *
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = (
'id',
'email',
'first_name',
'last_name',
'is_parent',
'phone',
'mobile_phone',
'address',
'city',
'zip',
'county',
'agency_name',
'caseworker_name',
'caseworker_email',
'caseworker_phone',
'caseworker_ext',
'is_active',
'agency_approved',
)
class UserSerializerWithToken(serializers.ModelSerializer):
token = serializers.SerializerMethodField()
password = serializers.CharField(write_only=True)
def get_token(self, obj):
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
payload = jwt_payload_handler(obj)
token = jwt_encode_handler(payload)
return token
def create(self, validated_data):
password = validated_data.pop('password', None)
instance = self.Meta.model(**validated_data)
if password is not None:
instance.set_password(password)
instance.save()
return instance
class Meta:
model = User
fields = '__all__'

File Upload using Django Rest Framework getting error "No file was submitted."

While trying to upload the file using Postman with Content-Type - multipart/form-data in the headers. I am passing both the fields, but I get the following error:
Error:{"upload_to": ["This field is required."],"file_object": ["No
file was submitted."]}
urls.py
from django.conf.urls import include, url
from rest_framework_nested import routers
from utils.views import TemporaryImageView
from . import views
router = routers.SimpleRouter(trailing_slash=False)
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^upload-temp-image/$', TemporaryImageView.as_view())
]
views.py
from rest_framework import viewsets, filters
import django_filters.rest_framework
from rest_framework.generics import CreateAPIView
from rest_framework.parsers import FileUploadParser, MultiPartParser, FormParser
from utils.serializers.temporary_image import TemporaryImageSerializer
class TemporaryImageView(CreateAPIView):
parser_classes = (MultiPartParser,)
serializer_class = TemporaryImageSerializer
serializers.py
from rest_framework import serializers
from utils.models.tempfile import TemporaryFile
class TemporaryImageSerializer(serializers.ModelSerializer):
choices = (('Company Logo','/company/logos/'),
)
upload_to = serializers.ChoiceField(choices=choices)
file_object = serializers.ImageField()
class Meta:
model = TemporaryFile
fields = ('upload_to', 'file_object')
models.py
from django.db import models
class TemporaryFile(models.Model):
"""
a temporary file to backend
"""
file_object = models.FileField(blank=False, null=False)
timestamp = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return str(self.id)
Please help...I don't know what is wrong.
I have changed my models.py file in the way below and it works as expected..
models.py
from django.db import models
def get_image_path(instance, filename):
if instance.upload_to == "company_logo":
path = 'company/logo/'
return path
class TemporaryFile(models.Model):
"""
a temporary file to backend
"""
file_object = models.FileField(blank=False, null=False, upload_to=get_image_path)
timestamp = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return str(self.id)
def __init__(self, *args, **kwargs):
self.upload_to = kwargs.pop("upload_to")
super(TemporaryFile, self).__init__(*args, **kwargs)

What would be the format of urls.py for class based views?

I am new to django so i want to know how to write urls.py for a project.
I want to make backend api for inventory management system.
When i type localhost:8000/inventory_backend/dep/, I am having following error:
**Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
The current path, inventory_backend/dep/, didn't match any of these.
My code for mysite/urls.py**
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^inventory_backend/', include('inventory_backend.urls')
),
url(r'^admin/', admin.site.urls) ,
]
inventory_backend/urls.py:
from inventory_backend.views import DepartmentsView,InventoriesView
from rest_framework import routers
router = routers.SimpleRouter()
router.register(r'dep/',DepartmentsView )
router.register(r'inv/',InventoriesView )
urlpatterns = router.urls
serializers.py
from rest_framework import serializers
from inventory_backend.models import Departments,Inventories
class DepartmentsSerializer(serializers.ModelSerializer):
class Meta:
model : Departments
fields: ('id','name')
class InventoriesSerializer(serializers.ModelSerializer):
dept = DepartmentsSerializer(many=True)
class Meta:
model : Inventories
fields : ('id','name','description','dept')
models.py
from django.db import models
class Departments(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class Inventories(models.Model):
name = models.CharField(max_length=200)
description = models.CharField(max_length=200)
dept = models.ManyToManyField(Departments)
def __str__(self):
return self.name
views.py
from rest_framework import viewsets
from inventory_backend.models import Inventories,Departments
from inventory_backend.serializers import InventoriesSerializer,
DepartmentsSerializer
class DepartmentsView(viewsets.ModelViewSet):
queryset = Departments.objects.all();
serializer_class = DepartmentsSerializer;
class InventoriesView(viewsets.ModelViewSet):
queryset = Inventories.objects.all();
serializer_class = InventoriesSerializer;
Change your inventory_backend.urls.py,
urlpatterns = [
url(r'^', include(router.urls))
]