想做个类似智能客服的机器人,网上查了下,发现大家再用图灵机器人,注册了下,发现已经没有免费版的了
于是想了下,直接使用django做个简单的api,实现个简单版的机器人先练练手
1.首先在djano里写个简单的api接口
urls.py
path('json_api', views.json_api,name="json_api"),
views.py
import random
import json
def json_api(request):
base_url = 'http://127.0.0.1:8000/'
json_data=json.loads(request.body)
print("json_data:",json_data)
#1.返回随机数
if json_data.get('key')=='随机数':
res=random.sample(range(6),3)
res=[str(i) for i in res]
result=''.join(res)
#返回随机问候语
elif json_data.get('key')=='你好':
result=random.choice(['你好','hello','欢迎你'])
#返回查找已有文章
elif json_data.get('key').startswith('博客'):
titles = Titles.objects.filter(text__contains=json_data.get('key')[3:])
result='\n'.join([i.text+'\t'+base_url+reverse('myapp:title', args=(i.id,)) for i in titles])
else:
result="请试试别的问题!"
data={"name":result}
return JsonResponse(data)
*如果使用post请求,需要把settings.py文件这行注释掉
'django.middleware.csrf.CsrfViewMiddleware',
2.然后编写个简单的命令行
# coding=utf-8
import json
import requests
api_url="http://127.0.0.1:8000/json_api"
print('robot:> hello,welcome!')
while True:
my_input=input("我:> ")
if my_input.strip()=='exit':
print('robot:> 慢走不送' )
break
data = {"key": my_input
}
data=json.dumps(data).encode(encoding='utf-8')
headers={'content-type':'application/json'}
res=requests.post(api_url,data=data,headers=headers).json().get('name')
#res=requests.get(api_url).json().get('name')
print('robot:> ',res)
启动django server
启动客户端
演示效果:
image.png