如何在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代码可以获得什么好处或含义:
class some_class(parent_class):
def doOp(self, x, y):
def add(x, y):
return x + y
return add(x, y)
Run Code Online (Sandbox Code Playgroud)
我在一个开源项目中发现了这一点,在嵌套函数中做了一些有用的事情,但除了调用它之外什么都不做.(实际的代码可以在这里找到.)为什么有人会像这样编码?在嵌套函数中编写代码而不是在外部正常函数中是否有一些好处或副作用?
问题 -
@is_premium_user
def sample_view:
.......
......
Run Code Online (Sandbox Code Playgroud)
我希望某些视图只能访问网站的高级用户.
如何在我的项目中的各种应用程序中使用此装饰器?
我正在尝试(失败)建立一个简单的 FastAPI 项目并使用 uvicorn 运行它。这是我的代码:
from fastapi import FastAPI
app = FastAPI()
app.get('/')
def hello_world():
return{'hello':'world'}
app.get('/abc')
def abc_test():
return{'hello':'abc'}
Run Code Online (Sandbox Code Playgroud)
这是我从终端运行的:
PS C:\Users\admin\Desktop\Self pace study\Python\Dev\day 14> uvicorn server2:app
INFO: Started server process [3808]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: 127.0.0.1:60391 - "GET / HTTP/1.1" 404 Not Found
INFO: 127.0.0.1:60391 - "GET /favicon.ico HTTP/1.1" 404 Not Found
Run Code Online (Sandbox Code Playgroud)
如您所见,我得到了 404 未找到。可能是什么原因?一些与网络相关的东西,可能是防火墙/VPN 阻止此连接或其他什么?我对此很陌生。提前致谢!
我有以下 Python 代码:
#!/usr/bin/python3
import time
class Greeter:
def __init__(self, person):
self.person = person
print("Hello", person);
def __del__(self):
print("Goodbye", self.person);
def inspect(self):
print("I greet", self.person);
if __name__ == '__main__':
to_greet = []
try:
to_greet.append(Greeter("world"));
to_greet.append(Greeter("john"));
to_greet.append(Greeter("joe"));
while 1:
for f in to_greet:
f.inspect()
time.sleep(2)
except KeyboardInterrupt:
while (len(to_greet) > 0):
del to_greet[0]
del to_greet
print("I hope we said goodbye to everybody. This should be the last message.");
Run Code Online (Sandbox Code Playgroud)
当我运行它并Ctrl+C
在睡眠期间,我得到:
Hello world
Hello john
Hello joe
I greet world
I …
Run Code Online (Sandbox Code Playgroud)