Skip to main content
 首页 » 编程设计

python-crontab 在 django 请求中请求特权用户

2024年12月31日18TianFang

我正在尝试使 crontab 自动接收请求并从 django 创建作业,但出现以下错误:

    Traceback: 
 
File "/var/www/venv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 
  34.             response = get_response(request) 
 
File "/var/www/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 
  126.                 response = self.process_exception_by_middleware(e, request) 
 
File "/var/www/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 
  124.                 response = wrapped_callback(request, *callback_args, **callback_kwargs) 
 
File "/var/www/venv/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view 
  54.         return view_func(*args, **kwargs) 
 
File "/var/www/myweb/apps/general/views.py" in create_cronjob_json 
  779.     return create_cronjob(request) 
 
File "/var/www/myweb/apps/utilities/daemons_planner.py" in create_cronjob 
  12.     cron = CronTab(user="pedro") 
 
File "/var/www/venv/lib/python3.6/site-packages/crontab.py" in __init__ 
  227.         self.read(tabfile) 
 
File "/var/www/venv/lib/python3.6/site-packages/crontab.py" in read 
  288.                 raise IOError("Read crontab %s: %s" % (self.user, err)) 
 
Exception Type: OSError at /create-cronjob-json/ 
Exception Value: Read crontab pedro: b'must be privileged to use -u\n' 

我正在使用 python-crontab

这是我的代码:

def create_cronjob(request): 
    received_json_data = json.loads(request.body) 
    cron = CronTab(user="pedro") 
    comment = received_json_data['name'] 
    command = received_json_data['command']  
    band = True 
    for job in cron: 
        if job.comment == comment: 
            band = False 
    if band: 
        job = cron.new(command=command, comment=comment) 
        job.setall(received_json_data['cron']) 
 
    cron.write() 
    response_data = {} 
    response_data["success"] = True 
    return JsonResponse(response_data) 

可能是什么问题?我该如何解决这个问题?

请您参考如下方法:

您可以尝试使用:

CronTab(user=True)