Example #1
0
File: views.py Project: gage/proto
def search(request):
    return redirect('registration-signup')
    if request.method == 'GET':
        input_q = request.GET.get("q","")
        q = name_seperate(input_q)
        default_num = 10
        #results = personal_ranking(s_qs=SearchQuerySet().auto_query(q).models(*TYPE['all']), user=request.user)        
        # Find location
        latitude, longitude = get_user_location(request)        
        search_city = request.session.get('search_city', 'Default')
        
        spatial_results = spatial_ranking(personal_ranking(SearchQuerySet().models(*TYPE['spatial']).filter(searchable=True), request.user), latitude, longitude).auto_query(q).load_all()[:default_num]
        spatial_results = get_clear_search_results(spatial_results)        
        
        results = personal_ranking(SearchQuerySet().models(*TYPE['non_spatial']).filter(searchable=True), request.user).load_all().auto_query(q)[:default_num]
        results = get_clear_search_results(results)
        
        results.extend(spatial_results)
        rtn = []
        for result in results:
            if result.pk not in request.user.get_profile().blocked_by_user_set:
                rtn.append(result)
                
        return render(request, 'search_result.html', {
            'results':rtn,
            'search_city':search_city,
            'q': input_q,
            'default_num': default_num,
        })
    else:
        return HttpResponseRedirect(slugreverse(request.user, "user-profile", args=[request.user.id]))
Example #2
0
    def read(self, request):
        """ Search """
        query_term = request.CLEANED['q']
        filter_type = request.CLEANED['filter_type']
        search_fields = request.CLEANED['search_fields']
        offset = int(request.CLEANED['offset']) if request.CLEANED['offset'] else None
        endpoint = int(request.CLEANED['endpoint']) if request.CLEANED['offset'] else None
        total_count = request.CLEANED['total_count'] == True if 'total_count' in request.CLEANED else False
        if not request.CLEANED.has_key('distance'):
            raise Exception('Call super read_validate when overwrite')
        distance = request.CLEANED['distance']
        if request.CLEANED.has_key('custom_query'):
            query_set = request.CLEANED['custom_query']
        else:
            if type(self.query_model)==list:
                query_set = SearchQuerySet().models(*self.query_model).load_all()
            else:
                query_set = SearchQuerySet().models(self.query_model).load_all()

        if self.about_privacy:
            # TODO
            pass

        query_list = []
        query_args = {}
        if filter_type == 'auto_query':
            query_set = query_set.auto_query(query_term)

        elif filter_type == 'auto_complete':
            query_set = query_set.filter(SQ(auto_complete=query_term))

        elif filter_type == 'startswith' or filter_type == 'location':
            query_term_list = process_query(query_term)
            for term in query_term_list:
                query_list.append(reduce(lambda a, b: a | b, [SQ(**{field + '__startswith':term}) for field in search_fields] + [SQ(**{field:term}) for field in search_fields]))
        if filter_type == 'location':
            latitude, longitude = request.CLEANED['location']
            query_set = spatial_ranking(query_set, latitude, longitude, distance, pure_dist=True)

        results = query_set.filter(*query_list)
        if total_count:
            return (results._clone().count(), get_clear_search_results(results[offset:endpoint]))
        else:
            return get_clear_search_results(results[offset:endpoint])
Example #3
0
File: ajax.py Project: gage/proto
def search_filter(request):
    """
        the filter of search.
        return json with search result html
        {
            status: 1(success) or 0(fail),
            html: search results,
            more: 1(has more) or 0 (no more),
            msg: any msg,
        }
    """
    if request.is_ajax and request.GET:
        q = request.GET.get("q", "")
        model = request.GET.get("m", "")
        city_id = request.GET.get("c", "")
        city_name = request.GET.get("name", None)
        from_index = int(request.GET.get("n", ""))
        to_index= int(request.GET.get("to_n", ""))

        if q and model:
            latitude, longitude = get_user_location(request) if city_id == 'null' else get_user_location(request, city_id, reset=True, city_name=city_name)

            if model == 'all':
                spatial_results = spatial_ranking(personal_ranking(SearchQuerySet().models(*TYPE['spatial']).filter(searchable=True), request.user), latitude, longitude).auto_query(q).load_all()[from_index:to_index]
                spatial_results = get_clear_search_results(spatial_results)

                results = personal_ranking(SearchQuerySet().models(*TYPE['non_spatial']).filter(searchable=True), request.user).load_all().auto_query(q)[from_index:to_index]
                results = get_clear_search_results(results)

                results.extend(spatial_results)
            elif model not in DJANGO_CT:
                results = spatial_ranking(personal_ranking(SearchQuerySet().models(*TYPE[model]).filter(searchable=True), request.user), latitude, longitude).auto_query(q).load_all()[from_index:to_index]
                results = get_clear_search_results(results)
            else:
                results = personal_ranking(SearchQuerySet().models(*TYPE[model]).filter(searchable=True), request.user).load_all().auto_query(q)[from_index:to_index]
                results = get_clear_search_results(results)

            rtn = []
            for result in results:
                if result.pk not in request.user.get_profile().blocked_by_user_set:
                    rtn.append(result)

            search_result = render_to_string('inc_search_result.html',{
                 #'results': results[start:start+num]
                 'results': rtn
            }, context_instance = RequestContext(request))
            response = {
                'status' : 1,
                'html' : search_result,
                'more' : 1,
                'msg' : '',
                'search_city' : request.session.get('search_city', 'Default'),
            }
        else:
            response = {
                'status' : 0,
                'html' : '',
                'more' : 0,
                'msg' : 'error',
            }

        return HttpResponse(json.dumps(response), mimetype="application/json")
    else:
        response = {
                'status' : 0,
                'html' : '',
                'more' : 0,
                'msg' : 'error',
            }
        return HttpResponse(json.dumps(response), mimetype="application/json")
Example #4
0
File: ajax.py Project: gage/proto
 def p_search(search_set, model_name):
     if model_name in ['event', 'user']:
         search_results[model_name]['result'] = get_clear_search_results(search_set.load_all()[:3])
     elif model_name in ['place', ]:
         search_results[model_name]['result'] = get_clear_search_results(spatial_ranking(search_set, latitude, longitude).load_all()[:3])
Example #5
0
File: ajax.py Project: gage/proto
def auto_complete_place(request):
    """ place autocomplete
    """
    q = request.GET.get('q', None)
    params = request.GET.get('other_params', None)
    limit = request.GET.get('limit', 10)

    latlon = None

    if params:
        params = json.loads(params)
        if 'lat' in params and 'lon' in params:
            latlon = (float(params['lat']), float(params['lon']))

    """ query handler """
    if q is None or q == '':
        return HttpResponse('', mimetype="text/plain")

    query_list = process_query(q)
    results = None

    # handle = open("/tmp/search.log","w")
    # ISOTIMEFORMAT='%Y-%m-%d %X'
    if latlon:
        latitude, longitude = latlon
    else:
        latitude, longitude = get_user_location(request)
    # t = time.strftime( ISOTIMEFORMAT, time.localtime() )
    # handle.write('start search:%s\n'%t)
    has_query = False
    for q_o in query_list:
        if q_o:
            if not has_query:
                has_query = True
                results = personal_ranking(s_qs=SearchQuerySet().filter(name__startswith=q_o), user=request.user)
            else:
                results = results.filter(name__startswith=q_o)
    if has_query:
        results = get_clear_search_results( spatial_ranking(results.models(Place), latitude, longitude, pure_dist=True).load_all()[:limit] )
    else:
        results = []
    # t = time.strftime( ISOTIMEFORMAT, time.localtime() )
    # handle.write('end search:%s\n'%t)
    tmp_response = []
    for result in results:
        # t = time.strftime( ISOTIMEFORMAT, time.localtime() )
        # handle.write('result:%s\n'%t)
        score_field = '%s_d'%request.user.id
        score = result.__dict__[score_field] if score_field in result.__dict__ else 'x'
        img_url = result.object.get_display_photo().image26x26.url
        img_url_l = result.object.get_display_photo().image105x105.url
        url = result.object.get_absolute_url()
        name = result.object.get_display_name()
        category = result.object.category
        if len(name) > 30:
            name = '%s..' % name[:30]
        item = [
            result.pk,
            name,
            result.model_name,
            '%s' % score,
            url,
            img_url,
            img_url_l,
            category,
        ]
        tmp_response.append(item)
    # tmp_response.sort(key=lambda obj: obj[1].lower().startswith(q),reverse=True)
    # t = time.strftime( ISOTIMEFORMAT, time.localtime() )
    # handle.write('End of all:%s\n'%t)
    response = ["|".join(r) for r in tmp_response]
    response_txt = '\n'.join(response)
    return HttpResponse(response_txt, mimetype="text/plain")