Py学习  »  Django

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

Naeem Khan • 4 年前 • 582 次点击  

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

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、自定义响应,但似乎没有任何工作。是否有任何类或函数检索访问过的页的标题?任何帮助都将不胜感激。

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

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/46699
 
582 次点击  
文章 [ 1 ]  |  最新文章 4 年前
Willem Van Onsem
Reply   •   1 楼
Willem Van Onsem    4 年前

是的 ,但并非所有响应都是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] 将标题设置为在处理程序中传递的变量,从而使检测更方便。