[英]Replace webapp2 usage for self.response.write in python script
[英]How to alias self.response.write in WebApp2
我想為webApp2 self.response.out.write
或self.response.write
函數使用別名。 喜歡
from __future__ import print_function
class M:
def __init__(self):
self.echo ( 'BOO BOO')
def f(self, data ) :
print ( data )
echo = f
a = M()
a.echo(' ALIASED FUNCTION ' )
我試過了
class Main(webapp2.RequestHandler):
def fun(self):
self.response.out.write ( 'FUNNY' )
def get(self):
self.response.headers['Content-Type'] = 'text/html'
self.response.write( 'DERIVED CLASS' )
self.aliasOut()
self.aliasFun()
def post(self):
pass
aliasOut = response.out.write # NameError: name 'response' is not defined
aliasFun = fun # This works
你遇到的問題是self
是每種方法的局部變量。 你不能創建一個包含self.response.out.write
的類變量,因為self
在類的頂層是未定義的。 我認為有兩種可能的解決方案:
最簡單的方法是在任何將調用self.response.out.write
的方法中創建一個本地別名:
def i_write_a_lot(self):
alias = self.response.out.write
alias("stuff")
alias("more stuff")
alias("yet more stuff")
另一種選擇是使別名成為類中的property
對象,因此可以在類中的任何位置訪問它。 關於別名的來源,這一點不太明顯,當其他人(或者你,幾個月后)讀取你的代碼時,這可能會引起混淆,但它更接近你想要的東西:
@property
def alias(self):
return self.response.out.write
def method1(self):
self.alias("stuff")
def method2(self):
self.alias("other stuff")
謝謝@Blckknght,你建議他們使用的兩種方法。
我知道這會令人困惑。 我修改了你的代碼,使其更容易混淆:)完整的最小AppEngine模板在這里:
#!/usr/bin/env python
import webapp2
class MainHandler(webapp2.RequestHandler):
def get(self):
self.echo('BOO BOO')
self.echoHtml( ' METHOD 2 ')
# To save more key strokes. I improved it slightly. Trust me, I tested it :)
echo = self.echo
echoHtml = self.echoHtml
echo ( 'HORA ')
echoHtml ( 'HAYDAAA ! ')
def echo(self, context):
alias = self.response.out.write
alias( context )
@property
def echoHtml(self):
return self.response.out.write
app = webapp2.WSGIApplication([
('/', MainHandler)
], debug=True)
我找到了另一個解決方案,我為WebApp2Request Handler創建了一個基類,並使用了這個基類而不是webapp2.RequestHandler
import webapp2
class Webapp2FactoryClass(webapp2.RequestHandler):
def echo(self, context):
self.response.out.write(context)
def __init__(self, *args, **kwargs):
super(Webapp2FactoryClass, self).__init__(*args, **kwargs)
self.args = args
self.kwargs = kwargs
class MainHandler(Webapp2FactoryClass):
def __init__(self, *args, **kwargs):
super(MainHandler, self).__init__(*args, **kwargs)
self.args = args
self.kwargs = kwargs
def get(self, *args, **kwargs):
self.echo('Bumbala')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.