python – 如何使用装饰器(bottle.py)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 如何使用装饰器(bottle.py),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含4861字,纯文字阅读大概需要7分钟。
内容图文
![python – 如何使用装饰器(bottle.py)](/upload/InfoBanner/zyjiaocheng/757/420882350ca24dc98cb058b6c122a5f2.jpg)
我正在尝试使用bottle.py来构建一些网页.似乎使用瓶子的一个主要部分是学习使用装饰器,但我已经阅读了python docs解释装饰器是什么,但我仍然不确定我理解它们.
文档说:
“Python装饰器是对Python语法的一种特定更改,它允许我们更方便地更改函数和方法(以及未来版本中可能的类).”
听起来你正在调用一个函数进行一些更改,但我不知道为什么你会这样做或如何阅读装饰器.
看一些瓶子代码:
if __name__ == '__main__':
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static').replace('\\', '/')
HOST = os.environ.get('SERVER_HOST', 'localhost')
try:
PORT = int(os.environ.get('SERVER_PORT', '5555'))
except ValueError:
PORT = 5555
@bottle.route('/static/<filepath:path>')
def server_static(filepath):
"""Handler for static files, used with the development server.
When running under a production server such as IIS or Apache,
the server should be configured to serve the static files."""
return bottle.static_file(filepath, root=STATIC_ROOT)
# Starts a local test server.
bottle.run(server='wsgiref', host=HOST, port=PORT)
这行是做什么的@ bottle.route(‘/ static /< filepath:path>‘)?
如果它是一个奇特的函数调用那么为什么这样做而不是只是调用函数?
谢谢你的帮助! :d
解决方法:
看看这段代码:
def my_decorator(func):
return lambda: print("goodbye")
def greet():
print('hello')
result = my_decorator(greet)
result()
--output:--
goodbye
以下是完成同样事情的快捷方式:
def my_decorator(func):
return lambda: print("goodbye")
@my_decorator
def greet():
print('hello')
greet()
--output:--
goodbye
@my_decorator语法接受它下面的函数,问候并进行此调用:
greet = my_decorator(greet)
必须定义my_decorator()函数,以便:
>它需要一个函数作为参数.
>返回一个函数.
A Python decorator is a specific change to the Python syntax that
allows us to more conveniently alter functions and methods (and
possibly classes in a future version).
好吧,那么让我们说你要添加到greet()函数的任何内容:
def my_decorator(func): # func = greet
def add_to_greet():
func() #<*********This is greet()
print('world') #<***This is additional stuff.
return add_to_greet
@my_decorator
def greet():
print('hello')
greet()
--output:--
hello
world
What does this line do
@bottle.route('/static/<filepath:path>')
好的,你准备好了吗?如果@some_name语法指定了参数,例如:
@wrapper('world')
def do_stuff():
第一个python将执行以下调用:
@wrapper('world')
def do_stuff():
...
#****HERE:
decorator = wrapper('world') #decorator is a newly created variable
wrapper()函数必须定义为:
>采取任何旧的论点,例如’世界’
>返回一个函数:
>将函数作为参数.
>返回一个函数.
其次,python将执行调用:
@wrapper('world')
def do_stuff():
...
decorator = wrapper('world')
#*****HERE:
do_stuff = decorator(do_stuff)
呼!这是一个例子:
def wrapper(extra_greeting):
def my_decorator(func):
def add_to_greet():
func()
print(extra_greeting)
return add_to_greet
return my_decorator
@wrapper('world')
def greet():
print('hello')
greet()
--output:--
hello
world
现在,让我们分析一下这个装饰器:
@bottle.route('/static/<filepath:path>')
def server_static(filepath):
bottle -- a module
route -- a function(or other callable) defined in the bottle module
'/static/<filepath:path>' -- a route
所以瓶子模块可能如下所示:
#bottle.py
def route(your_route): #your_route <= '/static/<filepath:path>'
def my_decorator(func): #The decorator syntax will cause python to call this function with server_static as the argument
def do_stuff(filepath):
func(filepath) #Call the server_static() function with the part of the url that matched filepath
return do_stuff #This function will be called when your code calls server_static(...)
return my_decorator
If its a fancy function call then why do it this way rather than just
calling the function?
先进的东西.
评论:也许您忘了解释路由装饰器的具体用途?
060011
The route() decorator binds a piece of code to an URL path. In this
case, we link the /hello path to the hello() function. This is called
a route (hence the decorator name) and is the most important concept
of this framework. You can define as many routes as you want. Whenever
a browser requests a URL, the associated function is called and the
return value is sent back to the browser. It’s as simple as that.
http://bottlepy.org/docs/dev/tutorial.html
路径可以包括通配符:
The simplest form of a wildcard consists of a name enclosed in angle
brackets (e.g.<name>
)….Each wildcard matches one or more
characters, but stops at the first slash (/).
The rule/<action>/<item>
matches as follows:
Path Result
/save/123 {'action': 'save', 'item': '123'}
/save/123/ No Match
/save/ No Match
//123 No Match
Filters are used to define more specific wildcards, and/or transform
the matched part of the URL before it is passed to the callback. A
filtered wildcard is declared as<name:filter>
The following standard filters are implemented:
:path matches all characters including the slash character in a non-greedy way and may be used to match more than one path
segment.
http://bottlepy.org/docs/dev/routing.html
内容总结
以上是互联网集市为您收集整理的python – 如何使用装饰器(bottle.py)全部内容,希望文章能够帮你解决python – 如何使用装饰器(bottle.py)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。