python 字符问题'utf8' codec can't decode byte 0xe6 in position 0:

我用sphinx和django做搜索,但是搜索的时候出现这种错误:'utf8'codeccan'tdecodebyte0xe6inposition0:unexpectedendofdata
出错信息:
Environment:
RequestMethod:GET
RequestURL:http://www.zhima.so:233/search/%E6%89%93%E7%AE%97/
DjangoVersion:1.8.1
PythonVersion:2.7.3
InstalledApplications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'search',
'web')
InstalledMiddleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'search.timermiddleware.TimerMiddleware')
Traceback:
File"/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py"inget_response
132.response=wrapped_callback(request,*callback_args,**callback_kwargs)
File"/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py"in_wrapped_view
110.response=view_func(request,*args,**kwargs)
File"/root/ssbc/web/views.py"insearch
69.keyword.decode('utf-8'),d['offset'],d['ps'],d['category'],d['sort'])
File"/root/ssbc/search/models.py"insearch
26.res=q.ask(subqueries=[q2])
File"/usr/local/lib/python2.7/dist-packages/sphinxit/core/processor.py"inask
287.returnself.connector.execute(query_batch)
File"/usr/local/lib/python2.7/dist-packages/sphinxit/core/connector.py"inexecute
149.raiseSphinxQLDriverException(e)
ExceptionType:SphinxQLDriverExceptionat/search/打算/
ExceptionValue:'utf8'codeccan'tdecodebyte0xe6inposition0:unexpectedendofdata
views.py:
#coding:utf8
importre
importdatetime
importsys
importurllib
fromdjango.httpimportHttp404
fromdjango.views.decorators.cacheimportcache_page
fromdjango.shortcutsimportrender,redirect
fromlibimportpolitics
importworkers.metautils
fromsearch.modelsimportRecKeywords,Hash
reload(sys)
sys.setdefaultencoding('utf-8')
re_punctuations=re.compile(
u"。|,|,|!|…|!|《|》|<|>|\"|'|:|:|?|\?|、|\||“|”|‘|’|;|—|(|)|·|\(|\)| |\.|【|】|『|』|@|&|%|\^|\*|\+|\||<|>|~|`|\[|\]")
@cache_page(600)
defindex(request):
reclist=RecKeywords.objects.order_by('-order')
returnrender(request,'index.html',{'reclist':reclist})
@cache_page(3600*24)
defhash(request,h):
try:
res=Hash.objects.list_with_files([h])
j=res[0]
except:
raiseHttp404(sys.exc_info()[1])
d={'info':j}
d['keywords']=list(
set(re_punctuations.sub(u'',d['info']['name']).split()))
if'files'ind['info']:
d['info']['files']=[
yforyind['info']['files']ifnoty['path'].startswith(u'_')]
d['info']['files'].sort(key=lambdax:x['length'],reverse=True)
d['magnet_url']='magnet:?xt=urn:btih:'+d['info']['info_hash']+\
'&'+urllib.urlencode({'dn':d['info']['name'].encode('utf8')})
d['download_url']='http://www.haosou.com/s?'+\
urllib.urlencode(
{'ie':'utf-8','src':'ssbc','q':d['info']['name'].encode('utf8')})
returnrender(request,'info.html',d)
@cache_page(1800)
defsearch(request,keyword=None,p=None):
ifnotkeyword:
returnredirect('/')
ifpolitics.is_sensitive(keyword):
returnredirect('/?'+urllib.urlencode({'notallow':keyword.encode('utf8')}))
keyword=keyword
printkeyword
#keyword=unicode(keyword,errors='ignore')
d={'keyword':keyword}
d['words']=list(set(re_punctuations.sub(u'',d['keyword']).split()))
try:
d['p']=int(porrequest.GET.get('p'))
except:
d['p']=1
d['category']=request.GET.get('c','')
d['sort']=request.GET.get('s','create_time')
d['ps']=10
d['offset']=d['ps']*(d['p']-1)
res=Hash.objects.search(
keyword.decode('utf-8'),d['offset'],d['ps'],d['category'],d['sort'])
printres
d.update(res)
#Fillinfo
ids=[str(x['id'])forxind['result']['items']]
ifids:
items=Hash.objects.list_with_files(ids)
forxind['result']['items']:
foryinitems:
ifx['id']==y['id']:
x.update(y)
x['magnet_url']='magnet:?xt=urn:btih:'+x['info_hash']+\
'&'+\
urllib.urlencode({'dn':x['name'].encode('utf8')})
x['maybe_fake']=x['name'].endswith(
u'.rar')oru'BTtiantang.com'inx['name']oru'liangzijie'inx['name']
if'files'inx:
x['files']=[
zforzinx['files']ifnotz['path'].startswith(u'_')][:5]
x['files'].sort(
key=lambdax:x['length'],reverse=True)
else:
x['files']=[
{'path':x['name'],'length':x['length']}]
#pagination
w=10
total=int(d['result']['meta']['total_found'])
d['page_max']=total/\
d['ps']iftotal%d['ps']==0elsetotal/d['ps']+1
d['prev_pages']=range(
max(d['p']-w+min(int(w/2),d['page_max']-d['p']),1),d['p'])
d['next_pages']=range(
d['p']+1,int(min(d['page_max']+1,max(d['p']-w/2,1)+w)))
d['sort_navs']=[
{'name':'按收录时间','value':'create_time'},
{'name':'按文件大小','value':'length'},
{'name':'按相关性','value':'relavance'},
]
d['cats_navs']=[{'name':'全部','num':total,'value':''}]
forxind['cats']['items']:
v=workers.metautils.get_label_by_crc32(x['category'])
d['cats_navs'].append(
{'value':v,'name':workers.metautils.get_label(v),'num':x['num']})
returnrender(request,'list.html',d)
defhash_old(request,h):
returnredirect('/hash/'+h,permanent=True)
defsearch_old(request,kw,p):
returnredirect('list',kw,p)
@cache_page(3600*24)
defhowto(request):
returnrender(request,'howto.html',{})
犯罪嫌疑人X
浏览 1040回答 2
2回答

慕运维8079593

/search/%E6%89%93%E7%AE%97/URL里不要使用ASCII以外的字符试试。当然更好的办法是不要使用Python2。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript