def run(self,rr,elem,**kw): tplname = elem._meta.app_label + '/' + elem.__class__.__name__ + '/email.html' fn = find_config_file(tplname) logger.info("Using email template %s",fn) tpl = CheetahTemplate(file(fn).read()) #~ tpl.self = elem # doesn't work because Cheetah adds itself a name 'self' tpl.instance = elem html_content = unicode(tpl) from lino.modlib.mails.models import Mail m = Mail(sender=rr.get_user(),subject=elem.get_subject(),body=html_content) m.full_clean() m.save() #~ for t,n,a in elem.get_recipients(): #~ m.recipient_set.create(type=t,address=a,name=n) for t,c in elem.get_mailable_recipients(): r = Recipient(mail=m,type=t,partner=c) r.full_clean() r.save() #~ m.recipient_set.create(type=t,partner=c) a = Attachment(mail=m,owner=elem) a.save() kw.update(open_url=rr.ui.get_detail_url(m)) return rr.ui.success(**kw)
def get_template_file(self, ar, action, elem): from lino.utils.config import find_config_file tpl_leaf = self.get_template_leaf(action, elem) group = elem.get_templates_group() tplfile = find_config_file(tpl_leaf, group) if not tplfile: raise Warning("No file %s/%s" % (group, tpl_leaf)) return tplfile
def get_template_leaf(self, action, elem): tpls = action.get_print_templates(self, elem) if len(tpls) != 1: raise Exception( "%s.get_print_templates() must return exactly 1 template (got %r)" % (elem.__class__.__name__, tpls) ) tpl_leaf = tpls[0] lang = elem.get_print_language() if lang != settings.SITE.DEFAULT_LANGUAGE.django_code: name = tpl_leaf[: -len(self.template_ext)] + "_" + lang + self.template_ext from lino.utils.config import find_config_file if find_config_file(name, *elem.get_template_groups()): return name return tpl_leaf
def appy_render(self,ar,target_file): if ar.get_total_count() > self.MAX_ROW_COUNT: raise Exception(_("List contains more than %d rows") % self.MAX_ROW_COUNT) tplgroup = None tplfile = find_config_file(self.template_name,tplgroup) if not tplfile: raise Exception("No file %s / %s" % (tplgroup,self.template_name)) ar.renderer = settings.SITE.ui.ext_renderer # 20120624 context = self.get_context(ar) if os.path.exists(target_file): os.remove(target_file) logger.info(u"appy.pod render %s -> %s (params=%s", tplfile,target_file,settings.SITE.appy_params) renderer = Renderer(ar,tplfile, context, target_file,**settings.SITE.appy_params) renderer.run()
def generate(self, tplname, fn, **context): from Cheetah.Template import Template as CheetahTemplate # ~ if self.tmpl_dir: # ~ tplname = join(self.tmpl_dir,tplname) # ~ tplname = self.subcommand + '/' + tplname tpl_filename = find_config_file(tplname, self.tmpl_dir) if tpl_filename is None: raise Exception("No file %s found" % tplname) if isinstance(tpl_filename, unicode): tpl_filename = tpl_filename.encode(sys.getfilesystemencoding()) tpl_filename = os.path.abspath(tpl_filename) fn = join(self.output_dir, fn) # ~ if os.path.exists(fn): # ~ if not self.options.get('overwrite'): # ~ if not confirm("Overwrite existing file %s (y/n) ?" % fn): # ~ logger.info("Skipping %s because file exists.",fn) # ~ return # ~ else: # ~ mkdir_if(os.path.dirname(fn)) settings.SITE.makedirs_if_missing(os.path.dirname(fn)) logger.info("Generating %s", fn) # ~ logger.info("Generating %s from %s",fn,tpl_filename) context.update( lino=lino, # ~ models=models, settings=settings, app_labels=app_labels, ) # ~ d = dict(site=site) # ~ print 20110223, [m for m in models.get_models()] # ~ print 20110315, context tpl = CheetahTemplate(file=tpl_filename, namespaces=[context]) # ~ tpl = CheetahTemplate(file(tpl_filename).read(),namespaces=[context]) s = unicode(tpl) # ~ print s file(fn, "w").write(s.encode("utf-8")) self.generated_count += 1
def get(self,request,app_label=None,actor=None): #~ ar = action_request(app_label,actor,request,request.GET,limit=PLAIN_PAGE_LENGTH) ar = action_request(app_label,actor,request,request.GET,True) ar.renderer = settings.LINO.ui.ext_renderer rh = ar.ah #~ print 20120630, 'api_list_view' fmt = request.GET.get( ext_requests.URL_PARAM_FORMAT, ar.bound_action.action.default_format) #~ logger.info("20121203 views.ApiList.get() %s",ar.bound_action.full_name()) if fmt == ext_requests.URL_FORMAT_JSON: #~ ar.renderer = ui.ext_renderer rows = [ rh.store.row2list(ar,row) for row in ar.sliced_data_iterator] #~ return json_response_kw(msg="20120124") #~ total_count = len(ar.data_iterator) total_count = ar.get_total_count() #~ if ar.create_rows: for row in ar.create_phantom_rows(): d = rh.store.row2list(ar,row) rows.append(d) total_count += 1 #~ 20120918 kw = dict(count=total_count, rows=rows, success=True, no_data_text=ar.no_data_text, #~ status=ar.get_status(ar.ui), title=unicode(ar.get_title())) #~ disabled_actions=rpt.disabled_actions(ar,None), #~ gc_choices=[gc.data for gc in ar.actor.grid_configs]) if ar.actor.parameters: #~ kw.update(param_values=ar.ah.store.pv2dict(ar.ui,ar.param_values)) kw.update(param_values=ar.actor.params_layout.params_store.pv2dict(ar.ui,ar.param_values)) return json_response(kw) if fmt == ext_requests.URL_FORMAT_HTML: #~ ar.renderer = ui.ext_renderer after_show = ar.get_status(ar.ui) if isinstance(ar.bound_action.action,actions.InsertRow): elem = ar.create_instance() #~ print 20120630 #~ print elem.national_id rec = elem2rec_insert(ar,rh,elem) after_show.update(data_record=rec) kw = dict(on_ready= ar.renderer.action_call(ar.request,ar.bound_action,after_show)) #~ ui.ext_renderer.action_call(ar.request,ar.action,after_show)) #~ print '20110714 on_ready', params kw.update(title=ar.get_title()) return http.HttpResponse(ar.ui.html_page(request,**kw)) if fmt == 'csv': #~ response = HttpResponse(mimetype='text/csv') charset = settings.LINO.csv_params.get('encoding','utf-8') response = http.HttpResponse( content_type='text/csv;charset="%s"' % charset) if False: response['Content-Disposition'] = \ 'attachment; filename="%s.csv"' % ar.actor else: #~ response = HttpResponse(content_type='application/csv') response['Content-Disposition'] = \ 'inline; filename="%s.csv"' % ar.actor #~ response['Content-Disposition'] = 'attachment; filename=%s.csv' % ar.get_base_filename() w = ucsv.UnicodeWriter(response,**settings.LINO.csv_params) w.writerow(ar.ah.store.column_names()) for row in ar.data_iterator: w.writerow([unicode(v) for v in rh.store.row2list(ar,row)]) return response if fmt in (ext_requests.URL_FORMAT_PDF,ext_requests.URL_FORMAT_ODT): if ar.get_total_count() > MAX_ROW_COUNT: raise Exception(_("List contains more than %d rows") % MAX_ROW_COUNT) from lino.utils.appy_pod import Renderer tpl_leaf = "Table.odt" tplgroup = None tplfile = find_config_file(tpl_leaf,tplgroup) if not tplfile: raise Exception("No file %s / %s" % (tplgroup,tpl_leaf)) ip = ar.request.META.get('REMOTE_ADDR','unknown_ip') target_parts = ['cache', 'appypdf', ip, str(ar.actor) + '.' + fmt] target_file = os.path.join(settings.MEDIA_ROOT,*target_parts) makedirs_if_missing(os.path.dirname(target_file)) target_url = settings.LINO.build_media_url(*target_parts) ar.renderer = ar.ui.ext_renderer # 20120624 """ [NOTE] `/blog/2012/0211` """ context = dict( ar=ar, title=unicode(ar.get_title()), dtos=babel.dtos, dtosl=babel.dtosl, dtomy=babel.dtomy, babelattr=babel.babelattr, babelitem=babel.babelitem, tr=babel.babelitem, settings=settings, _ = _, #~ knowledge_text=fields.knowledge_text, ) if os.path.exists(target_file): os.remove(target_file) logger.info(u"appy.pod render %s -> %s (params=%s", tplfile,target_file,settings.LINO.appy_params) renderer = Renderer(tplfile, context, target_file,**settings.LINO.appy_params) renderer.run() return http.HttpResponseRedirect(target_url) if fmt == ext_requests.URL_FORMAT_PRINTER: if ar.get_total_count() > MAX_ROW_COUNT: raise Exception(_("List contains more than %d rows") % MAX_ROW_COUNT) #~ ar.renderer = ui.ext_renderer response = http.HttpResponse(content_type='text/html;charset="utf-8"') doc = xghtml.Document(force_unicode(ar.get_title())) doc.body.append(xghtml.E.h1(doc.title)) t = doc.add_table() ar.ui.ar2html(ar,t,ar.data_iterator) doc.write(response,encoding='utf-8') return response raise http.Http404("Format %r not supported for GET on %s" % (fmt,ar.actor))
def objects(): city = Instantiator("countries.Place", country="EE").build input_file = find_config_file("sihtnumbrid.csv") settings.SITE.logger.info("Importing Estonian places from %s", input_file) f = codecs.open(input_file, "r", "latin-1", "replace") # ~ f = codecs.open(input_file,'r','utf-8','replace') f.readline() r = unicode_csv_reader(f, delimiter=";") # ~ r = UnicodeReader(f,delimiter=';') # r.next() maakonnad = dict() mk_names_dict = dict() # ~ vallad = dict() # ~ laakid = dict() # ~ names = set() for ln in r: # print repr(ln) if len(ln) > 2: mk = maakonnad.get(ln[0]) if mk is None: mk = city(name=ln[0], type=PlaceTypes.county) yield mk # ~ print "20120822 maakond", mk, mk.pk maakonnad[ln[0]] = mk mk_names_dict[ln[0]] = dict() names = mk_names_dict[ln[0]] if ln[1]: vald = names.get(ln[1]) if vald is None: # ~ ct = CITY_TYPES[ln[4]] vald = city(name=ln[1], type=PlaceTypes.municipality, parent=mk, zip_code=ln[7]) yield vald # ~ if ct != PlaceTypes.municipality: # ~ print "20120822", vald, "expected municipality, found", ct # ~ else: # ~ print "20120822 vald", vald, vald.pk names[ln[1]] = vald else: vald.zip_code = "" vald.save() else: vald = None laak = names.get(ln[2]) if laak is None: # ~ ct = CITY_TYPES.get(ln[4]) ct = CITY_TYPES[ln[4]] if ct is None: # ~ print "20120822 ignored addressiliik", ln[4] continue elif vald is None: laak = city(name=ln[2], type=ct, parent=mk, zip_code=ln[7]) else: laak = city(name=ln[2], type=ct, parent=vald, zip_code=ln[7]) yield laak # ~ print "20120822", laak.type, laak, laak.pk names[ln[2]] = laak # ~ else: # ~ print "20120822 pole vald ega Tallinn:", ln # ~ names.add(ln[2]) else: laak.zip_code = "" laak.save() f.close()