def search(request, title, limit=10, entities_include=False, entities_limit=5, lookup_type=None, lookup_token=None): results = [] search_type = None if lookup_type is not None and lookup_token is not None: # ------------------------------- # External "lookup" # ------------------------------- search_type = 'lookup' # Check lookup_type is valid lookup_type_valid = False try: for type_id, _ in Recipient.TYPES: if int(lookup_type) == int(type_id): lookup_type_valid = True lookup_type = int(lookup_type) break except ValueError: pass if not lookup_type_valid: print "error" return cors_response(build_error( API_ERROR.INVALID_PARAMETER, parameter='lookup_type' )) # Find the token in our database token = None try: token = Token.objects.filter( token_type=Token.TOKEN_RECIPIENT_LOOKUP, token=lookup_token ) if len(token) == 1: token = token[0] else: token = None except Token.DoesNotExist: pass # Check token is still valid if token and token.valid(): token.delete() # Token has been used, let's remove it. if 'title' in token.data and token.data['title'] == title: results = entitygen.registry[lookup_type].recipient_create( token.data['title'], limit=9 ) else: return cors_response( build_error(API_ERROR.RECIPIENT.LOOKUP_TOKEN_INVALID)) else: return cors_response( build_error(API_ERROR.RECIPIENT.LOOKUP_TOKEN_INVALID)) else: # ------------------------------- # Direct database "search" # ------------------------------- search_type = 'search' results = Recipient.objects.all().filter( s_title__ilike='%' + search_like(title) + '%' )[:limit] # Append dicts of recipient results items = [] for recipient in results: items.append(recipient.dict( entities_include=entities_include, entities_filter={'parent': None}, entities_limit=entities_limit, check_owner=request.user )) # Build result dict result_dict = { 'success': True, 'items': items } # Create a Token (with a 10 min expire) that can be used for lookups if search_type == 'search': token = Token.objects.create( token_type=Token.TOKEN_RECIPIENT_LOOKUP, expire=datetime.datetime.now( tz=pytz.utc ) + datetime.timedelta(minutes=1), data={ 'title': title } ) result_dict['lookup_token'] = token.token # Return our response return cors_response(simplejson.dumps(result_dict))