简体   繁体   English

如何在Django的每个管理页面加载中运行python函数

[英]How to run a python function on every Admin page load in Django

I would like a python function to be run any time a page from the admin interface is loaded. 我希望在从管理界面加载页面的任何时候都可以运行python函数。 This does not need to run on every page load(ie non-admin related pages). 不需要在每个页面加载(即与管理员无关的页面)上运行。 This function requires the request object or the user id. 此函数需要请求对象或用户标识。

I know I could create a new view and call it from javascript from the page, but this seems like a horrible way of doing it. 我知道我可以创建一个新视图并从页面的javascript中调用它,但这似乎是一种可怕的方法。 Is there a way to somehow attach a function to admin page loads server side without adding any additional dependencies? 有没有办法以某种方式将功能附加到管理页面加载服务器端而不添加任何其他依赖项?

Update: the function is used to hook into a kind of logging system that keeps track of first/last interaction of each user each day that needs to be updated whenever the user uses the admin interface. 更新:该功能用于挂接一种日志记录系统,该日志系统跟踪每个用户每天在用户使用管理界面时需要更新的第一次/最后一次交互。 It would seem that a middleware app would allow me to do what I want to do, thank you guys! 中间件应用程序似乎可以让我做我想做的事情,谢谢大家!

Disclaimer: I don't know a terrible lot about the internals or API(s) of Django perse. 免责声明:我对Django perse的内部或API并不了解。

What you need to use/write is a Middleware Component. 您需要使用/编写的是一个中间件组件。

See: Django Middleware 请参阅: Django中间件

Trivial Example: 琐碎的例子:

class LocaleMiddleware(object): LocaleMiddleware类(对象):

def process_request(self, request):

    if 'locale' in request.cookies:
        request.locale = request.cookies.locale
    else:
        request.locale = None

def process_response(self, request, response):

    if getattr(request, 'locale', False):
        response.cookies['locale'] = request.locale

See also: Understanding Django Middleware from Effective Django. 另请参阅:从有效Django 了解Django中间件

One way would be to create a middleware and check on every page request if it is an admin page: 一种方法是创建一个中间件,并检查每个页面请求是否为管理页面:

https://docs.djangoproject.com/en/dev/topics/http/middleware/ https://docs.djangoproject.com/en/dev/topics/http/middleware/

I would deal it with a simple way. 我将以一种简单的方式处理它。 Find a function the admin must execute such as save_model() . 查找管理员必须执行的功能,例如save_model() Then put your own function in it. 然后放入您自己的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM