Cant pickle : attribute lookup builtin.function failed

2024/9/8 10:46:34

I'm getting the error below, the error only happens when I add delay to process_upload function, otherwise it works without a problem.

Could someone explain what this error is, why its happening and any recommendations to resolve?

Error:

PicklingError at /contacts/upload/configurator/47/Can't pickle <type 'function'>: attribute lookup __builtin__.function failed

This is the view

 if request.method == 'POST':form = ConfiguratorForm(data=request.POST)# Send import to task.process_upload.delay(upload_id=upload.id, form=form)

This is the task

@task
def process_upload(upload_id, form):upload = Upload.objects.get(id=upload_id)upload.process(form=form)

Upload.process is within my model:

 def process(self, form):self.date_start_processing = timezone.now()import_this(data=self.filepath, extra_fields=[{'value': self.group_id, 'position': 5},{'value': self.uploaded_by.id, 'position': 6}], form=form)

Full trace:

Traceback:
File "/Users/user/Documents/workspace/sms/django-env/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response115.                         response = callback(request, *callback_args, **callback_kwargs)
File "/Users/user/Documents/workspace/sms/django-env/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view25.                 return view_func(request, *args, **kwargs)
File "/Users/user/Documents/workspace/sms/contacts/views.py" in upload_configurator118.         process_upload.delay(upload_id=upload.id, form=form)
File "/Users/user/Documents/workspace/sms/django-env/lib/python2.7/site-packages/celery/app/task.py" in delay357.         return self.apply_async(args, kwargs)
File "/Users/user/Documents/workspace/sms/django-env/lib/python2.7/site-packages/celery/app/task.py" in apply_async472.                                      **options)
File "/Users/user/Documents/workspace/sms/django-env/lib/python2.7/site-packages/celery/app/amqp.py" in publish_task249.             **kwargs
File "/Users/user/Documents/workspace/sms/django-env/lib/python2.7/site-packages/kombu/messaging.py" in publish157.             compression, headers)
File "/Users/user/Documents/workspace/sms/django-env/lib/python2.7/site-packages/kombu/messaging.py" in _prepare233.              body) = encode(body, serializer=serializer)
File "/Users/user/Documents/workspace/sms/django-env/lib/python2.7/site-packages/kombu/serialization.py" in encode161.         payload = encoder(data)
File "/Users/user/Documents/workspace/sms/django-env/lib/python2.7/site-packages/kombu/serialization.py" in dumps340.         return dumper(obj, protocol=pickle_protocol)Exception Type: PicklingError at /contacts/upload/configurator/47/
Exception Value: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed

forms.py

COL_CHOICES = [('N/A', 'No Import'),('first_name', 'First Name'),('last_name', 'Last Name'),('company', 'Company'),('mobile', 'Mobile Number'),('email', 'Email Address'),]class ConfiguratorForm(forms.Form):col1 = forms.TypedChoiceField(choices=COL_CHOICES, initial='first_name')col2 = forms.TypedChoiceField(choices=COL_CHOICES, initial='first_name')col3 = forms.TypedChoiceField(choices=COL_CHOICES, initial='first_name')col4 = forms.TypedChoiceField(choices=COL_CHOICES, initial='first_name')
Answer

You don't provide your ConfiguratorForm's definition but anyway: async execution requires that your task's arguments are pickable, and obviously your form is not. You could possibly go the hard way and make it pickable but that's just a waste of time. The simple solution is don't pass the form, only pass the form's data (iow: request.POST.copy() but I'm not sure Querydict are pickable) - or better, first validate the form and only pass the form's cleaned_data, as there's no point in processing an invalid form.

https://en.xdnf.cn/q/72572.html

Related Q&A

Pandas Merge two DataFrames without some columns

ContextIm trying to merge two big CSV files together.ProblemLets say Ive one Pandas DataFrame like the following...EntityNum foo ... ------------------------ 1001.01 100 1002.02 50 1003…

Getting Youtube data using Python

Im trying to learn how to analyze social media data available on the web and Im starting with Youtube.from apiclient.errors import HttpError from outh2client.tools import argparser from apiclient.disco…

matplotlib does not show legend in scatter plot

I am trying to work on a clustering problem for which I need to plot a scatter plot for my clusters.%matplotlib inline import matplotlib.pyplot as plt df = pd.merge(dataframe,actual_cluster) plt.scatte…

Correct usage of asyncio.Conditions wait_for() method

Im writing a project using Pythons asyncio module, and Id like to synchronize my tasks using its synchronization primitives. However, it doesnt seem to behave as Id expect.From the documentation, it se…

displaying newlines in the help message when using pythons optparse

Im using the optparse module for option/argument parsing. For backwards compatibility reasons, I cant use the argparse module. How can I format my epilog message so that newlines are preserved?In th…

How to use a learnable parameter in pytorch, constrained between 0 and 1?

I want to use a learnable parameter that only takes values between 0 and 1. How can I do this in pytorch? Currently I am using: self.beta = Parameter(torch.Tensor(1)) #initialize zeros(self.beta)But I…

generating a CSV file online on Google App Engine

I am using Google App Engine (python), I want my users to be able to download a CSV file generated using some data from the datastore (but I dont want them to download the whole thing, as I re-order th…

Python equivalence of Rs match() for indexing

So i essentially want to implement the equivalent of Rs match() function in Python, using Pandas dataframes - without using a for-loop. In R match() returns a vector of the positions of (first) matches…

Why doesnt Pydantic validate field assignments?

I want to use Pydantic to validate fields in my object, but it seems like validation only happens when I create an instance, but not when I later modify fields. from pydantic import BaseModel, validato…

Format OCR text annotation from Cloud Vision API in Python

I am using the Google Cloud Vision API for Python on a small program Im using. The function is working and I get the OCR results, but I need to format these before being able to work with them.This is …