本文整理汇总了Python中webob.Response.content_type方法的典型用法代码示例。如果您正苦于以下问题:Python Response.content_type方法的具体用法?Python Response.content_type怎么用?Python Response.content_type使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类webob.Response
的用法示例。
在下文中一共展示了Response.content_type方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: application
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_type [as 别名]
def application(environ, start_response):
"""Determine the user's country based on their IP address."""
request = Request(environ)
response = Response(
status=200,
cache_control=('no-store, no-cache, must-revalidate, post-check=0, '
'pre-check=0, max-age=0'),
pragma='no-cache',
expires='02 Jan 2010 00:00:00 GMT',
)
client_ip = request.headers.get('HTTP_X_CLUSTER_CLIENT_IP',
request.client_addr)
geo_data = {
'country_code': geoip.country_code_by_addr(client_ip),
'country_name': geoip.country_name_by_addr(client_ip),
}
# Users can request either a JavaScript file or a JSON file for the output.
path = request.path_info_peek()
if path == 'country.js':
response.content_type = 'text/javascript'
response.body = """
function geoip_country_code() {{ return '{country_code}'; }}
function geoip_country_name() {{ return '{country_name}'; }}
""".format(**geo_data)
elif path == 'country.json':
response.content_type = 'application/json'
response.body = json.dumps(geo_data)
else:
response.status = 404
response.content_type = 'application/json'
response.body = json.dumps({'error': 'Function not supported.'})
return response(environ, start_response)
示例2: get_version_info
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_type [as 别名]
def get_version_info(self, req, file="version"):
resp = Response()
resp.charset = 'UTF-8'
if utils.is_xml_response(req):
resp_file = os.path.join(POSSIBLE_TOPDIR,
"keystone/content/%s.xml.tpl" % file)
resp.content_type = "application/xml"
elif utils.is_atom_response(req):
resp_file = os.path.join(POSSIBLE_TOPDIR,
"keystone/content/%s.atom.tpl" % file)
resp.content_type = "application/atom+xml"
else:
resp_file = os.path.join(POSSIBLE_TOPDIR,
"keystone/content/%s.json.tpl" % file)
resp.content_type = "application/json"
hostname = req.environ.get("SERVER_NAME")
port = req.environ.get("SERVER_PORT")
if 'HTTPS' in req.environ:
protocol = 'https'
else:
protocol = 'http'
resp.unicode_body = template.template(resp_file,
PROTOCOL=protocol,
HOST=hostname,
PORT=port,
API_VERSION=version.API_VERSION,
API_VERSION_STATUS=version.API_VERSION_STATUS,
API_VERSION_DATE=version.API_VERSION_DATE)
return resp
示例3: static
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_type [as 别名]
def static(request):
response = Response()
extension = os.path.splitext(request.path_url)[1].replace('.', '')
mime = settings.mime_types.get(extension, 'text/html')
file_path = os.path.join(settings.STATIC,
request.path_info.replace('/static/', ''))
try:
file = open(file_path, 'rb')
response.body = file.read()
except Exception:
try:
file_path = os.path.join(settings.MEDIA,
request.path_info.replace('/media/', ''))
file = open(file_path, 'rb')
response.body = file.read()
except Exception:
return view_404(request)
else:
response.content_type = mime
else:
response.content_type = mime
return response
示例4: __call__
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_type [as 别名]
def __call__(self, environ, start_response):
req = Request(environ)
if req.path_info.endswith('.txt'):
s = 'Hello %s' % req.path_info
resp = Response(s)
resp.content_type = 'text/plain'
elif req.path_info.endswith('.iter'):
resp = Response()
s = 'Hello %s' % req.path_info.encode('ascii')
def app_iter(sample):
for piece in ('<html><body>', sample, '</body>', '</html>'):
yield piece
self.consumed_iter = True
yield ' '
self.consumed_iter = False
resp.content_type = 'text/html'
resp.app_iter = app_iter(s)
else:
s = '<html><body><h1>Hello %s</h1></body></html>' % req.path_info
resp = Response(s)
resp.content_type = 'text/html'
return resp(environ, start_response)
示例5: test_content_type
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_type [as 别名]
def test_content_type():
r = Response()
# default ctype and charset
eq_(r.content_type, 'text/html')
eq_(r.charset, 'UTF-8')
# setting to none, removes the header
r.content_type = None
eq_(r.content_type, None)
eq_(r.charset, None)
# can set missing ctype
r.content_type = None
eq_(r.content_type, None)
示例6: view
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_type [as 别名]
def view():
"""
Serve file content as is
"""
## FIXME: use file_wrapper
path = request.path_info
resp = Response(vfs.getcontents(path))
(content_type, resp.content_encoding) = mimetypes.guess_type(path)
if content_type:
resp.content_type = content_type
else:
resp.content_type = 'application/octet-stream'
return resp
示例7: __call__
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_type [as 别名]
def __call__(self, environ, start_response):
req = Request(environ)
resp = Response()
filename = req.path_info.strip('/')
lfilename = filename.lower()
if not req.path_info.strip('/') or os.path.isdir(filename):
if filename:
filename = path(filename, 'index.html')
else:
filename = 'index.html'
body = open(filename, 'rb').read()
resp.body = body
elif os.path.isfile(filename):
if req.method.lower() == 'delete':
sh.rm(filename + '*', shell=True)
resp = exc.HTTPNoContent()
return resp(environ, start_response)
if req.path_info.endswith('.metadata'):
cfg = ConfigObject(filename=filename)
if req.method.lower() == 'get':
resp.content_type = 'application/json'
elif req.method.lower() == 'put':
data = json.loads(req.body)
cfg.metadata.update(data)
cfg.write()
metadata = dict(cfg.metadata.items())
metadata.update(tags=cfg.metadata.tags.as_list())
resp.body = json.dumps(metadata)
elif req.path_info.endswith('.js'):
resp.content_type = 'text/javascript'
elif req.path_info.endswith('.json'):
resp.content_type = 'application/json'
elif req.path_info.endswith('.css'):
resp.content_type = 'text/css'
elif lfilename.endswith('.jpg'):
resp.charset = None
resp.content_type = 'image/jpeg'
print(filename)
if not resp.content_length:
resp.app_iter = fd(filename)
elif req.path_info.startswith('/delete/'):
filename = req.path_info[8:-1]
self.delete(filename)
resp.status_int = 302
resp.location = '/' + path.dirname(filename)
else:
resp.body = str(req.path_info)
resp.last_modified = datetime.now()
return resp(environ, start_response)
示例8: do_static
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_type [as 别名]
def do_static(self, req, path):
"""
Serve static files from disk
"""
path = os.path.normpath(os.path.join(self.static_dir, path))
if not path.startswith(self.static_dir):
self.not_found(req)
resp = Response()
resp.content_type, resp.content_encoding = mimetypes.guess_type(
path, strict=False)
if resp.content_type is None:
resp.content_type = 'application/octet-stream'
resp.content_length = os.stat(path).st_size
resp.app_iter = FileWrapper(io.open(path, 'rb'))
return resp
示例9: __call__
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_type [as 别名]
def __call__(self, env, start_response):
res = Response (content_type = 'text/plain', status = 200)
req = Request (env)
url = req.path_info
additional_params = dict(req.params)
additional_params['request'] = req
additional_params['response'] = res
additional_params['method'] = req.method
additional_params['headers'] = req.headers
found = False
for handler in UrlCallableFunction.request_handlers:
result = handler.call_if_matches (url, additional_params)
if result:
found = True
if isinstance (result, str):
res.text = result
elif isinstance (result, dict):
if 'body' in result: res.text = result['body']
if 'charset' in result: res.charset = result['charset']
if 'content_type' in result: res.content_type = result['content_type']
if 'additional_headers' in result: res.headers.update(result['additional_headers'])
if 'status' in result: res.status = result['status']
break
if not found:
res.status = 400
return res (env, start_response)
示例10: make_transcript_http_response
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_type [as 别名]
def make_transcript_http_response(content, filename, language, content_type, add_attachment_header=True):
"""
Construct `Response` object.
Arguments:
content (unicode): transcript content
filename (unicode): transcript filename
language (unicode): transcript language
mimetype (unicode): transcript content type
add_attachment_header (bool): whether to add attachment header or not
"""
headerlist = [
('Content-Language', language),
]
if add_attachment_header:
headerlist.append(
('Content-Disposition', 'attachment; filename="{}"'.format(filename.encode('utf-8')))
)
response = Response(
content,
headerlist=headerlist,
charset='utf8'
)
response.content_type = content_type
return response
示例11: __call__
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_type [as 别名]
def __call__(self, environ, start_response):
req = Request(environ)
res = Response()
res.status = "200 OK"
res.content_type = "text/plain"
# get operands
operator = req.GET.get("operator", None)
operand1 = req.GET.get("operand1", None)
operand2 = req.GET.get("operand2", None)
#print req.GET
opnd1 = int(operand1)
opnd2 = int(operand2)
if operator == u'plus':
opnd1 = opnd1 + opnd2
elif operator == u'minus':
opnd1 = opnd1 - opnd2
elif operator == u'star':
opnd1 = opnd1 * opnd2
elif operator == u'slash':
opnd1 = opnd1 / opnd2
res.body = "%s \nRESULT= %d" % (str(req.GET) , opnd1)
return res(environ,start_response)
示例12: __call__
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_type [as 别名]
def __call__(self,environ, start_response):
#print environ
print "calculator call"
req = Request(environ)
res = Response()
res.status = "200 OK"
res.content_type = "text/plain"
# get operands
operator = req.GET.get("oper", None)
operand1 = req.GET.get("op1", None)
operand2 = req.GET.get("op2", None)
print req.GET
#print operand1, operand2
#sleep(10)
opnd1 = int(operand1)
opnd2 = int(operand2)
if operator == u'plus':
opnd1 = opnd1 + opnd2
elif operator == u'minus':
opnd1 = opnd1 - opnd2
elif operator == u'star':
opnd1 = opnd1 * opnd2
elif operator == u'slash':
opnd1 = opnd1 / opnd2
res.body = "%s \nRESULT = %d\n" % (str(req.GET) , opnd1)
#return [res.body]
return res(environ,start_response)
示例13: xls_response
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_type [as 别名]
def xls_response(rows, encoding='ISO-8859-1', filename='response.xls', num_formats=(), col_widths=()):
"""Creates a downloadable webob.Response instance with the given row data
as an XLS (Excel) file.
:param rows: The spreadsheet data as rows.
:type rows: iterable
:param encoding: The character encoding for the data in the spreadsheet.
:type encoding: str
:param filename: The suggested filename for the user to save the file as.
:type filename: str
:param num_formats: A tuple of Excel format strings for numeric values.
:type num_formats: tuple
"""
stream = StringIO()
wb = xlwt.Workbook(encoding=encoding)
ws = wb.add_sheet('Nuorisovaalit 2011')
# Compile the style objects
styles = []
for fmt in num_formats:
if fmt is None:
styles.append(None)
else:
styles.append(xlwt.easyxf(num_format_str=fmt))
# Set column formatting styles.
if len(rows) > 0 and len(num_formats) == len(rows[0]):
for c in xrange(len(rows[0])):
if styles[c] is not None:
ws.col(c).set_style(styles[c])
# Set column widths.
if len(rows) > 0 and len(col_widths) == len(rows[0]):
for c in xrange(len(rows[0])):
if col_widths[c] is not None:
ws.col(c).width = col_widths[c]
for r, row in enumerate(rows):
for c, item in enumerate(row):
if len(styles) == len(row) and styles[c] is not None:
ws.write(r, c, item, styles[c])
else:
ws.write(r, c, item)
wb.save(stream)
response = Response()
response.body = stream.getvalue()
stream.close()
# Set Response headers.
response.content_type = 'application/vnd.ms-excel'
response.content_type_params = {}
response.content_disposition = 'attachment; filename={0}'.format(filename)
return response
示例14: __call__
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_type [as 别名]
def __call__(self, environ, start_response):
# SQLAlchemy boilerplate code to connect to db and connect models to db objects
engine = create_engine(engine_string)
Session = sessionmaker(bind=engine)
session = Session()
req = Request(environ)
# TODO: Add more possible filters. Do something w/ tuple below
filterkeys = ('stardate', 'enddate', 'age', 'sex')
subs = session.query(Subject)
if req.params.has_key('startdate') and req.params.has_key('enddate'):
subs = subs.filter(Subject.entrydate < req.params['enddate'], Subject.entrydate > req.params['startdate'])
elif req.params.has_key('startdate'):
subs = subs.filter(Subject.entrydate > req.params['startdate'])
elif req.params.has_key('enddate'):
subs = subs.filter(Subject.entrydate < req.params['enddate'])
subs = subs.order_by(Subject.lastname).all()
count = len(subs)
subjects = [s.to_dict(deep={'phone': {}, 'email': {}}) for s in subs]
env = Environment(loader=FileSystemLoader(os.path.join(basepath,'templates')))
template = env.get_template('subject_list.html')
template = template.render(subjects=subjects, count = count)
resp = Response()
resp.content_type='text/html'
resp.unicode_body = template
return resp(environ, start_response)
示例15: __call__
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_type [as 别名]
def __call__(self,environ,start_response):
req = Request(environ)
res = Response()
res.status = "200 OK"
res.content_type = "text/plain"
# get operands
operator = req.GET.get("op", None)
operand1 = req.GET.get("a", None)
operand2 = req.GET.get("b", None)
print req.GET
opnd1 = int(operand1)
opnd2 = int(operand2)
if operator == u'add':
opnd1 = opnd1 + opnd2
elif operator == u'-':
opnd1 = opnd1 - opnd2
elif operator == u'*':
opnd1 = opnd1 * opnd2
elif operator == u'/':
opnd1 = opnd1 / opnd2
if operator == u'add':
str1 = "%d + %d = %d" % (int(req.GET.get('a')), int(req.GET.get('b')), opnd1)
else:
str1 = "%d %s %d = %d" % (int(req.GET.get('a')), str(req.GET.get('op')), int(req.GET.get('b')), opnd1)
res.body = str1
return res(environ,start_response)