Haystack/Whoosh 将字符串转换为类似字节的对象? "Cannot use a string pattern on a bytes-like object" 错误

Haystack/Whoosh convert string to bytes-like object? "Cannot use a string pattern on a bytes-like object" error

在我的 Django(2.2.7,Python3.7)项目中,我使用 Haystack(2.8.1) 和 Whoosh(2.7.4) 进行全文搜索。

搜索时,我总是得到 Cannot use a string pattern on a bytes-like object 错误。

我知道,一般来说,为什么会发生这个错误,但我不知道如何避免它。我将适当的字符串关键字传递给 haystack/whoosh 函数,但它可能会在上述库中的某处转换为类似字节的对象。

例如我给它一个字符串 somestring,但它在 "/usr/local/lib/python3.7/site-packages/haystack/inputs.py" 文件中变成了 b'somestring'self.exact_match_re.findall(query_string) 函数中

当时的本地变量:

__class__   
<class 'haystack.inputs.AutoQuery'>
query_obj   
<haystack.backends.whoosh_backend.WhooshSearchQuery object at 0x7fea4c19c550>
query_string    
b'somestring'
self    
<AutoQuery 'somestring'>

整个堆栈跟踪:

ERROR 2019-11-23 01:17:51,136 middlewares 5013 140644284933888 http://www.my_project.loc/hledat?q=ATIKA&x=3&y=16
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python3.7/site-packages/haystack/views.py", line 51, in __call__
    return self.create_response()
  File "/my_project/search/views.py", line 57, in create_response
    for item in self.results:
  File "/usr/local/lib/python3.7/site-packages/haystack/query.py", line 154, in _manual_iter
    if not self._fill_cache(current_position, current_position + ITERATOR_LOAD_PER_QUERY):
  File "/usr/local/lib/python3.7/site-packages/haystack/query.py", line 231, in _fill_cache
    results = self.query.get_results(**kwargs)
  File "/usr/local/lib/python3.7/site-packages/haystack/backends/__init__.py", line 638, in get_results
    self.run(**kwargs)
  File "/usr/local/lib/python3.7/site-packages/haystack/backends/__init__.py", line 550, in run
    final_query = self.build_query()
  File "/usr/local/lib/python3.7/site-packages/haystack/backends/__init__.py", line 693, in build_query
    final_query = self.query_filter.as_query_string(self.build_query_fragment)
  File "/usr/local/lib/python3.7/site-packages/haystack/backends/__init__.py", line 381, in as_query_string
    result.append(query_fragment_callback(field, filter_type, value))
  File "/usr/local/lib/python3.7/site-packages/haystack/backends/whoosh_backend.py", line 801, in build_query_fragment
    prepared_value = value.prepare(self)
  File "/usr/local/lib/python3.7/site-packages/haystack/inputs.py", line 105, in prepare
    exacts = self.exact_match_re.findall(query_string)
TypeError: cannot use a string pattern on a bytes-like object

谢谢。

好的,找到了!

我正在使用自己的 class 自定义搜索查询集 (searchqueryset=MyClass)。

class 的目的是从查询字符串中删除重音符号。有一个函数:

textutil.strip_accents(query_string)

在 class 中,总是返回一个类似字节的对象。

我添加了一个解码来解决这个问题:

textutil.strip_accents(query_string).decode('utf-8')

谢谢。