相关疑难解决方法(0)

5409
推荐指数
22
解决办法
75万
查看次数

如何制作一系列功能装饰器?

如何在Python中创建两个装饰器来执行以下操作?

@makebold
@makeitalic
def say():
   return "Hello"
Run Code Online (Sandbox Code Playgroud)

...应该返回:

"<b><i>Hello</i></b>"
Run Code Online (Sandbox Code Playgroud)

我不是试图HTML在一个真实的应用程序中这样做 - 只是试图了解装饰器和装饰器链是如何工作的.

python decorator python-decorators

2647
推荐指数
17
解决办法
49万
查看次数

动态创建方法和装饰器,得到错误'functools.partial'对象没有属性'__module__'

我目前正在使用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
Run Code Online (Sandbox Code Playgroud)

我想让它们变得通用.所以我尝试动态添加方法到类.到目前为止我尝试了什么:

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( …
Run Code Online (Sandbox Code Playgroud)

python google-app-engine functools google-cloud-endpoints endpoints-proto-datastore

18
推荐指数
2
解决办法
8256
查看次数

decorate a python class such that most methods raise an exception if condition

我曾遇到过这样的情况:如果某个条件为,则除一个方法外,大多数类的方法都需要引发异常False。可以进入大多数方法并编写if not condition,以便在条件不成立的情况下每个方法都将引发异常,但是我认为可以用类顶部的单个装饰器以某种方式进行此操作。

这个问题是相似的,但是它涉及到分别装饰每个方法,如果我要这样做,那么最好将if语句放入每个方法中。

这是一些代码和注释,以帮助进行交流:

CONDITION = True  # change to False to test

def CheckMethods():
    if CONDITION:
        # run all the methods as usual if they are called
        pass 
    else:
        # raise an exception for any method which is called except 'cow'
        # if 'cow' method is called, run it as usual
        pass


@CheckMethods
class AnimalCalls:
    def dog(self):
        print("woof")
    def cat(self):
        print("miaow")
    def cow(self):
        print("moo")
    def sheep(self)
        print("baa") 

a = AnimalCalls()
a.dog() …
Run Code Online (Sandbox Code Playgroud)

python oop class decorator python-3.x

4
推荐指数
1
解决办法
94
查看次数