本文整理汇总了Python中werkzeug.Response.data方法的典型用法代码示例。如果您正苦于以下问题:Python Response.data方法的具体用法?Python Response.data怎么用?Python Response.data使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类werkzeug.Response
的用法示例。
在下文中一共展示了Response.data方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: dispatch_request
# 需要导入模块: from werkzeug import Response [as 别名]
# 或者: from werkzeug.Response import data [as 别名]
def dispatch_request(self, request):
# Process variables
self.var_dict = {
'refresh_interval': self.cfg['refresh_interval'],
'python_version': version,
'werkzeug_version': werkzeug.__version__,
'jinja_version': jinja2.__version__,
'buteo_version': self.version
}
# add data from plugins
if self.enabled_plugins != []:
for plugin in plugins.get_plugins():
try:
data = plugin.get_data(self.cfg)
except Exception as inst:
print ' * ERROR: %s. Skipping plugin %r.' % (inst, plugin.__class__.__name__)
continue
for key in data:
if not key in self.var_dict:
self.var_dict[key] = data[key]
self.var_dict['exectime'] = round(time()-self.starttime, 4)
try:
response = Response(mimetype='text/html')
response.data = self.template.render(self.var_dict)
return response
except HTTPException, e:
return e
示例2: __call__
# 需要导入模块: from werkzeug import Response [as 别名]
# 或者: from werkzeug.Response import data [as 别名]
def __call__(self, environ, start_response):
local.application = self
request = MongoRequest(environ)
local.url_adapter = adapter = url_map.bind_to_environ(environ)
environ['mongo.db'] = self.db
environ['mongo.fs'] = self.fs
try:
endpoint, values = adapter.match()
handler = getattr(views, endpoint)
data = handler(request, **values)
# WSGI
if callable(data):
return data(environ, start_response)
data = safe_keys(data)
data['request'] = request
# Templates
template = self.env.get_template("%s.html" % endpoint)
response = Response()
response.content_type = "text/html"
response.add_etag()
# if DEBUG:
# response.make_conditional(request)
data['endpoint'] = endpoint
response.data = template.render(**data)
except HTTPException, e:
response = e
示例3: miku
# 需要导入模块: from werkzeug import Response [as 别名]
# 或者: from werkzeug.Response import data [as 别名]
def miku(request):
data = request.files['image'].stream.read()
img = HomeImage.split(images.Image(data))[0]
png = img.execute_transforms(output_encoding=images.PNG)
r = Response()
r.content_type = 'image/png'
r.data = png
return r
示例4: message
# 需要导入模块: from werkzeug import Response [as 别名]
# 或者: from werkzeug.Response import data [as 别名]
def message(request, name):
response = Response()
path = os.path.join(datadir, str(name))
if request.method == 'HEAD':
pass # we only need to return headers
elif request.method == 'GET':
try:
response.data = open(path, 'r').read()
except IOError, e:
print e
raise NotFound()
示例5: test_wrapper_internals
# 需要导入模块: from werkzeug import Response [as 别名]
# 或者: from werkzeug.Response import data [as 别名]
def test_wrapper_internals():
"""Test internals of the wrappers"""
from werkzeug import Request
req = Request.from_values(data={'foo': 'bar'}, method='POST')
req._load_form_data()
assert req.form.to_dict() == {'foo': 'bar'}
# second call does not break
req._load_form_data()
assert req.form.to_dict() == {'foo': 'bar'}
# check reprs
assert repr(req) == "<Request 'http://localhost/' [POST]>"
resp = Response()
assert repr(resp) == '<Response 0 bytes [200 OK]>'
resp.data = 'Hello World!'
assert repr(resp) == '<Response 12 bytes [200 OK]>'
resp.response = iter(['Test'])
assert repr(resp) == '<Response streamed [200 OK]>'
# unicode data does not set content length
response = Response([u'Hällo Wörld'])
headers = response.get_wsgi_headers(create_environ())
assert 'Content-Length' not in headers
response = Response(['Hällo Wörld'])
headers = response.get_wsgi_headers(create_environ())
assert 'Content-Length' in headers
# check for internal warnings
print 'start'
filterwarnings('error', category=Warning)
response = Response()
environ = create_environ()
response.response = 'What the...?'
assert_raises(Warning, lambda: list(response.iter_encoded()))
assert_raises(Warning, lambda: list(response.get_app_iter(environ)))
response.direct_passthrough = True
assert_raises(Warning, lambda: list(response.iter_encoded()))
assert_raises(Warning, lambda: list(response.get_app_iter(environ)))
resetwarnings()
示例6: in
# 需要导入模块: from werkzeug import Response [as 别名]
# 或者: from werkzeug.Response import data [as 别名]
resdata = {'jsonrpc':'2.0',
'id':None,
'error':{'code':INVALID_REQUEST,
'message':errors[INVALID_REQUEST]}}
else:
resdata = [d for d in (self.process(d) for d in data)
if d is not None]
response = Response(content_type="application/json")
if resdata:
response.headers["Cache-Control"] = "no-cache"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "-1"
response.data = json.dumps(resdata)
return response(environ, start_response)
def getmod(modname):
try:
__import__(modname)
except ImportError, e:
logging.warn("import failed: %s." % e)
return None
mod = sys.modules[modname]
return mod
def HTTPExceptionMiddleware(app):
def wrap(environ, start_response):
示例7: __call__
# 需要导入模块: from werkzeug import Response [as 别名]
# 或者: from werkzeug.Response import data [as 别名]
def __call__(self, request):
try:
response = Response(mimetype="text/html")
req_url = request.path
msg = ""
if request.method == "POST":
if req_url.startswith("/add"):
goterror = False
id = self._get_id_from_path(req_url[4:])
params = []
config = {}
form = request.form
typename = form.get("typename", "")
typeerror = check_typename(typename)
if typeerror:
goterror = True
n = 0
checker = ParamChecker()
while True:
k = "param%d_" % (n,)
nk = k + "name"
vk = k + "value"
if nk not in form and vk not in form:
break
name = form.get(nk, "")
value = form.get(vk, "")
if name or value:
type = form.get(k + "type", "string")
params.append(checker.doparam(name, type, value))
if params[-1][-1]:
goterror = True
else:
config[name] = params[-1][2]
n += 1
if goterror:
msg = "Illegal input"
else:
try:
t1C.add(id, config.get("name", None), typename, config)
return redirect(id)
except Exception, e:
self.logger.exception("error")
msg = "An error occured: %s" % (e,)
else:
req_url = self._get_id_from_path(req_url)
# raise Exception(req_url)
entity = t1C.get_entity(req_url)
old = entity.config
config = {}
for k, v in request.form.iteritems():
print "%s - %s" % (k, v)
if "-" not in k:
continue
type, _, name = k.partition("-")
if type == "boolean":
v = v.lower().startswith("t")
elif type == "integer":
v = int(v)
elif type == "float":
v = float(v)
elif type == "reference":
raise NotImplementedError()
if name not in old or old[name] != v:
config[name] = v
if config:
entity.update(config)
msg = "Update successful"
else:
msg = "No values changed, nothing to do"
if req_url.startswith("/add/"):
id = req_url[5:]
if request.method != "POST":
params = [("", "", "", None) for _ in range(10)]
typename = ""
typeerror = None
t_test = self.template_lookup.get_template("add.html")
response.data = t_test.render_unicode(
url=self.__make_url,
request=request,
params=params,
id=id,
typename=typename,
types=types,
typeerror=typeerror,
msg=escape(msg),
log=(),
)
elif req_url.startswith("/del/"):
id = req_url[5:]
#.........这里部分代码省略.........