Viewset to access external API (elastic search)

2019-07-27 22:21发布

问题:

So I'm trying to use my ElasticSearch api via Django as a viewset.

This is my attempt, which doesnt work. I don't get errors, but the URL doesn't actually even appear which makes me think my viewset is broken

services.py import json import requests

def get_items(id, title):
    url = 'http://localhost:9200/_search' 
    params = json.loads(request.GET.body)
    r = requests.get('http://localhost:9200/_search', params=params)
    items = r.json()
    return items['results']

views.py

import services

class ElasticViewSet(viewsets.ViewSet):
    def list(self,request):
        item_list = get_items()
        return item_list
        pass

urls.py

from api.views import ElasticViewSet
router.register(r'elastic', ElasticViewSet, base_name='Elastic')

回答1:

Structure your get_items method to return a value.

import json
import requests

def get_items(request):
    url = 'http://localhost:9200/_search' 
    params = json.loads(request.body)
    r = requests.get('http://localhost:9200/_search', params=params)
    items = r.json()
    return items['results'] # handle exceptions for fail proof design

and call the the method get_items in your views, As for a bare bone, you can do this.

from rest_framework.response import Response
from rest_framework import viewsets

class ElasticViewSet(viewsets.ViewSet):
    def list(self, request):
        item_list = get_items(request)
        return Response(data=item_list)