2016-11-02 100 views
0

我正在構建一個API函數,它允許客戶端發送帶有URL參數的GET請求,服務器接收並處理基於給定信息的文件,並返回一個自定義文件。好消息是我所有的步驟都是獨立工作的!如何使用Django Rest Framework返回HttpResponse?

我能夠得到def get_query函數中的所有內容,除了返回HttpResponse。該函數需要一個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框架缺乏經驗,我不知道是否有實現這個更好的辦法,否則我怎麼會調用該函數def send_file

回答

2

您正在尋找自定義路線。設置你的send_filelist_routehttp://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 
+0

,它運行'高清get_query'並返回404錯誤。 – RknRobin

+0

@RknRobin你的意思是'def get_queryset'? –

+0

雙重檢查後,它實際上運行整個'class SubFileViewSet',包括'def get_queryset',但仍然忽略'def send_file'。 – RknRobin

相關問題