は、ここに私のプラグインのバージョンを簡略化されています:Bottleの各リクエストでカスタムリクエスト属性をリセットするにはどうすればよいですか?
class MyPlugin(object):
''' My plugin.
'''
api = 2
def __init__(self):
self.time = datetime.now()
def apply(self, callback, route):
request.my_attr = self.time
@wraps(callback)
def wrapper(*args, **kwargs):
cb_response = callback(*args, **kwargs)
return cb_response
# Forget any cached values.
route.reset()
# Replace the route callback with the wrapped one.
return wrapper
my_plugin = MyPlugin()
@route('/my_route', method=['GET', 'POST'], apply=[my_plugin])
def my_route():
""" Http Handler.
"""
response.content_type = 'text/txt;'
time = request.my_attr
print(time)
run(host=HOST, port=PORT, debug=DEBUG, quiet=QUIET)
それは、最初の要求で動作しますが、それ以降のすべての要求に失敗します。
# ./my_app.py
Bottle v0.12.9 server starting up (using WSGIRefServer())...
Listening on http://0.0.0.0:8888/
Hit Ctrl-C to quit.
2016-10-25 14:51:29.975600
46.101.xx.yy - - [25/Oct/2016 14:51:33] "POST /my_route HTTP/1.1" 200 1569
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/bottle.py", line 1391, in __getattr__
var = self.environ['bottle.request.ext.%s'%name]
KeyError: 'bottle.request.ext.my_attr'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/bottle.py", line 862, in _handle
return route.call(**args)
File "/usr/local/lib/python3.4/dist-packages/bottle.py", line 1732, in wrapper
rv = callback(*a, **ka)
File "./my_app.py", line 245, in wrapper
cb_response = callback(*args, **kwargs)
File "./my_app.py", line 264, in my_route
time = request.my_attr
File "/usr/local/lib/python3.4/dist-packages/bottle.py", line 1394, in __getattr__
raise AttributeError('Attribute %r not defined.' % name)
AttributeError: Attribute 'my_attr' not defined.
46.101.xx.yy - - [25/Oct/2016 14:51:37] "POST /my_route HTTP/1.1" 500 760
私はそれぞれの要求にrequest.my_attr
をリセットするにはどうすればよいですか?
私は、単に 'request'ごとにプラグイン本体の中でカスタムオブジェクトを初期化し、属性として' request'ボトルに付け加えて、そのカスタムオブジェクトをhttpハンドラで再利用したいと思っていました。これを行うより良い戦略はありますか?もし存在しなければ - 私はあなたの答えを受け入れるでしょう。 'wrapper'の中で(' callback'呼び出しの前に) 'request.my_attr = self.time'を動かすことは本質的に私の問題を解決しました。私は 'route.reset()'を使ってすべてのプラグインが確実に再適用されるようにしましたが、実際にはもう少しテストをしてみると実際には必要ないようです。 –
ありがとうございます。はい、あなたのプラグインがすべての要求にルートハンドラで使用できる属性を追加するようにするには、本当に 'wrapper'でそれを設定する必要があります。 'wrapper'はすべての要求(ルートハンドラの前に)で呼び出されるものです。 –