AttributeError:'Morsel'对象没有属性'replace'

时间:2018-02-04 07:59:13

标签: python

我正在尝试使用localhost上的http.cookies模块运行cookie服务器:

当我使用python3命令运行此文件时,会引发此错误:

127.0.0.1 - - [04/Feb/2018 15:53:45] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [04/Feb/2018 15:53:45] "POST / HTTP/1.1" 303 -
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 48854)
Traceback (most recent call last):
  File "/home/user/anaconda3/lib/python3.6/socketserver.py", line 317, in _handle_request_noblock
    self.process_request(request, client_address)
  File "/home/user/anaconda3/lib/python3.6/socketserver.py", line 348, in process_request
    self.finish_request(request, client_address)
  File "/home/user/anaconda3/lib/python3.6/socketserver.py", line 361, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/home/user/anaconda3/lib/python3.6/socketserver.py", line 696, in __init__
    self.handle()
  File "/home/user/anaconda3/lib/python3.6/http/server.py", line 418, in handle
    self.handle_one_request()
  File "/home/user/anaconda3/lib/python3.6/http/server.py", line 406, in handle_one_request
    method()
  File "CookieServer.py", line 72, in do_GET
    message = "Hey there, " + html_escape(name)
  File "/home/user/anaconda3/lib/python3.6/html/__init__.py", line 19, in escape
    s = s.replace("&", "&") # Must be done first!
AttributeError: 'Morsel' object has no attribute 'replace'

我的环境是Ubuntu 16.04,安装了Anaconda 3。 我提到http.cookies documentation,但我没有弄清楚Morsel对象是什么。

1 个答案:

答案 0 :(得分:1)

在您的CookieServer模块中,您试图逃避cookie属性的值,但是您正在逃避一个Morsel而不是值本身。

>>> c = http.cookies.SimpleCookie()
>>> c['foo'] = 'bar'
>>> c['baz'] = 'quux'
>>> c
<SimpleCookie: baz='quux' foo='bar'>

# The values corresponding to cookie keys are Morsels, not strings:
>>> c['foo']
<Morsel: foo=bar>
>>> html.escape(c['foo'])

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/html/__init__.py", line 19, in escape
    s = s.replace("&", "&amp;") # Must be done first!
AttributeError: 'Morsel' object has no attribute 'replace'

# Use the morsel's value attribute to get the string value that you want:
>>> html.escape(c['foo'].value)
'bar'

所以在你的代码中,行

message = "Hey there, " + html_escape(name)

应该是

message = "Hey there, " + html_escape(name.value)