流程
- 将coreseek/api中的sphinxapi.py复制一份到django项目文件夹
- 修改views.py新增一个结果页面的调用函数
- 新建一个result.html对应views.py的调用函数
- 启动nginx+fastcgi服务器
- 启动coreseek的searchd服务器
- 输入查询结果
修改views.py文件
# -*- coding:utf-8 -*-
from django.shortcuts import render_to_response
from django.http import HttpResponse
from sphinxapi import *
# coreseek服务端searchd信息
MODE = SPH_MATCH_ALL
HOST = 'localhost'
PORT = 9312
INDEX = '*'
# 搜索框主页
def search_form(request):
return render_to_response('search_form.html')
# 搜索结果页面
# 通过request.GET['q']获取附在URL上的查询内容
# 先打开coreseek服务器searchd
# 创建客户端连接服务器
# 执行查询语句
# 将查询结果传给结果页面
def search(request):
global MODE
global HOST
global PORT
global INDEX
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
client = SphinxClient()
client.SetServer( HOST, PORT)
client.SetMatchMode( MODE )
res = client.Query( q, INDEX )
total = res['total_found']
t = res['time'] + ' ' + 'sec'
if res.has_key('words'):
s = res['words'][0]['word']
else:
return render_to_response('search_form.html',{'error': True})
return render_to_response('result.html',{'total_found':total,'use_time':t ,'summary':s ,'matches':res['matches']})
新建一个result.html对应
{% extends "base.html" %}
{% block title %}Result Page{% endblock %}
{% block content %}
<div id="logo" style="text-align: center">
{% load staticfiles %}
<img src="{% static "images/bg.png" %}" alt="bg image"/>
</div>
<form action="/search/" method="get">
<div style="width: 100%; text-align: center;margin-top: 10">
<input type="text" name="q" maxlength="100" size="60">
<input type="submit" value="Search">
</div>
</form>
<div style="margin-bottom: 50">
<p>Total_found : {{ total_found }}, Use_time : {{ use_time }}. </p>
</div>
{% if matches %}
<ul>
{% for match in matches %}
<hr />
<div style="margin-bottom: 20">
<p>Summary is: {{ summary }} </p>
<a href="{{match.attrs.url}}">The url</a>
</div>
{% endfor %}
<ul>
{% else %}
<p> Sorry, Can't find any results! </p>
{% endif %}
{% endblock %}
{% block footer %}
<div style="text-align: center; margin-top: 50">
<p>Thanks for visiting my site.</p>
</div>
{% endblock %}
输入查询结果
启动服务器参考之前文章