DjangoRestAPI使用ModelViewSet在运行自己的函数(如事件处理程序)时执行数据库管理

2024-05-15 08:38:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我习惯于使用flask作为API,使用Django作为数据库,我正在努力学习Django API。我遵循官方的Quickstart和medium的另一个教程,做了很多研究,但我仍然难以理解如何实现自己的功能(例如:进行一些计算或请求Twilio api在收到api请求后发送消息)在ModelViewSet中。我已经了解到APIView也可以是另一个选项,但它会使访问数据库变得非常困难吗?当我在views.py中的ModelViewSet类中运行打印函数或@action函数时,它只在服务器启动时的程序开始时打印一次。这是我在Flask中的代码版本,也是我在Django中尝试过的

我应该继承哪个类(APIView、Viewset或ModelViewSet)以及在哪里可以查找有关该类的详细信息?

非常感谢您提前提供的帮助:-请注意,flask实现是一个get请求

@app.route('/api/upload/<uuid>/<major>/<minor>/<rssi>',methods=['GET'])
def beacon_info_upload(uuid,major,minor,rssi):
    if 'uuid' in request.args:
        uuid = str(request.args['uuid'])
    if 'major' in request.args:
        major = str(request.args['major'])
    if 'minor' in request.args:
        minor = str(request.args['minor'])
    if 'rssi' in request.args:
        rssi = str(request.args['rssi'])
    qualify = send_twilio_message(uuid,major,minor,rssi)
    return jsonify(uuid,major,minor,qualify)

尝试使用Django(views.py)

class beacon_occuranceViewSet(viewsets.ModelViewSet):
    queryset = beacon_occurance.objects.all().order_by('from_location')
    serializer_class = beacon_occuranceSerializer
    print("event occ beacon occ views.py L32 success experiment") #only prints once at the beginning

    @action(detail=True, methods=['post'])
    def register(self, request, pk=None):
        print("hello!!!!! L38") #only prints once at the beginning
        beacon = self.get_object()
        print(beacon)

class beacon_occuranceSerializer(serializers.HyperlinkedModelSerializer):
    print("hello") #also only prints once when booting the server
    class Meta:
        model = beacon_occurance
        fields = ('from_location','uuid','major','minor','rssi','time')


Tags: djangoinapiifuuidrequestargsclass
1条回答
网友
1楼 · 发布于 2024-05-15 08:38:43

解决-使用

def create(self, request):
     #do what you want - do access data- do request.data (its a dictionary)
     return super().create(request)

请参阅Custom function which performs create and update on DRF modelViewSet

相关问题 更多 >