序列化用户实例以用于其他功能

时间:2019-05-25 18:36:00

标签: python django

我试图将User实例传递给其他函数,但无法实现。 User实例不可JSON可序列化,因此我在Google上进行了一些搜索,发现可以在Django中使用内置的序列化程序。但是我仍然无法使其正常工作。

观看次数1:

from django.core import serializers
userdata = request.user
serialized_obj = serializers.serialize('json', userdata)
SubtaskUpdate("2464c7ca-7f14-11e9-b4c2-b870aca6d744", serialized_obj)

观看次数2:

def SubtaskUpdate(taskid, user):
    base_dir = settings.BASE_DIR
    uniquefolder = os.path.join(base_dir, 'var/taskqueries').replace("\\", "/")
    os.chdir(uniquefolder)
    logfilnavn = str(uuid.uuid4()) # Variabel til filnavn
    logfile = open(logfilnavn, 'w') # Åbner fil med navn fra forrige variabel
    proc=subprocess.Popen(['golemcli', '--mainnet', "tasks", 'subtasks', taskid, "--json"], universal_newlines=True, stdout=logfile, stderr=logfile)
    proc.wait()
    logfile.close()
    taskre = Task(TaskID=taskid, User=user)
    taskre.save()
    with open(logfilnavn) as json_file:
        print(json_file) 
        json_object = json.load(json_file)
        for node in json_object['values']:
            Node = node[0]
            ID = node[1]
            Time = node[2]
            Status = node[3]
            h = NodesData.objects.get(Node=Node)
            a = Subtask(SubtaskID=ID, Country=h.NodeCountry, City=h.NodeCity, Cores=h.Node_Cores, Disk=h.Node_Disk, Memory=h.Node_Memory, OS=h.Node_OS,  SubtaskNode=Node, SubtaskStatus=Status, Task=taskre)
            a.save()
    os.remove(logfilnavn)

型号:

class Task(models.Model):
    TaskID = models.CharField(max_length=128)
    User = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,)



class Subtask(models.Model):
    SubtaskID = models.CharField(max_length=128, default="Awaiting Query")
    SubtaskNode = models.CharField(max_length=24, default="Awaiting Query")
    SubtaskStatus = models.CharField(max_length=15, default="Awaiting Query")
    Country = models.CharField(max_length=25, default="Awaiting Query")
    City = models.CharField(max_length=25, default="Awaiting Query")
    OS = models.CharField(max_length=15, default="Awaiting Query")
    Cores = models.CharField(max_length=15, default="Awaiting Query")
    Memory = models.CharField(max_length=15, default="Awaiting Query")
    Disk = models.CharField(max_length=15, default="Awaiting Query")
    SubtaskStatus = models.CharField(max_length=15, default="Awaiting Query")
    Task = models.ForeignKey(Task, on_delete=models.CASCADE)

跟踪:

> Internal Server Error: /faq Traceback (most recent call last):   File
> "/home/django/copypaste/cleanup/lib/python3.6/site-packages/django/core/handlers/exception.py",
> line 34, in inner
>     response = get_response(request)   File "/home/django/copypaste/cleanup/lib/python3.6/site-packages/django/core/handlers/base.py",
> line 126, in _get_response
>     response = self.process_exception_by_middleware(e, request)   File "/home/django/copypaste/cleanup/lib/python3.6/site-packages/django/core/handlers/base.py",
> line 124, in _get_response
>     response = wrapped_callback(request, *callback_args, **callback_kwargs)   File "./faq/views.py", line 11, in index
>     serialized_obj = serializers.serialize('json', userdata)   File "/home/django/copypaste/cleanup/lib/python3.6/site-packages/django/core/serializers/__init__.py",
> line 128, in serialize
>     s.serialize(queryset, **options)   File "/home/django/copypaste/cleanup/lib/python3.6/site-packages/django/core/serializers/base.py",
> line 87, in serialize
>     for count, obj in enumerate(queryset, start=1):   File "/home/django/copypaste/cleanup/lib/python3.6/site-packages/django/utils/functional.py",
> line 214, in inner
>     return func(self._wrapped, *args) TypeError: 'User' object is not iterable Not Found: /favicon.ico

修改 代码追溯:

from django.shortcuts import render
from .models import stats
from backgroundtasks.models import NodesData
from backgroundtasks.tasks import SubtaskUpdate
from callgolem.models import Task, Subtask
from django.core import serializers
import json


def index(request):
    SubtaskUpdate("2464c7ca-7f14-11e9-b4c2-b870aca6d744", request.user)
    data = stats.objects.get(id=1)
    mapdb = NodesData.objects.all()
    return render(request, 'faq.html', {'data':data, 'mapdb':mapdb}) 

Traceback (most recent call last):
   File "/home/django/copypaste/cleanup/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
   File "/home/django/copypaste/cleanup/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
    response = self.process_exception_by_middleware(e, request)
   File "/home/django/copypaste/cleanup/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
   File "./faq/views.py", line 10, in index
    SubtaskUpdate("2464c7ca-7f14-11e9-b4c2-b870aca6d744", request.user)
   File "/home/django/copypaste/cleanup/lib/python3.6/site-packages/background_task/tasks.py", line 296, in __call__
    remove_existing_tasks)
   File "/home/django/copypaste/cleanup/lib/python3.6/site-packages/background_task/tasks.py", line 223, in schedule
    repeat_until, remove_existing_tasks)
   File "/home/django/copypaste/cleanup/lib/python3.6/site-packages/background_task/models.py", line 91, in new_task
    task_params = json.dumps((args, kwargs), sort_keys=True)
   File "/usr/lib/python3.6/json/__init__.py", line 238, in dumps
    **kw).encode(obj)
   File "/usr/lib/python3.6/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
   File "/usr/lib/python3.6/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
   File "/usr/lib/python3.6/json/encoder.py", line 180, in default
    o.__class__.__name__) TypeError: Object of type 'User' is not JSON serializable
Not Found: /favicon.ico

1 个答案:

答案 0 :(得分:1)

将参数传递给后台任务时,应避免传递模型实例。而是传递ID并在任务本身中获取实例。

SubtaskUpdate('<uuid>',  request.user.id)

...

def SubtaskUpdate(taskid, user_id):
    user = User.objects.get(id=user_id)