21

我目前正在使用 EndpointsModel 为我在 AppEngine 上的所有模型创建一个 RESTful API。由于它是 RESTful,这些 api 有很多我想避免的重复代码。

例如:

class Reducer(EndpointsModel):
    name = ndb.StringProperty(indexed=False)

@endpoints.api(
    name="bigdata",
    version="v1",
    description="""The BigData API""",
    allowed_client_ids=ALLOWED_CLIENT_IDS,
)
class BigDataApi(remote.Service):
    @Reducer.method(
        path="reducer",
        http_method="POST",
        name="reducer.insert",
        user_required=True,
    )
    def ReducerInsert(self, obj):
        pass

    ## and GET, POST, PUT, DELETE
    ## REPEATED for each model

我想让它们变得通用。所以我尝试向类动态添加方法。到目前为止我已经尝试过:

from functools import partial, wraps

def GenericInsert(self, obj, cls):
    obj.owner = endpoints.get_current_user()
    obj.put()
    return obj

# Ignore GenericDelete, GenericGet, GenericUpdate ...

import types
from functools import partial

def register_rest_api(api_server, endpoint_cls):
    name = endpoint_cls.__name__

    # create list method 
    query_method = types.MethodType(
    endpoint_cls.query_method(
        query_fields=('limit', 'pageToken'),
        path="%ss" % name,
        http_method="GET",
        name="%s.list" % name,
        user_required=True
    )(partial(GenericList, cls=endpoint_cls)))

    setattr(api_server, "%sList", query_method)

    # create insert method
    # ...

register_rest_api(BigDataApi, Reducer)

但我明白了,我认为这是因为's 装饰器和部分装饰器'functools.partial' object has no attribute '__module__' exception. 之间存在一些冲突。endpoints.method但不知道如何避免它。

Traceback (most recent call last):
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 239, in Handle
    handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 298, in _LoadHandler
    handler, path, err = LoadObject(self._handler)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 84, in LoadObject
    obj = __import__(path[0])
  File "/Users/Sylvia/gcdc2013/apis.py", line 795, in <module>
    register_rest_api(BigDataApi, Reducer)
  File "/Users/Sylvia/gcdc2013/apis.py", line 788, in register_rest_api
    )(partial(GenericList, cls=endpoint_cls)))
  File "/Users/Sylvia/gcdc2013/endpoints_proto_datastore/ndb/model.py", line 1544, in RequestToQueryDecorator
    @functools.wraps(api_method)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/functools.py", line 33, in update_wrapper
    setattr(wrapper, attr, getattr(wrapped, attr))
AttributeError: 'functools.partial' object has no attribute '__module__'

相关文章:

4

7 回答 7

12

我也偶然发现了这一点,我真的很惊讶,对我来说,问题是部分对象缺少某些属性,特别__module____name__

由于wraps默认情况下用于functools.WRAPPER_ASSIGNMENTS更新属性,('__module__', '__name__', '__doc__')无论如何默认在 python 2.7.6 中,有几种方法可以处理这个......

仅更新当前属性...

import functools
import itertools

def wraps_safely(obj, attr_names=functools.WRAPPER_ASSIGNMENTS):
    return wraps(obj, assigned=itertools.ifilter(functools.partial(hasattr, obj), attr_names))

>>> def foo():
...     """ Ubiquitous foo function ...."""
... 
>>> functools.wraps(partial(foo))(foo)()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/functools.py", line 33, in update_wrapper
setattr(wrapper, attr, getattr(wrapped, attr))
AttributeError: 'functools.partial' object has no attribute '__module__'
>>> wraps_safely(partial(foo))(foo)()
>>> 

在这里,我们只是过滤掉所有不存在的属性。

另一种方法是仅严格处理部分对象,您可以折叠wrapssingledispatch创建包装的部分对象,其属性将从最深 func的属性中获取。

类似的东西:

import functools

def wraps_partial(wrapper, *args, **kwargs):
    """ Creates a callable object whose attributes will be set from the partials nested func attribute ..."""
    wrapper = wrapper.func
    while isinstance(wrapper, functools.partial):
        wrapper = wrapper.func
    return functools.wraps(wrapper, *args, **kwargs)

def foo():
    """ Foo function.
    :return: None """
    pass

>>> wraps_partial(partial(partial(foo)))(lambda : None).__doc__
' Foo Function, returns None '
>>> wraps_partial(partial(partial(foo)))(lambda : None).__name__
'foo'
>>> wraps_partial(partial(partial(foo)))(lambda : None)()
>>> pfoo = partial(partial(foo))
>>> @wraps_partial(pfoo)
... def not_foo():
...     """ Not Foo function ... """
... 
>>> not_foo.__doc__
' Foo Function, returns None '
>>> not_foo.__name__
'foo'
>>>

这稍微好一点,因为现在我们可以获得原始函数文档,之前默认使用部分对象文档字符串。

这可以修改为仅在当前部分对象还没有 set 属性时进行搜索,嵌套许多部分对象时应该会稍微快一些...

更新

似乎python(CPython)3(至少3.4.3)没有这个问题,因为我不知道也不应该假设所有版本的python 3或其他实现(如Jython)也有这个问题在这里是另一个面向未来的方法

from functools import wraps, partial, WRAPPER_ASSIGNMENTS

try:
    wraps(partial(wraps))(wraps)
except AttributeError:
    @wraps(wraps)
    def wraps(obj, attr_names=WRAPPER_ASSIGNMENTS, wraps=wraps):
        return wraps(obj, assigned=(name for name in attr_names if hasattr(obj, name))) 

有几点需要注意:

  • 仅当我们未能包装 partial时,我们才定义一个新wraps函数,以防 python2 或其他版本的未来版本解决此问题。
  • 我们使用原件wraps来复制文档和其他信息
  • 我们不使用ifilter它,因为它在 python3 中被删除,我有和没有ifilter时间,但结果不确定,至少在 python (CPython) 2.7.6 中,两者的差异充其量是微不足道的......
于 2015-02-26T20:22:15.327 回答
7

在 Python 3.5 中,我发现在partial. 您可以通过以下方式访问它.func

from functools import partial

def a(b):
    print(b)


In[20]:  c=partial(a,5)

In[21]:  c.func.__module__
Out[21]: '__main__'

In[22]:  c.func.__name__
Out[22]: 'a'
于 2017-05-22T08:51:20.513 回答
2

如果它是由 functools 中的“wraps”问题引起的,那么没有什么能阻止您编写自己的不调用 wraps 的部分。根据 python 文档,这是部分的有效实现:

def partial(func, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = keywords.copy()
        newkeywords.update(fkeywords)
        return func(*(args + fargs), **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc
于 2014-07-22T20:48:27.647 回答
1

我偶然发现了这一点,并认为会提到我的解决方法。

正如@samy-vilar 正确提到的那样,python3 没有这个问题。我有一些使用 functools.wrap 的代码,需要在 python2 和 python3 上运行。

对于 python2,我们使用functools32,它是 python3 的用于 python2 的 functools 的反向移植。wraps这个包的实施很完美。此外,它还提供了 lru_cache,它仅在 python3 functools 中可用。

import sys 

if sys.version[0] == '2':
   from functools32 import wraps
else:
   from functools import wraps
于 2016-01-13T07:14:38.123 回答
0

这里描述了一个非常方便的 python 2.7 解决方案 http : //louistiao.me/posts/adding-name-and-doc-attributes-to-functoolspartial-objects/

即:

from functools import partial, update_wrapper

def wrapped_partial(func, *args, **kwargs):
    partial_func = partial(func, *args, **kwargs)
    update_wrapper(partial_func, func)

    return partial_func
于 2019-09-17T15:14:37.617 回答
0

在我们的例子中,我通过子类化 functools.partial 解决了这个问题:

class WrappablePartial(functools.partial):

    @property
    def __module__(self):
        return self.func.__module__

    @property
    def __name__(self):
        return "functools.partial({}, *{}, **{})".format(
            self.func.__name__,
            self.args,
            self.keywords
        )

    @property
    def __doc__(self):
        return self.func.__doc__

注意,您也可以使用 __getattr__ 来重定向查询,但我认为这实际上不太可读(并且像使用 __name__ 那样插入任何有用的元数据变得更加困难)

于 2015-10-16T14:37:05.200 回答
-2

这个问题自 Python 2.7.11 起已修复(不确定它是在哪个特定版本中修复的)。您可以在 2.7.11 中functools.wraps对对象执行操作。functools.partial

于 2016-08-29T23:20:56.433 回答