简体   繁体   English

在同一项目中使用Django Rest Api

[英]Consuming Django Rest Api in the same project

I'm pretty new to django's rest framework and I built my first example api using the official tutorial here . 我对django的rest框架还很陌生,我使用此处的官方教程构建了我的第一个示例api。 But I have no idea how to consume this api's data into another app in the same project such it's data can be rendered into HTML. 但是我不知道如何将这个api的数据消费到同一项目中的另一个应用程序中,这样它的数据可以呈现为HTML。

Suppose I create an API students for students(with their details) in a school. 假设我为学校的学生(及其详细信息)创建了一个API students Now how do I use this api in the same project to display number of student in schools and their details. 现在,我如何在同一项目中使用此api来显示学校的学生人数及其详细信息。

Most of the tutorials or explanations online are for third party API's and I can't figure out how to proceed. 在线上的大多数教程或解释都是针对第三方API的,我不知道该如何进行。 Thanks in advance. 提前致谢。

models.py

class Test(models.Model):
    date = models.DateTimeField(auto_now_add=True)
    test_name = models.CharField(max_length=200,default='simple blood test',blank=False)
    subject = models.CharField(max_length=100,default='')

def __str__(self):
    return self.test_name

class Person(models.Model):
    tests = models.ManyToManyField(Test)
    title = models.CharField(max_length=3,default="mr",blank=False)
    name = models.CharField(max_length=50,default='',blank=False)

def __str__(self):
    return self.name

views.py

class PersonList(generics.ListCreateAPIView):
    queryset = Person.objects.all()
    serializer_class = PersonSerializer

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)


class PersonDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Person.objects.all()
    serializer_class = PersonSerializer

serializers.py

class TestSerializer(serializers.ModelSerializer):
    class Meta:
        model = Test
        fields = ('test_name','subject')

class PersonSerializer(serializers.HyperlinkedModelSerializer):
    owner = serializers.ReadOnlyField(source='owner.username')
    tests = TestSerializer(many=True, read_only=True)
    class Meta:
        model = Person
        fields = ('url','id','name') 

This is my API definiton. 这是我的API定义。 I want to create another app to display data such list of all students and details about them etc. 我想创建另一个应用程序以显示数据,例如所有学生的列表以及有关他们的详细信息等。

You will have to hit your endpoints in your consuming view, the easiest way to do this is with the requests library. 您将必须在使用方视图中命中端点,最简单的方法是使用requests库。 First install the library: 首先安装库:

pip install requests

Then use it in your consuming view: 然后在您的使用视图中使用它:

def consumer_view(request):
    response = requests.get('http://your-url.com/your-endpoint')
    # do what you need to do here

You can use response.json() to get the JSON response form your API as a Python dictionary. 您可以使用response.json()从API作为Python字典获取JSON响应。 If you are just using ./manage.py runserver your URL will be: 如果您仅使用./manage.py runserver URL为:

http:localhost:8000/your-endpoint

or 要么

http://192.168.0.1:8000/your-endpoint

This way of consuming an API is somewhat redundant if you are working completely within Django. 如果您完全在Django中工作,则使用API​​的这种方式有些多余。 It's often much easier to use the ORM in these cases. 在这些情况下,使用ORM通常会容易得多。 However if you are making the API to be available for outside use (either publicly or via API keys) then this approach makes sense. 但是,如果您要使该API供外界使用(公开或通过API密钥),则此方法很有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM