简体   繁体   English

如何将命名参数传递给另一个函数需要的函数?

[英]How do you pass a named parameter into a function that another function needs?

EDIT: I've changed the title to better represent the solution I seeking. 编辑:我已更改标题以更好地代表我寻求的解决方案。

I'm repeating a block of code and would like to a write a function to reduce clutter. 我在重复一段代码,并想编写一个函数来减少混乱。 I'm having trouble passing in the kwarg key hourly_id (last line of the original code). 我在传递kwarg键hourly_id (原始代码的最后一行)时遇到了麻烦。

Original Code 原始码

# Create Hourly data.
hourly_data = validated_data.pop('hourly')
hourly_points_data = hourly_data.pop('data')
hourly = Hourly.objects.create(**hourly_data)
for hourly_point_data in hourly_points_data:
    hourly_point = HourlyPoint.objects.create(
        hourly_id=hourly.pk, **hourly_point_data)    <-- This

New Function 新功能

def create_data_block(self, data, block_str, DataBlock, DataPoint, id):
    block_data = data.pop(block_str)
    points_data = block_data.pop('data')
    block = DataBlock.objects.create(**block_data)
    for point_data in points_data:
        point = DataPoint.objects.create(
            id=block.pk, **point_data)    <-- This 

Function Call 函数调用

self.create_data_block(validated_data, 'hourly', Hourly, HourlyPoint, 'hourly_id')

So you can see here I am trying to pass hourly_id as id using a string, but I get a database error saying that that hourly_id was missing so I'm clearly not passing it in correctly. 因此,您可以在这里看到我正在尝试使用字符串将hourly_id作为id传递,但是我收到一个数据库错误,指出该hourly_id丢失了,所以我显然没有正确地传递它。

Traceback 追溯

Traceback (most recent call last):
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner
    response = get_response(request)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/lib/python3.5/contextlib.py", line 30, in inner
    return func(*args, **kwds)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/rest_framework/views.py", line 489, in dispatch
    response = self.handle_exception(exc)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/rest_framework/views.py", line 449, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/rest_framework/views.py", line 486, in dispatch
    response = handler(request, *args, **kwargs)
  File "/home/cudb/Projects/a/b/c/weather/views.py", line 36, in get
    response = self.get_entry(latitude, longitude)
  File "/home/cudb/Projects/a/b/c/weather/views.py", line 59, in get_entry
    response = self.create_or_update_entry(latitude, longitude)
  File "/home/cudb/Projects/a/b/c/weather/views.py", line 76, in create_or_update_entry
    location_serializer.save()
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/rest_framework/serializers.py", line 215, in save
    self.instance = self.create(validated_data)
  File "/home/cudb/Projects/a/b/c/weather/serializers.py", line 119, in create
    validated_data, 'hourly', Hourly, HourlyPoint, 'hourly_id')
  File "/home/cudb/Projects/a/b/c/weather/serializers.py", line 169, in create_data_block
    id=block.pk, **point_data)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/models/query.py", line 399, in create
    obj.save(force_insert=True, using=self.db)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/models/base.py", line 796, in save
    force_update=force_update, update_fields=update_fields)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/models/base.py", line 824, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/models/base.py", line 908, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/models/base.py", line 947, in _do_insert
    using=using, raw=raw)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/models/query.py", line 1045, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 1054, in execute_sql
    cursor.execute(sql, params)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/debug_toolbar/panels/sql/tracking.py", line 164, in execute
    return self._record(self.cursor.execute, sql, params)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/debug_toolbar/panels/sql/tracking.py", line 106, in _record
    return method(sql, params)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/home/cudb/.virtualenvs/otto/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: null value in column "hourly_id" violates not-null constraint
DETAIL:  Failing row contains (6, 76.22, 77.31, 0.80, 0.00, clear-night, Clear, null).

[04/Aug/2017 12:05:30] "GET /weather/0,4 HTTP/1.1" 500 288106

This where I see a problem: 这是我看到的问题:

hourly_point = HourlyPoint.objects.create(hourly_id=hourly.pk, **hourly_point_data)
point = DataPoint.objects.create(id=block.pk, **point_data)

You can rename the variables to be more generic as you see fit, but hourly_id is not a variable, it's a named parameter. 您可以根据需要将变量重命名为更通用的名称,但是hourly_id不是变量,而是命名参数。 By using id instead, you're not passing in the expected hourly_id argument but passing in a potentially unwanted, or incorrect, id argument. 通过使用id ,您不会传递期望的hourly_id参数,而是传递了可能不需要或不正确的id参数。

Unless you change the definition of create() itself, the argument name remains hourly_id . 除非您更改create()本身的定义,否则参数名称仍为hourly_id One way around this is to use the argument positionally, if possible, instead of by name. 解决此问题的一种方法是,尽可能在位置上使用参数,而不要按名称使用。 (Ie is it a keyword argument only or a positional argument being accessed by keyword?) (即是仅使用关键字参数还是使用关键字访问位置参数?)

Alternatively, if you pass in 'hourly_id' as id then augment point_data with this key and value: 另外,如果您将'hourly_id'作为id传递,则使用以下键和值增加point_data

def create_data_block(self, data, block_str, DataBlock, DataPoint, id):
    block_data = data.pop(block_str)
    points_data = block_data.pop('data')
    block = DataBlock.objects.create(**block_data)
    for point_data in points_data:
        point = DataPoint.objects.create(**{id: block.pk, **point_data})

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

相关问题 如何将输入作为参数传递给python中的另一个函数? 不是 - How do you pass input as parameter to another function in python? It doesn't 如何将参数从一个函数传递给另一个函数? - How do you pass arguments from one function to another? 如果需要第一个功能,如何在脚本中执行第二个功能? - How do you execute the second function in a script if it needs the first function? 如何在函数中使用函数作为参数? - How do you use a function as a parameter in a function? 如何将参数列表传递给Python中的另一个函数? - How to pass a parameter list to another function in Python? 如何将函数的参数转换为字符串 - how do you make a parameter of a function into a string 将return作为参数传递给另一个函数 - Pass return as parameter for another function 如何在另一个函数中将Python pandas函数作为变量/参数传递? - How to pass a Python pandas function as a variable/parameter in another function? 如何将带有参数的 function 作为参数传递给 Python 中的另一个 function? - How pass a function with parameters as a parameter to another function in Python? 您如何为 function 编写名为 makeWordLengthDict 的程序,该程序将单词列表作为其唯一参数,并在 python 中返回字典 - how do you write a program for function named makeWordLengthDict which takes a LIST of words as its only parameter, and returns a dictionary in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM