【问题标题】:How can I return an HttpResponse with Django Rest Framework?如何使用 Django Rest 框架返回 HttpResponse?
【发布时间】:2016-11-02 07:13:33
【问题描述】:

我正在构建一个 API 函数,允许客户端发送带有 URL 参数的 GET 请求,服务器根据给定的信息接收和处理文件,并返回一个自定义文件。好消息是我的所有步骤都是独立工作的!

我能够在返回 HttpResponse 的 def get_query 函数 except 中让一切正常工作。该函数需要一个 Queryset 响应(我猜是有道理的..)。我想我需要另一个函数来返回 HttpResponse,所以我创建了def send_file。我不知道如何调用这个函数,现在它只是跳过它。

views.py.

class SubFileViewSet(viewsets.ModelViewSet):

    queryset = subfiles.objects.all()
    serializer_class = SubFilesSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,
                          IsOwnerOrReadOnly,)

    def send_file(self, request):

        req = self.request
        make = req.query_params.get('make')
        model = req.query_params.get('model')
        plastic = req.query_params.get('plastic')
        quality = req.query_params.get('qual')
        filenum = req.query_params.get('fileid')
        hotend = req.query_params.get('hotendtemp')
        bed = req.query_params.get('bedtemp')

        if make and model and plastic and quality and filenum:            

            filepath = subfiles.objects.values('STL', 'FileTitle').get(fileid = filenum)

            path = filepath['STL']
            title =  filepath['FileTitle']    

            '''
            #Live processing (very slow)
            gcode = TheMagic(
                make=make, 
                model=model, 
                plastic=plastic, 
                qual=quality, 
                path=path, 
                title=title, 
                hotendtemp=hotend,
                bedtemp=bed)

            '''
            #Local data for faster testing
            gcode = "/home/bradman/Documents/Programming/DjangoWebProjects/3dprinceprod/fullprince/media/uploads"

            test_file = open(gcode, 'r')
            response = HttpResponse(test_file, content_type='text/plain')
            response['Content-Disposition'] = "attachment; filename=%s" % title


            print (response)
            return response

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


    def get_queryset(self):
        req = self.request
        make = req.query_params.get('make')
        model = req.query_params.get('model')
        plastic = req.query_params.get('plastic')
        quality = req.query_params.get('qual')
        filenum = req.query_params.get('fileid')
        hotend = req.query_params.get('hotendtemp')
        bed = req.query_params.get('bedtemp')

        return self.queryset
        #function proved in here then removed and placed above
        #get_query required a queryset response

我对 Django Rest Framework 几乎没有经验,我不确定是否有更好的方法来实现它,或者我如何调用函数def send_file

【问题讨论】:

    标签: python django python-3.x request django-rest-framework


    【解决方案1】:

    您正在寻找自定义路线。将您的send_file 设置为list_route http://www.django-rest-framework.org/api-guide/viewsets/#marking-extra-actions-for-routing

    from rest_framework.decorators import list_route
    
    class SubFileViewSet(viewsets.ModelViewSet):
        ...
    
        @list_route(methods=['get'])
        def send_file(self, request):
            ...
    

    然后你就可以访问这个方法了

    /subfile/send_file/?params
    

    【讨论】:

    • 当我从客户端请求访问它时,它运行 def get_query 并返回 404 错误。
    • @RknRobin 你的意思是def get_queryset?
    • 经过仔细检查,它实际上运行了整个class SubFileViewSet,包括def get_queryset,但仍然忽略了def send_file
    • @RknRobin 你按照我的建议做了吗,现在使用包含send_file的网址?
    • 是的,我从客户端运行了requests.get(SERVER + '/api/files/send_file/', auth=(authuser, authpass), params=data)。我现在只能从客户端的 url 得到 404 错误。但是,我可以在浏览器的 url 中访问它并运行该函数。
    猜你喜欢
    • 2021-08-14
    • 2017-08-21
    • 2014-10-16
    • 1970-01-01
    • 2017-02-05
    • 2021-09-26
    • 1970-01-01
    • 2022-08-16
    • 2018-06-30
    相关资源
    最近更新 更多