是的
,但并非所有响应都是http响应,也并非所有http响应都具有
本身
一个头衔。但我们可以尽最大努力从回复中获取标题。
为了做到这一点,我们可以使用一个html刮刀,比如
beautifulsoup4
[PiPy]
是的。您可能需要安装:
pip install beautifulsoup4 lxml
我们可以通过以下回复获得标题:
from bs4 import BeautifulSoup
def get_response_title(response):
try:
soup = BeautifulSoup(response.content, 'lxml')
return soup.find('title').getText()
except AttributeError:
return None
因此,您可以在中间件中使用它,如:
class AccessLogs(object):
def __call__(self, request):
response = self.get_response(request)
if '/media/' not in request.path:
try:
title = get_response_title(response)
ActivityLog(user=request.user, title=title, pageURL=request.path).save()
except Exception as e:
print(e)
那是说,作为
@IainShelvington says
,它会减慢处理速度,因为我们每次都会查看响应。一些web开发框架
Yesod
[yesodweb.com]
将标题设置为在处理程序中传递的变量,从而使检测更方便。