Django:从中间件获取页面标题



我写了一个小的中间件来跟踪用户活动:

class AccessLogs(object):
def __init__(self, get_response):
    self.get_response = get_response
def __call__(self, request):
    response = self.get_response(request)
    if "/media/" not in request.path:
        try:
            ActivityLog(user=request.user, pageURL=request.path).save()
        except Exception as e:
            print(e)
    return response

有什么方法可以使用这种中间件方法获得页面标题?我在这里查找了很多东西,例如TemplateView,自定义响应,但似乎没有任何作用。是否有任何可以检索访问页面标题的类或功能?任何帮助都将不胜感激。

编辑:我要寻找的是获取页面用户标题刚刚访问的方法,因此我可以在此中间件中将其与数据库中的其他信息一起存储。

,尽管并非所有响应都是http响应,也不是所有HTTP响应都具有本se 标题。但是我们可以尽力从响应中获取标题。

为了做到这一点,我们可以使用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

因此,您可以在中间件中使用它,例如:

类AccessLogs(对象(:    def __call __(自我,请求(:        响应= self.get_response(请求(        如果'/媒体/'不在request.path中:            尝试:                 title = get_response_title(reverse(                ActivityLog(user = request.user, title = title ,pageurl = request.path(.save((            除例外为E:                打印(e(

正如@iainshelvington所说的那样,它会减慢处理的速度,因为我们每次都会看一下响应。一些Web开发框架(例如 yesod [yesodweb.com](将把标题设置为处理程序中传递的变量,从而使检测到更方便。

最新更新