Ubuntu + coreseek + python + mysql (三、通过前端html进行搜索,用python处理数据)

首先要引入API:

通过路径/usr/local/coreseek-4.1-beta/csft-4.1/api 找到sphinxapi.py

复制sphinxapi.py到工程中去,在使用时,需要在文件头部这样引入即可:

from sphinxapi import *
import sys, time

前端的HTML,是一个很简单的form表单

<pre name="code" class="html"><div class="row">
     <div class="col-xs-12 col-sm-6 col-md-4 col-lg-4">
          <form id="form3" action="../search3/" method="post">
	        <div class="input-group">
		     <input type="text" id="content" name="content" class="form-control" placeholder="id/name/text" aria-describedby="basic-addon2">
		     <span class="input-group-btn">
			   <button class="btn btn-default" type="button" onclick="submit3()">搜索</button>
		     </span>
		</div>
          </form>
     </div>
</div>

JS文件,用户判断输入是否为空,然后提交form表单,通过form 中的action 来设置表单由哪段后台代码或文件处理,此处是search3这个函数

function submit3(){
  if(!$("#content").val()){
	alert("表单不能为空");
  } else {
  	$("#form3").submit();
  }
}

search3 函数

(别忘了在这个函数的文件头,添加 from sphinxapi import * 和 import sys, time两句代码)

我用的是django,绿色代码是比较核心、通用的部分

def search3(request):
<span style="color:#FFCC00;">    <span style="color:#33CC00;">q = request.REQUEST.get("content")
    mode = SPH_MATCH_ALL
    host = 'localhost'
    port = 9312
    index = 'mysql'
    filtercol = ''
    filtervals = []
    sortby = ''
    groupby = ''
    groupsort = ''
    limit = 0

    # do query
    cl = SphinxClient()
    cl.SetServer ( host, port )
    cl.SetWeights ( [100, 1] )
    cl.SetMatchMode ( mode )
    if filtervals:
        cl.SetFilter ( filtercol, filtervals )
    if groupby:
        cl.SetGroupBy ( groupby, SPH_GROUPBY_ATTR, groupsort )
    if sortby:
        cl.SetSortMode ( SPH_SORT_EXTENDED, sortby )
    if limit:
        cl.SetLimits ( 0, limit, max(limit,1000) )
    res = cl.Query ( q, index )
    print "res:",res</span></span>
    if res['total'] is 0:
        print 'query failed: %s' % cl.GetLastError()
        return HttpResponse('木有查到')
    else: 
        result = []
        s0 = ''#s1和s0的命名很傻很天真
        s1 = '('
        length = len(res['matches'])
        for i in range(0,length):
            result.append(res['matches'][i]['id'])
            s0 = str(result[i])
            s1 = s1 + s0 + ','  #先用“+”号,以后换成join等更好的方法
        s1 = s1[0:-1] + ')'
        
        '''
        以下是通过id到mysql test tb_test中查询数据
        '''
        import MySQLdb
        import json
        conn = MySQLdb.connect(host='localhost',
                             user='root',
                             passwd='admin',
                             db='test',
                             charset='utf8'
                             )
        cur = conn.cursor()        
        sql = 'SELECT * FROM test.tb_test WHERE id IN %s' % s1
        cur.execute(sql)
        
        result = []
        args = {}
        i = 0
        for row in cur.fetchall():
            list = {}
            list["id"] = row[0]
            list["name"] = row[1]
            list["text"] = row[2]
            result.append(list)
        cur.close()  
        conn.close()  
        args["test_list"] = json.dumps(result)
         
        instance, type, name = get_instance_and_type(request.user)
        if instance.photo :
            photourl = instance.photo.url
            args['photourl'] = photourl
        args["name"] = name
        args["keyword"] = q
        return render_to_response('test_list.html',args)

test_list.html如下

<div class="container theme-showcase" role="main">
	<div id="result" style="display:none;">
		{{ test_list }}
	</div>
	<input type="hidden" id="keyword" value={{ keyword }}>
	<div class="row" id="test_list">
	</div>
</div>



你可能感兴趣的:(Ubuntu + coreseek + python + mysql (三、通过前端html进行搜索,用python处理数据))