def ask_search(request, language='en', as_json=False): if 'selected_facets' in request.GET: return redirect_ask_search(request, language=language) language_map = {'en': 'ask-cfpb-search-results', 'es': 'respuestas'} results_page = get_object_or_404(AnswerResultsPage, language=language, slug=language_map[language]) # If there's no query string, don't search search_term = request.GET.get('q', '') if not search_term: results_page.query = '' results_page.result_query = '' return results_page.serve(request) page = AnswerPageSearch(search_term, language=language) response = page.search() # Check if we want to use the suggestion or not suggest = request.GET.get('correct', '1') == '1' # Provide a suggestion only when no results are found if not response.get('results') and suggest: response = page.suggest() suggestion = response.get('suggestion') else: suggestion = search_term if as_json: payload = { 'query': search_term, 'result_query': make_safe(search_term).strip(), 'suggestion': make_safe(suggestion).strip(), 'results': [{ 'question': result.autocomplete, 'url': result.url, 'text': result.text, 'preview': result.preview, } for result in response.get('results')] } json_results = json.dumps(payload) return HttpResponse(json_results, content_type='application/json') results_page.query = search_term results_page.result_query = response.get('search_term') results_page.suggestion = response.get('suggestion') results_page.answers = [(result.url, result.autocomplete, result.preview) for result in response['results']] return results_page.serve(request)
def ask_autocomplete_es7(request, language='en'): term = request.GET.get('term', '') safe_term = make_safe(term) if not safe_term: return JsonResponse([], safe=False) try: results = AnswerPageSearch(search_term=safe_term).autocomplete() return JsonResponse(results, safe=False) except IndexError: return JsonResponse([], safe=False)
def test_make_safe(self): test_phrase = 'Would you like green eggs and ^~`[]#<>;|%\\{\\}\\?' self.assertEqual( make_safe(test_phrase), 'Would you like green eggs and ?' )
def clean_q(self): return make_safe(self.cleaned_data['q'])
def clean_term(self): return make_safe(self.cleaned_data['term'])