本文整理汇总了Python中pyramid.response.Response.content_type方法的典型用法代码示例。如果您正苦于以下问题:Python Response.content_type方法的具体用法?Python Response.content_type怎么用?Python Response.content_type使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyramid.response.Response
的用法示例。
在下文中一共展示了Response.content_type方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_json_xsrf
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_type [as 别名]
def test_json_xsrf(self):
def json_response(string_value):
resp = Response(string_value)
resp.status = 200
resp.content_type = 'application/json'
filter_json_xsrf(resp)
# a view returning a vulnerable json response should issue a warning
for value in [
'["value1", "value2"]', # json array
' \n ["value1", "value2"] ', # may include whitespace
'"value"', # strings may contain nasty characters in UTF-7
]:
resp = Response(value)
resp.status = 200
resp.content_type = 'application/json'
filter_json_xsrf(resp)
assert len(self.get_logs()) == 1, "Expected warning: %s" % value
# a view returning safe json response should not issue a warning
for value in [
'{"value1": "value2"}', # json object
' \n {"value1": "value2"} ', # may include whitespace
'true', 'false', 'null', # primitives
'123', '-123', '0.123', # numbers
]:
resp = Response(value)
resp.status = 200
resp.content_type = 'application/json'
filter_json_xsrf(resp)
assert len(self.get_logs()) == 0, "Unexpected warning: %s" % value
示例2: thumbnail
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_type [as 别名]
def thumbnail(request):
matchdict = request.matchdict
photo_album_id = matchdict['photo_album_id']
photo_id = matchdict['photo_id']
photo_album = models.PhotoAlbum.objects.with_id(photo_album_id)
photo = photo_album.get_photo(photo_id)
extension = photo.image.filename[photo.image.filename.rfind('.')+1:]
if photo.image.thumbnail:
image = photo.image.thumbnail
response = Response()
if extension.lower() in ['jpg', 'jpeg']:
response.content_type='image/jpeg'
elif extension.lower() in ['png']:
response.content_type='image/png'
img = Image.open(image)
img_format = img.format
if photo.orientation == 'vertical':
img = img.transpose(Image.ROTATE_90)
tmp_img = tempfile.TemporaryFile()
img.save(tmp_img, format=img_format)
tmp_img.seek(0)
response.body_file = tmp_img
return response
示例3: download_view
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_type [as 别名]
def download_view(context, request):
response = Response(context.data)
filename = context.frs.basename(context.vpath)
mt, encoding = mimetypes.guess_type(filename)
if isinstance(context, Page):
response.content_type = 'text/html' # mt or 'text/plain'
else:
response.content_type = mt or 'text/plain'
return response
示例4: getResponse
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_type [as 别名]
def getResponse(self, reqPath):
with open(reqPath, "rb") as fp:
ret = Response(body=fp.read())
if reqPath.endswith(".js"):
ret.content_type = "text/javascript"
if reqPath.endswith(".css"):
ret.content_type = "text/css"
if reqPath.endswith(".ico"):
ret.content_type = "image/x-icon"
self.log.info("Request for URL %s, inferred MIME type %s", reqPath, ret.content_type)
return ret
示例5: export
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_type [as 别名]
def export(self, extm, params, req):
csv_dialect = params.pop('csv_dialect', 'excel')
csv_encoding = params.pop('csv_encoding', 'utf_8')
fields = []
for field in extm.export_view:
if isinstance(field, PseudoColumn):
continue
fields.append(field)
if csv_encoding not in _encodings:
raise ValueError('Unknown encoding specified')
res = Response()
loc = get_localizer(req)
now = datetime.datetime.now()
res.last_modified = now
if csv_dialect in ('excel', 'excel-tab'):
res.content_type = 'application/vnd.ms-excel'
else:
res.content_type = 'text/csv'
res.charset = _encodings[csv_encoding][0]
res.cache_control.no_cache = True
res.cache_control.no_store = True
res.cache_control.private = True
res.cache_control.must_revalidate = True
res.headerlist.append(('X-Frame-Options', 'SAMEORIGIN'))
if PY3:
res.content_disposition = \
'attachment; filename*=UTF-8\'\'%s-%s.csv' % (
urllib.parse.quote(loc.translate(extm.menu_name), ''),
now.date().isoformat()
)
else:
res.content_disposition = \
'attachment; filename*=UTF-8\'\'%s-%s.csv' % (
urllib.quote(loc.translate(extm.menu_name).encode(), ''),
now.date().isoformat()
)
for prop in ('__page', '__start', '__limit'):
if prop in params:
del params[prop]
data = extm.read(params, req)['records']
res.app_iter = csv_generator(
data, fields, csv_dialect,
encoding=csv_encoding,
localizer=loc,
model=extm
)
return res
示例6: test_json_xsrf
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_type [as 别名]
def test_json_xsrf(self):
# a view returning a json list should issue a warning
resp = Response(json.dumps(('value1', 'value2')))
resp.status = 200
resp.content_type = 'application/json'
filter_json_xsrf(resp)
self.assertEquals(len(self.get_logs()), 1)
# json lists can also start end end with spaces
resp = Response(" ('value1', 'value2') ")
resp.status = 200
resp.content_type = 'application/json'
filter_json_xsrf(resp)
self.assertEquals(len(self.get_logs()), 1)
示例7: show_img
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_type [as 别名]
def show_img(request):
'''画像表示
'''
file_name = request.matchdict['file_name']
md = model(request.db)
file = md.get_file(file_name)
response = Response()
if file is not None:
response.content_type = file.content_type
response.app_iter = file
else:
response.content_type = 'image/jpeg'
response.app_iter = open('nopict.jpg', 'rb')
return response
示例8: structured_text_view
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_type [as 别名]
def structured_text_view(context, request):
""" Filesystem-based STX view
"""
result = stx2html(context.source)
response = Response(result)
response.content_type = 'text/html'
return response
示例9: getUserAvatar
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_type [as 别名]
def getUserAvatar(context, request):
"""
Get user avatar
"""
base_folder = request.registry.settings.get('avatar_folder')
username = request.matchdict['username']
named_size = request.matchdict.get('size', '')
filename = ''
# First attempt to find an existing named size avatar
# If image is not sized, this will fallback to regular avatar.
avatar_folder = get_avatar_folder(base_folder, 'people', username, size=named_size)
if os.path.exists(os.path.join(avatar_folder, username)):
filename = username
# If we were loking for a named size avatar, reaching here
# menans we did not found it, so fallback to base avatar
elif named_size:
avatar_folder = get_avatar_folder(base_folder, 'people', username)
if os.path.exists(os.path.join(avatar_folder, username)):
filename = username
# At this point we should have a filename set, if not, it means that we
# couldn't locate any size of the requested avatar. In this case, set the
# missing avatar filename, based on context and size and located at root
# avatars folder
avatar_folder = avatar_folder if filename else get_avatar_folder(base_folder)
named_size_sufix = '-{}'.format(named_size) if named_size else ''
filename = filename if filename else 'missing-people.png'.format(context, named_size_sufix)
data = open(os.path.join(avatar_folder, filename)).read()
image = Response(data, status_int=200)
image.content_type = 'image/png'
return image
示例10: translation_template
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_type [as 别名]
def translation_template(request):
resp = Response()
resp.content_disposition = 'attachment; filename=oscad.pot'
resp.app_iter = resource_stream('oscad', 'locale/oscad.pot')
# otherwise Firefox thinks its a PowerPoint
resp.content_type = 'text/plain'
return resp
示例11: buildResponse
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_type [as 别名]
def buildResponse(self, payload=None):
"""
"""
data = payload == None and self.data or payload
response = Response(data, status_int=self.status_code)
response.content_type = self.response_content_type
return response
示例12: response
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_type [as 别名]
def response(self, request, error):
"""
Render an API Response
Create a Response object, similar to the JSONP renderer
[TODO: re-factor in to the JSONP renderer]
Return the Response object with the appropriate error code
"""
jsonp_render = request.registry._jsonp_render
default = jsonp_render._make_default(request)
val = self.serializer(self.envelope(success=False, error=error.error),
default=default,
**jsonp_render.kw)
callback = request.GET.get(jsonp_render.param_name)
response = Response("", status=200) # API Error code is always 200
if callback is None:
ct = 'application/json'
response.status = error.code
response.body = val
else:
ct = 'application/javascript'
response.text = '%s(%s)' % (callback, val)
if response.content_type == response.default_content_type:
response.content_type = ct
return response
示例13: getBadges
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_type [as 别名]
def getBadges(req):
'''Retrieve a user's badge information'''
key = db.get(req.matchdict['user'])
res = Response(status=404)
if key.exists:
# generate proper response body
body = None
if 'type' not in req.matchdict:
body = {'badges': key.data['badges']}
elif req.matchdict['type'] in ['achieved','inprogress','desired']:
badgeType = 'inProgress' if req.matchdict['type'] == 'inprogress' else req.matchdict['type']
body = {badgeType: key.data['badges'][badgeType]}
if body != None:
hash = util.genETag(body)
if_none_match = req.headers['If-None-Match'] if 'If-None-Match' in req.headers.keys() else None
if if_none_match not in ['*',hash]:
res.status = 200
res.content_type = 'application/json'
res.headers['ETag'] = hash
res.json = body
else:
res.status = 304
return res
示例14: plot
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_type [as 别名]
def plot(request):
"""
http://stackoverflow.com/a/5515994/185820
"""
import cStringIO
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg
x, y = 4, 4
qs = parse_qs(request.query_string)
if 'x' in qs:
x = int(qs['x'][0])
if 'y' in qs:
y = int(qs['y'][0])
fig = Figure(figsize=[x, y])
ax = fig.add_axes([.1, .1, .8, .8])
ax.scatter([1, 2], [3, 4])
canvas = FigureCanvasAgg(fig)
# write image data to a string buffer and get the PNG image bytes
buf = cStringIO.StringIO()
canvas.print_png(buf)
data = buf.getvalue()
# write image bytes back to the browser
response = Response(data)
response.content_type = 'image/png'
response.content_length = len(data)
return response
示例15: find_entities
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_type [as 别名]
def find_entities(self):
#page_limit, current_page, start, end = self._get_pagin_data()
user = get_current()
dace_catalog = find_catalog('dace')
system_catalog = find_catalog('system')
novaideo_catalog = find_catalog('novaideo')
filter_schema = FindEntitiesJson(self.context, self.request)
try:
appstruct = filter_schema.calculate_posted_filter()
except Exception as e:
return {'items': [], 'total_count': 0, 'error': True,
'message': '{}: {}'.format(
e.__class__.__name__, e.args[0])}
if appstruct is None:
return {'items': [], 'total_count': 0, 'error': True,
'message': 'appstruct is None'}
content_types_tree = appstruct['metadata_filter'].get('content_types', {}).copy()
content_types = list(content_types_tree.keys())
appstruct['metadata_filter'] = appstruct.get('metadata_filter', {})
appstruct['metadata_filter']['content_types'] = content_types
appstruct['dace'] = dace_catalog
appstruct['system'] = system_catalog
appstruct['novaideo'] = novaideo_catalog
entities = find_entities(
user=user, sort_on='release_date', include_site=True, **appstruct)
def dumps(obj):
"""return values of attributes descibed in
the colander schema node 'node' """
registry = get_current_registry()
content_type = registry.content.typeof(obj)
fields = content_types_tree.get(content_type, {})
result, to_add = get_obj_value(obj, fields)
if result is None:
return {}, to_add
return result, to_add
def merge_items(old_items, new_items):
for item in new_items:
oid = item.get('@id', None)
if oid and oid not in old_items:
old_items[oid] = item
elif oid:
old_item = old_items[oid]
old_items[oid] = merge_dicts([item, old_item])
items = {}
for entity in entities:
values, to_add = dumps(entity)
to_add.append(values)
merge_items(items, to_add)
result = {'items': list(items.values()), 'total_count': len(items)}
response = Response()
response.content_type = "application/json"
response.text = json.dumps(result, indent=2)
return response