ValueError: элемент # 0 последовательности обновления словаря имеет длину 25; 2 требуется при распаковке кортежа со словарем - PullRequest
0 голосов
/ 27 мая 2020

Я получаю следующую ошибку при распаковке этого словаря при ссылке из метода generate_pdf, который теперь при назначении этому методу как conext = self.get_context (self) <--- возвращает кортеж, а не словарь? почему </strong> и как я могу получить ключ и значение , которые находятся в словаре в функции / методе в generate_pdf, и чтобы я мог использовать их в объекте EmailMessage. Ниже используется функция, которая заполняет контекст

    def get_context(self, state=None):
        utility= ...
        customer= ...
        context = snoop.pp("get_context dict", {
            'document': self,
            'utility': utility,
            'utility_email': self.utility.email,
            'customer': self.customer,
            'customer_first_name': self.customer.customer_first_name,
            'customer_last_name': self.customer.customer_last_name,
            'customer_email': self.customer.customer_email,
            'docs': self._docs,
            'state': state
        })

Он возвращает dict, теперь я называю его или ссылаюсь на него как context = self.get_context(state), здесь я хочу распаковать, чтобы получить значение customer_email и отправить электронное письмо, но я продолжаю получать

  def generate_pdf(self, state=None, upload=True):
       # !!! ensure this is not called concurrently for the same document

       context = self.get_context(state)
       snoop.pp(type(context))
       for f,d  in enumerate(context):
           f, d
           snoop.pp(print(f,d))
       document, utility, utility_email, customer, customer_first_name,customer_last_name, customer_email, docs, state = context
       snoop.pp("customer_email ", customer_email)
       snoop.pp(context)
       context_dict = dict(context)
       for key, value in context_dict.items():
           snoop.pp('Value', value)
       snoop.pp("Done")
       snoop.pp("Get Customer Email From Context ", context.customer_email)


       object = self.pdf.generate(template=self.get_template(state),
                                           context=context,
                                           upload=upload)

       return object

ниже - трассировка стека и вывод

 10:43:36.69 ....                                              {
10:43:36.69          'document': self,
10:43:36.69          'utility': utility,
10:43:36.69          'utility_email': self.utility.email,
10:43:36.69          'customer': self.customer,
10:43:36.69          'customer_first_name': self.customer.customer_first_name,
10:43:36.69          'customer_last_name': self.customer.customer_last_name,
10:43:36.69          'customer_email': self.customer.customer_email,
10:43:36.69          'docs': self._docs,
10:43:36.69          'state': state
10:43:36.69      } = {'customer': <Customer: Lauren Williams zporter@hicks.com>,
10:43:36.69           'customer_email': 'zporter@hicks.com',
10:43:36.69           'customer_first_name': 'Lauren',
10:43:36.69           'customer_last_name': 'Williams',
10:43:36.69           'docs': <generator object Billing._docs at 0x7fed12e1b8d0>,
10:43:36.69           'document': <Invoice: InvoiceSeries-1 Keller-Cooley  Lauren Williams zporter@hicks.com => None [175452.23 KES]>,
10:43:36.69           'state': 'paid',
10:43:36.69           'utility': <Utility: Edward Irwin>,
10:43:36.69           'utility_email': 'sparksnathan@dyer.biz'}
10:43:36.69 LOG:
10:43:36.73 .... type(context) = <class 'tuple'>
0 get_template_context dict
10:43:36.73 LOG:
10:43:36.76 .... print(f,d) = None
1 {'document': <Invoice: InvoiceSeries-1 Keller-Cooley  Lauren Williams zporter@hicks.com => None [175452.23 KES]>, 'utility': <Utility: Edward Irwin>, 'utility_email': 'sparksnathan@dyer.biz', 'customer': <Customer: Lauren Williams zporter@hicks.com>, 'customer_first_name': 'Lauren', 'customer_last_name': 'Williams', 'customer_email': 'zporter@hicks.com', 'docs': <generator object Billing._docs at 0x7fed12e1b8d0>, 'state': 'paid'}
10:43:36.76 LOG:
10:43:36.77 .... print(f,d) = None
Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv
    self.execute(*args, **cmd_options)
  File "lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute
    output = self.handle(*args, **options)
  File "generate_pdfs.py", line 37, in handle
    snoop.pp('snooping ', document.generate_pdf())
  File "models.py", line 517, in generate_pdf
    document, utility, utility_email, customer, customer_first_name,customer_last_name, customer_email, docs, state = context
ValueError: not enough values to unpack (expected 9, got 2)

1 Ответ

1 голос
/ 27 мая 2020

Вы не можете распаковать словарь так:

document, utility, utility_email, customer, customer_first_name,customer_last_name, customer_email, docs, state = context

Более того, context - это 2-кортеж. Вы можете сделать это:

context_number, context_dict = context

А затем использовать context_dict в качестве словаря, например

snoop.pp("customer_email ", context_dict["customer_email"])
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...