查看外部API(弹性搜索) [英] Viewset to access external API (elastic search)

查看:101
本文介绍了查看外部API(弹性搜索)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图使用我的ElasticSearch api通过Django作为一个观点。



这是我的尝试,这不工作。我没有收到错误,但网址实际上甚至不会出现,这使我觉得我的观点被打破了



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']



.py



  import services 

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



urls.py



 从api.views导入ElasticViewSet 
router.register(r'elastic' ,ElasticViewSet,base_name ='Elastic')


解决方案

r get_items 方法返回值。

  def get_items(id,标题):
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']#处理失败验证设计的异常
/ pre>

,并在您的视图中调用方法 get_items
至于裸骨,你可以这样做。

  
class ElasticViewSet(viewsets.ViewSet) :
def list(self,request):
item_list = get_items(id,title)
return响应(data = item_list)


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')

解决方案

Structure your get_items method to return a value.

def get_items(id, title):
    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

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

这篇关于查看外部API(弹性搜索)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆