为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

犯罪嫌疑人X 2019-04-19 16:29:51
我用sphinx和django做搜索,但是搜索的时候出现这种错误:'utf8'codeccan'tdecodebyte0xe6inposition0:unexpectedendofdata出错信息:Environment:RequestMethod:GETRequestURL:http://www.zhima.so:233/search/%E6%89%93%E7%AE%97/DjangoVersion:1.8.1PythonVersion:2.7.3InstalledApplications:('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_response132.response=wrapped_callback(request,*callback_args,**callback_kwargs)File"/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py"in_wrapped_view110.response=view_func(request,*args,**kwargs)File"/root/ssbc/web/views.py"insearch69.keyword.decode('utf-8'),d['offset'],d['ps'],d['category'],d['sort'])File"/root/ssbc/search/models.py"insearch26.res=q.ask(subqueries=[q2])File"/usr/local/lib/python2.7/dist-packages/sphinxit/core/processor.py"inask287.returnself.connector.execute(query_batch)File"/usr/local/lib/python2.7/dist-packages/sphinxit/core/connector.py"inexecute149.raiseSphinxQLDriverException(e)ExceptionType:SphinxQLDriverExceptionat/search/打算/ExceptionValue:'utf8'codeccan'tdecodebyte0xe6inposition0:unexpectedendofdataviews.py:#coding:utf8importreimportdatetimeimportsysimporturllibfromdjango.httpimportHttp404fromdjango.views.decorators.cacheimportcache_pagefromdjango.shortcutsimportrender,redirectfromlibimportpoliticsimportworkers.metautilsfromsearch.modelsimportRecKeywords,Hashreload(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=keywordprintkeyword#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']=1d['category']=request.GET.get('c','')d['sort']=request.GET.get('s','create_time')d['ps']=10d['offset']=d['ps']*(d['p']-1)res=Hash.objects.search(keyword.decode('utf-8'),d['offset'],d['ps'],d['category'],d['sort'])printresd.update(res)#Fillinfoids=[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']}]#paginationw=10total=int(d['result']['meta']['total_found'])d['page_max']=total/\d['ps']iftotal%d['ps']==0elsetotal/d['ps']+1d['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',{})
查看完整描述

2 回答

?
慕运维8079593

TA贡献1876条经验 获得超5个赞

/search/%E6%89%93%E7%AE%97/
URL里不要使用ASCII以外的字符试试。当然更好的办法是不要使用Python2。
                            
查看完整回答
反对 回复 2019-04-19
  • 2 回答
  • 0 关注
  • 1039 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信