def _process(self): pdf = ContributionBook(self.event, session.user, self.contribs, tz=self.event.timezone) return send_file('book-of-abstracts.pdf', pdf.generate(), 'application/pdf')
def _process(self): filename = '{}-category.ics'.format( secure_filename(self.category.title, str(self.category.id))) buf = serialize_categories_ical([self.category.id], session.user, Event.end_dt >= (now_utc() - timedelta(weeks=4))) return send_file(filename, buf, 'text/calendar')
def _process(self): # QRCode (Version 6 with error correction L can contain up to 106 bytes) qr = qrcode.QRCode(version=6, error_correction=qrcode.constants.ERROR_CORRECT_M, box_size=4, border=1) checkin_app = OAuthApplication.find_one( system_app_type=SystemAppType.checkin) qr_data = { "event_id": self.event.id, "title": self.event.title, "date": self.event.start_dt.isoformat(), "version": 1, "server": { "base_url": config.BASE_URL, "consumer_key": checkin_app.client_id, "auth_url": url_for('oauth.oauth_authorize', _external=True), "token_url": url_for('oauth.oauth_token', _external=True) } } json_qr_data = json.dumps(qr_data) qr.add_data(json_qr_data) qr.make(fit=True) qr_img = qr.make_image() output = BytesIO() qr_img.save(output) output.seek(0) return send_file('config.png', output, 'image/png')
def _generate_zip_file(self, files_holder, name_prefix='material', name_suffix=None): """Generate a zip file containing the files passed. :param files_holder: An iterable (or an iterable containing) object that contains the files to be added in the zip file. :param name_prefix: The prefix to the zip file name :param name_suffix: The suffix to the zip file name :return: The generated zip file. """ temp_file = NamedTemporaryFile(suffix='fossir.tmp', dir=config.TEMP_DIR) with ZipFile(temp_file.name, 'w', allowZip64=True) as zip_handler: self.used_filenames = set() for item in self._iter_items(files_holder): name = self._prepare_folder_structure(item) self.used_filenames.add(name) with item.storage.get_local_path( item.storage_file_id) as filepath: zip_handler.write(filepath.encode('utf-8'), name) temp_file.delete = False zip_file_name = '{}-{}.zip'.format( name_prefix, name_suffix) if name_suffix else '{}.zip'.format(name_prefix) chmod_umask(temp_file.name) return send_file(zip_file_name, temp_file.name, 'application/zip', inline=False)
def _process(self): self.commit = False config_params = poster_cache.get(request.view_args['uuid']) if not config_params: raise NotFound pdf = PosterPDF(self.template, config_params, self.event) return send_file('Poster-{}.pdf'.format(self.event.id), pdf.get_pdf(), 'application/pdf')
def _process(self): if not self.category.has_logo: raise NotFound metadata = self.category.logo_metadata return send_file(metadata['filename'], BytesIO(self.category.logo), mimetype=metadata['content_type'], conditional=True)
def _process(self): filename = '{}-category.atom'.format( secure_filename(self.category.title, str(self.category.id))) buf = serialize_category_atom( self.category, url_for(request.endpoint, self.category, _external=True), session.user, Event.end_dt >= now_utc()) return send_file(filename, buf, 'application/atom+xml')
def send_file(self, file_id, content_type, filename, inline=True): try: return send_file(filename, self._resolve_path(file_id).encode('utf-8'), content_type, inline=inline) except Exception as e: raise StorageError('Could not send "{}": {}'.format( file_id, e)), None, sys.exc_info()[2]
def send_csv(filename, headers, rows): """Sends a CSV file to the client :param filename: The name of the CSV file :param headers: a list of cell captions :param rows: a list of dicts mapping captions to values :return: a flask response containing the CSV data """ buf = generate_csv(headers, rows) return send_file(filename, buf, 'text/csv', inline=False)
def _process(self): pdf = RegistrantsListToPDF(self.event, reglist=self.registrations, display=self.export_config['regform_items'], static_items=self.export_config['static_item_ids']) try: data = pdf.getPDFBin() except Exception: if config.DEBUG: raise raise NoReportError(_("Text too large to generate a PDF with table style. " "Please try again generating with book style.")) return send_file('RegistrantsList.pdf', BytesIO(data), 'application/pdf')
def _process(self): config_params = badge_cache.get(request.view_args['uuid']) if not config_params: raise NotFound if config_params['page_layout'] == PageLayout.foldable: pdf_class = RegistrantsListToBadgesPDFFoldable elif config_params['page_layout'] == PageLayout.double_sided: pdf_class = RegistrantsListToBadgesPDFDoubleSided else: pdf_class = RegistrantsListToBadgesPDF registration_ids = config_params.pop('registration_ids') signals.event.designer.print_badge_template.send(self.template, regform=self.regform) pdf = pdf_class(self.template, config_params, self.event, registration_ids) return send_file('Badges-{}.pdf'.format(self.event.id), pdf.get_pdf(), 'application/pdf')
def send_xlsx(filename, headers, rows, tz=None): """Sends an XLSX file to the client :param filename: The name of the CSV file :param headers: a list of cell captions :param rows: a list of dicts mapping captions to values :param tz: the timezone for the values that are datetime objects :return: a flask response containing the XLSX data """ buf = generate_xlsx(headers, rows, tz=tz) return send_file( filename, buf, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', inline=False)
def _process(self): xmlgen = XMLGen() xmlgen.initXml() outgen = outputGenerator(session.user, xmlgen) xmlgen.openTag(b'marc:record', [ [b'xmlns:marc', b'http://www.loc.gov/MARC21/slim'], [b'xmlns:xsi', b'http://www.w3.org/2001/XMLSchema-instance'], [ b'xsi:schemaLocation', b'http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd' ] ]) outgen.confToXMLMarc21(self.event) xmlgen.closeTag(b'marc:record') return send_file('event-{}.marc.xml'.format(self.event.id), BytesIO(xmlgen.getXml()), 'application/xml')
def js_vars_global(): """ Provides a JS file with global definitions (all users) Useful for server-wide config options, URLs, etc... """ cache_file = os.path.join(config.CACHE_DIR, 'assets_global_{}.js'.format(config.hash)) if not os.path.exists(cache_file): data = generate_global_file() with open(cache_file, 'wb') as f: f.write(data) return send_file('global.js', cache_file, mimetype='application/javascript', no_cache=False, conditional=True)
def room_photo(roomID, size, **kw): cache_key = 'photo-{}-{}'.format(roomID, size) photo_data = _cache.get(cache_key) if photo_data == '*': return _redirect_no_photo(size) elif photo_data is None: photo = Photo.find_first(Room.id == roomID, _join=Photo.room) if photo is None: _cache.set(cache_key, '*') return _redirect_no_photo(size) photo_data = photo.thumbnail if size == 'small' else photo.data _cache.set(cache_key, photo_data) io = BytesIO(photo_data) return send_file('photo-{}.jpg'.format(size), io, 'image/jpeg', no_cache=False)
def i18n_locale(locale_name): """ Retrieve a locale in a Jed-compatible format """ root_path = os.path.join(current_app.root_path, 'translations') plugin_key = ','.join(sorted(plugin_engine.get_active_plugins())) cache_file = os.path.join( config.CACHE_DIR, 'assets_i18n_{}_{}.js'.format(locale_name, crc32(plugin_key))) if not os.path.exists(cache_file): i18n_data = locale_data(root_path, locale_name, 'fossir') if not i18n_data: # Dummy data, not having the fossir domain would cause lots of failures i18n_data = { 'fossir': { '': { 'domain': 'fossir', 'lang': locale_name } } } for pid, plugin in plugin_engine.get_active_plugins().iteritems(): data = {} if plugin.translation_path: data = locale_data(plugin.translation_path, locale_name, pid) if not data: # Dummy entry so we can still load the domain data = {pid: {'': {'domain': pid, 'lang': locale_name}}} i18n_data.update(data) with open(cache_file, 'wb') as f: f.write("window.TRANSLATIONS = {};".format(json.dumps(i18n_data))) return send_file('{}.js'.format(locale_name), cache_file, mimetype='application/javascript', no_cache=False, conditional=True)
def category(self, idlist, format): try: idlist = map(int, idlist) except ValueError: raise HTTPAPIError('Category IDs must be numeric', 400) if format == 'ics': buf = serialize_categories_ical(idlist, self.user, event_filter=Event.happens_between( self._fromDT, self._toDT), event_filter_fn=self._filter_event, update_query=self._update_query) return send_file('events.ics', buf, 'text/calendar') else: query = (Event.query.filter( ~Event.is_deleted, Event.category_chain_overlaps(idlist), Event.happens_between(self._fromDT, self._toDT)).options( *self._get_query_options(self._detail_level))) query = self._update_query(query) return self.serialize_events( x for x in query if self._filter_event(x) and x.can_access(self.user))
def _process(self): form = TimetablePDFExportForm(formdata=request.args, csrf_enabled=False) if form.validate_on_submit(): form_data = form.data_for_format pdf_format = TimetablePDFFormat(form_data) if not form.advanced.data: pdf_format.contribsAtConfLevel = True pdf_format.breaksAtConfLevel = True pdf_class = SimplifiedTimeTablePlain additional_params = {} else: pdf_class = TimeTablePlain additional_params = {'firstPageNumber': form.firstPageNumber.data, 'showSpeakerAffiliation': form_data['showSpeakerAffiliation'], 'showSessionDescription': form_data['showSessionDescription']} if request.args.get('download') == '1': pdf = pdf_class(self.event, session.user, sortingCrit=None, ttPDFFormat=pdf_format, pagesize=form.pagesize.data, fontsize=form.fontsize.data, **additional_params) return send_file('timetable.pdf', BytesIO(pdf.getPDFBin()), 'application/pdf') else: url = url_for(request.endpoint, **dict(request.view_args, download='1', **request.args.to_dict(False))) return jsonify_data(flash=False, redirect=url, redirect_no_loading=True) return jsonify_template('events/timetable/timetable_pdf_export.html', form=form, back_url=url_for('.timetable', self.event))
def _process(self): pdf = ConfManagerAbstractToPDF(self.abstract) filename = 'abstract-{}-reviews.pdf'.format(self.abstract.friendly_id) return send_file(filename, pdf.generate(), 'application/pdf')
def _process(self): pdf = ProgrammeToPDF(self.event) return send_file('program.pdf', BytesIO(pdf.getPDFBin()), 'application/pdf')
def _process(self): pdf = get_timetable_offline_pdf_generator(self.event) return send_file('timetable.pdf', BytesIO(pdf.getPDFBin()), 'application/pdf')
def _process(self): if not self.event.has_stylesheet: raise NotFound data = BytesIO(self.event.stylesheet.encode('utf-8')) return send_file(self.event.stylesheet_metadata['filename'], data, mimetype='text/css', conditional=True)
def _process(self): sorted_abstracts = sorted(self.abstracts, key=attrgetter('friendly_id')) cls = ConfManagerAbstractsToPDF if self.management else AbstractsToPDF pdf = cls(self.event, sorted_abstracts) return send_file('abstracts.pdf', pdf.generate(), 'application/pdf')
def _process(self): contribs = self.list_generator.get_list_kwargs()['contribs'] pdf = ContribsToPDF(self.event, contribs) return send_file('contributions.pdf', pdf.generate(), 'application/pdf')
def _process(self): pdf = ContribToPDF(self.contrib) return send_file('contribution.pdf', pdf.generate(), 'application/pdf')
def _process(self): io = BytesIO(self.agreement.attachment) mimetype = mimetypes.guess_type(self.agreement.attachment_filename)[0] or 'application/octet-stream' return send_file(self.agreement.attachment_filename, io, mimetype)
def _process(self): if not self.contrib.is_scheduled: raise NotFound('This contribution is not scheduled') return send_file('contribution.ics', get_contribution_ical_file(self.contrib), 'text/calendar')
def _process(self): detail_level = request.args.get('detail', 'events') data = {'results': serialize_event_for_ical(self.event, detail_level)} serializer = Serializer.create('ics') return send_file('event.ics', BytesIO(serializer(data)), 'text/calendar')
def _process(self): filename = secure_filename('{}-Ticket.pdf'.format(self.event.title), 'ticket.pdf') return send_file(filename, generate_ticket(self.registration), 'application/pdf')
def _process(self): pdf = AbstractsToPDF(self.event, get_user_abstracts(self.event, session.user)) return send_file('my-abstracts.pdf', pdf.generate(), 'application/pdf')