我用Django创建了一个API
我要做的是从django API中获取数据并将其存储在数据库中。
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))
]
这是我尝试从API检索数据的地方 客户端-> 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')
此代码不起作用。如何从('http://127.0.0.1:8000/api/Usersapi/1/')检索数据 并将其存储在我的models.py数据库中
客户端-> 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)
答案 0 :(得分:1)
您的问题是corapi客户端已经返回了命令字典。
这将起作用:
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}")
我在这里创建了一个最小的工作示例: https://github.com/CarliJoy/MWE_SO_59668515