import json
from django.core.serializers.json import DjangoJSONEncoder
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404
from data_center.models import Course
from django.db.models import Q
from django.views.decorators.cache import cache_page

from haystack.query import SearchQuerySet
from haystack.inputs import AutoQuery
# Create your views here.

def search(request):
    q = request.GET.get('q', '')
    next_page = request.GET.get('next_page', '')

    courses = SearchQuerySet().filter(content=AutoQuery(q))
    courses = Course.objects.filter(pk__in=[c.pk for c in courses]). \
        values('id', 'no', 'eng_title', 'chi_title', 'note', 'objective',
            'time', 'teacher', 'room', 'credit', 'prerequisite').order_by('-hit')

    pager = Paginator(courses, 10)

    try:
        courses_page = pager.page(next_page)
    except PageNotAnInteger:
        courses_page = pager.page(1)
    except EmptyPage:
        courses_page = pager.page(pager.num_pages)

    result = {
        'total': courses.count(),
        'next': courses_page.next_page_number() if courses_page.has_next() else pager.num_pages,
        'courses': list(courses_page.object_list)
    }

    return HttpResponse(json.dumps(result, cls=DjangoJSONEncoder))


@cache_page(60 * 60)
def syllabus(request, id):
    course = get_object_or_404(Course, id=id)
    return render(request, 'syllabus.html', {'course': course})


@cache_page(60 * 60)
def hit(request, id):
    course = get_object_or_404(Course, id=id)
    course.hit += 1
    course.save()
    return HttpResponse('')

@@ -1,12 +1,36 @@
+# -*- coding: utf-8 -*-%0A
 import json%0A
@@ -482,16 +482,343 @@
 s here.%0A
+import re%0Adef group_words(s):%0A    regex = %5B%5D%0A%0A    # Match a whole word:%0A    regex += %5Bur'%5Cw+'%5D%0A%0A    # Match a single CJK character:%0A    regex += %5Bur'%5B%5Cu4e00-%5Cufaff%5D'%5D%0A%0A    # Match one of anything else, except for spaces:%0A    regex += %5Bur'%5B%5E%5Cs%5D'%5D%0A%0A    regex = %22%7C%22.join(regex)%0A    r = re.compile(regex)%0A%0A    return r.findall(s)%0A%0A
 %0Adef sea
@@ -864,16 +864,50 @@
 q', '')%0A
+    q = ' '.join(group_words(q))%0A%0A
     next

solve 普物 issue