def download_results_csv(user_dao, round_id, request_dict): coord_dao = CoordinatorDAO.from_round(user_dao, round_id) rnd = coord_dao.get_round(round_id) now = datetime.datetime.now().isoformat() output_name = 'montage_results-%s-%s.csv' % (slugify(rnd.name, ascii=True), now) # TODO: Confirm round is finalized # raise DoesNotExist('round results not yet finalized') results_by_name = coord_dao.make_vote_table(round_id) output = io.BytesIO() csv_fieldnames = ['filename', 'average'] + [r.username for r in rnd.jurors] csv_writer = unicodecsv.DictWriter(output, fieldnames=csv_fieldnames, restval=None) # na means this entry wasn't assigned csv_writer.writeheader() for filename, ratings in results_by_name.items(): csv_row = {'filename': filename} valid_ratings = [r for r in ratings.values() if type(r) is not str] if valid_ratings: # TODO: catch if there are more than a quorum of votes ratings['average'] = sum(valid_ratings) / len(valid_ratings) else: ratings['average'] = 'na' csv_row.update(ratings) csv_writer.writerow(csv_row) ret = output.getvalue() resp = Response(ret, mimetype='text/csv') resp.mimetype_params['charset'] = 'utf-8' resp.headers['Content-Disposition'] = 'attachment; filename=%s' % output_name return resp
def __call__(self, context, callback): data = context jsonp_cb = callback json_iter = self.json_encoder.iterencode(data) if jsonp_cb: resp = Response( "".join([jsonp_cb, "(", "".join([r for r in json_iter]), ")"]), mimetype="application/javascript" ) else: resp = Response(json_iter, mimetype="application/json") resp.mimetype_params["charset"] = self.json_encoder.encoding return resp
def render_response(self, request, context, _route): from collections import Sized if isinstance(context, basestring): # already serialized if self._guess_json(context): return Response(context, mimetype="application/json") elif '<html' in context[:168]: # based on the longest DOCTYPE I found in a brief search return Response(context, mimetype="text/html") else: return Response(context, mimetype="text/plain") # not serialized yet, time to guess what the requester wants if not isinstance(context, Sized): return Response(unicode(context), mimetype="text/plain") return self._serialize_to_resp(context, request, _route)
def download_round_entries_csv(user_dao, round_id): coord_dao = CoordinatorDAO.from_round(user_dao, round_id) rnd = coord_dao.get_round(round_id) entries = coord_dao.get_round_entries(round_id) entry_infos = [e.to_export_dict() for e in entries] output_name = 'montage_entries-%s.csv' % slugify(rnd.name, ascii=True) output = io.BytesIO() csv_fieldnames = sorted(entry_infos[0].keys()) csv_writer = unicodecsv.DictWriter(output, fieldnames=csv_fieldnames) csv_writer.writeheader() csv_writer.writerows(entry_infos) ret = output.getvalue() resp = Response(ret, mimetype='text/csv') resp.mimetype_params['charset'] = 'utf-8' resp.headers['Content-Disposition'] = 'attachment; filename=%s' % (output_name,) return resp
def __call__(self, context, _route): content_parts = [self._html_wrapper] if self._html_style_content: content_parts.extend([ '<head><style type="text/css">', self._html_style_content, '</style></head>' ]) content_parts.append('<body>') title = self._html_format_ep(_route) content_parts.append(title) table = Table.from_data(context, max_depth=self.max_depth) table._html_table_tag = self._html_table_tag content = table.to_html(max_depth=self.max_depth, orientation=self.orientation) content_parts.append(content) content_parts.append('</body>') content_parts.append(self._html_wrapper_close) return Response('\n'.join(content_parts), mimetype='text/html')
def _serialize_to_resp(self, context, request, _route): req_format = request.args.get(self.qp_name) # explicit GET query param if req_format and req_format not in self._format_mime_map: # TODO: badrequest raise ValueError('format expected one of %r, not %r' % (self.formats, req_format)) resp_mime = self._format_mime_map.get(req_format) if not resp_mime and request.accept_mimetypes: resp_mime = request.accept_mimetypes.best_match(self.mimetypes) if resp_mime not in self._mime_format_map: resp_mime = self._default_mime if resp_mime == 'application/json': return self.json_render(context) elif resp_mime == 'text/html': return self.autotable_render(context, _route) return Response(unicode(context), mimetype="text/plain")
def test_base_application_basics(): br = Route('/', lambda request: Response('lolporte')) ba = Application([br]) client = ba.get_local_client() res = client.get('/') assert res.data == b'lolporte'
from __future__ import unicode_literals from pytest import raises from clastic import Application, render_basic, Response from clastic.application import Application from clastic.route import Route from clastic.route import (InvalidEndpoint, InvalidPattern, InvalidMethod) from clastic.route import S_STRICT, S_REWRITE, S_REDIRECT from clastic.errors import NotFound, ErrorHandler MODES = (S_STRICT, S_REWRITE, S_REDIRECT) NO_OP = lambda: Response() def test_new_base_route(): # note default slashing behavior ub_rp = Route('/a/b/<t:int>/thing/<das+int>', NO_OP) rp = ub_rp.bind(Application()) d = rp.match_path('/a/b/1/thing/1/2/3/4') assert d == {u't': 1, u'das': [1, 2, 3, 4]} d = rp.match_path('/a/b/1/thing/hi/') assert d == None d = rp.match_path('/a/b/1/thing/') assert d == None
def get_pytypes_len(): return Response(get_pytypes_len_gen(), mimetype="application/json")
def render(context): template = self._env.get_template(template_filename) merged_context = dict(self._injector.get(TemplateContext), **context) content = template.render(**merged_context) return Response(content, status=200, mimetype='text/html')