示例#1
0
        def _generate_cards(*args, **kwargs):
            """Render every card using :func:`tg.render_template`. All
            arguments are given to each of the card generators"""
            for gened in generator(*args, **kwargs):
                if title_template is not None:
                    gened.title_escape = False
                    gened.title = tg.render_template(template_vars={**gened.title},
                                                     template_name=title_template)

                if body_template is not None:
                    gened.body_escape = False
                    gened.body = tg.render_template(template_vars={**gened.body},
                                                    template_name=body_template)

                yield gened
示例#2
0
def template_patches_hook(response, *args, **kw):
    patched_template = response.get('template_name')
    if patched_template is None:
        return

    patches = tg.config._pluggable_templates_patches
    template_patches = patches.get(patched_template)
    if template_patches is None:
        return

    root = _html.document_fromstring(response['response'])
    for patch in template_patches:
        for action in patch.actions:
            nodes = action.selector(root)
            if nodes:
                if action.template is not None:
                    content = tg.render_template(
                        tg.request._template_patches_data, action.engine,
                        action.template)
                else:
                    content = ""

            for node in nodes:
                action.apply(node, content)

    response['response'] = _html.tostring(
        root, doctype=root.getroottree().docinfo.doctype)
示例#3
0
def test_render_default():
    conf = AppConfig(minimal=True)
    conf.default_renderer = 'json'
    app = conf.make_wsgi_app()

    res = tg.render_template({'value': 'value'})
    assert 'value": "value' in res
示例#4
0
    def create(cls, parameters, name, url):
        cwd = os.getenv('dispatch_DIR')
        np = cwd.rfind("/") + 1
        who = whoami()
        if who == "":
            error = "CSV Failure"
            reason = "User not logged"
            message = "The following {} occured, this is due to {}, please DEBUG the url : {}".format(
                error, reason, url)
            abort(status_code=500, detail=message)
        file_name = cwd + "/" + cwd[np:].replace(
            ".", "") + "/public/" + who + "_" + name + ".pdf"

        my_file = Path(file_name)
        if my_file.is_file():
            os.remove(file_name)

        ## PDF Generation ##

        options = {
            'page-width': '11.0in',
            'page-height': '8.5in',
            'margin-top': '0.1in',
            'margin-right': '0.1in',
            'margin-bottom': '0.1in',
            'margin-left': '0.1in',
            'encoding': "UTF-8",
            'quiet': '',
        }
        body = render_template(parameters, "mako", url)
        pdfkit.from_string(body, file_name, options=options)

        return "/" + who + "_" + name + ".pdf"
示例#5
0
 def genshi_manual_rendering_with_doctype(self, doctype=None):
     response.content_type = 'text/html'
     response.charset = 'utf-8'
     return render_template({},
                            'genshi',
                            'genshi_doctype.html',
                            doctype=doctype)
示例#6
0
def test_render_default():
    conf = AppConfig(minimal=True)
    conf.default_renderer = 'json'
    app = conf.make_wsgi_app()

    res = tg.render_template({'value': 'value'})
    assert 'value": "value' in res
示例#7
0
 def loadWizard(self, **kw):
     list = []
     dedwizardtemplate = render_template(
         {
             "list": list,
             "parameter1": 'something'
         }, "mako", kw['name'])
     return dict(dedwizardtemplate=dedwizardtemplate)
示例#8
0
    def getDynamicTemplate(self, **kw):
        list=[]
        #listener=kw['listener']
        currentevent = DBSession.query(Events).all()
        for element in currentevent:
            list.append({"FIELD1": element.event_id, "FIELD2": element.event_desc})

        eventtemplate = render_template({"list": list}, "mako", 'pythondispatchms.templates.traffic.eventstemplate')
        return dict(eventtemplate=eventtemplate)
示例#9
0
def table(entities, fields, workspace, *args, **kw):
    variables = dict(fields=fields,
                     entities=entities,
                     workspace=workspace,
                     actions_content=kw.get('actions_content', None))
    variables.update(kw)

    return render_template(variables,
                           template_name='ksweb.templates.partials.table')
示例#10
0
 def asyncStep(self, **kw):
     localtz = 'America/Mexico_City'
     oper_localtime = datetime.now(pytz.timezone(localtz))
     dedwizardtemplate = render_template(
         {
             "user": request.identity["repoze.who.userid"],
             "cal": kw['cal'],
             "current_time": oper_localtime.strftime('%Y-%m-%dT%H:%M:%S')
         }, "mako", 'pythondispatchms.templates.test.asyncStep')
     return dedwizardtemplate
示例#11
0
 def open(self, **kw):
     kw['id'] = "dataBase"
     if kw['user_id'] == "0":
         kw['user'] = User()
     else:
         kw['user'] = DBSession.query(User).filter_by(
             user_id=kw['user_id']).first()
     dialogtemplate = render_template(kw, "mako",
                                      'jqgrid.templates.jqgrid.user_form')
     return dict(dialogtemplate=dialogtemplate)
示例#12
0
 def grouped(self, **kw):
     pager = paginate("data", items_per_page=kw.get('items') or 10)
     pager.before_validate(None, kw)
     data = DBSession.query(PaginasGroup)
     content = dict(page='pagina',
                    title='Grouped Paginas',
                    data=data,
                    grid=group_grid)
     pager.before_render(None, kw, content)
     return render_template(content, 'kajiki', 'tgtest.templates.list')
示例#13
0
    def jinja2_manual_rendering(self, frompylons=False):
        try:
            import pylons
        except ImportError:
            frompylons = False

        if frompylons:
            from pylons.templating import render_jinja2
            return render_jinja2('jinja_inherits.jinja')
        else:
            return render_template({}, 'jinja', 'jinja_inherits.jinja')
示例#14
0
文件: root.py 项目: antsfee/tg2
    def jinja2_manual_rendering(self, frompylons=False):
        try:
            import pylons
        except ImportError:
            frompylons = False

        if frompylons:
            from pylons.templating import render_jinja2
            return render_jinja2('jinja_inherits.jinja')
        else:
            return render_template({}, 'jinja', 'jinja_inherits.jinja')
示例#15
0
文件: partials.py 项目: todun/ksweb
def sidebar(section=None, workspace=None, **kw):
    unread_qas = Qa.unread_count(workspace)
    unread_outputs = Output.unread_count(workspace)
    unread_filters = Precondition.unread_count(workspace)
    unread_documents = Document.unread_count(workspace)
    return render_template(dict(workspace=workspace,
                                unread_qas=unread_qas,
                                unread_outputs=unread_outputs,
                                unread_filters=unread_filters,
                                unread_documents=unread_documents),
                           template_name='ksweb.templates.partials.sidebar')
示例#16
0
 def addUsuario(self, **kw):
     print(kw)
     if kw["usuario_id"] == "0":
         kw['handler'] = Usuario()
         print(kw)
     else:
         kw['handler'] = DBSession.query(Usuario).filter_by(
             usuario_id=kw['usuario_id']).first()
         print(kw)
     dialogagrega = render_template(
         kw, "mako", 'myproject.templates.libreria.agregausuario')
     print(kw)
     return dict(dialogagrega=dialogagrega)
示例#17
0
    def openClose(self, **kw):
        handler_user = DBSession.query(prestamo_books_table).filter_by(
            usuario_id=kw['id']).all()
        kw['usuario'] = DBSession.query(Usuario).filter_by(
            usuario_id=kw['id']).first()
        kw['book'] = []
        kw['image'] = ""

        for item in handler_user:
            handler_book = DBSession.query(Book).filter_by(
                book_id=item.book_id).first()
            if handler_book != None:
                kw['book'].append({'book_name': handler_book.book_name})
        if kw['usuario'].image != None:
            kw['image'] = base64.b64encode(kw['usuario'].image)
            kw['image'] = str(kw['image']).replace("b'", "")
            kw['image'] = str(kw['image']).replace("'", "")
        dialogtemplate = render_template(kw, "mako",
                                         'myproject.templates.libreria.hello')
        return dict(dialogtemplate=dialogtemplate)
def template_patches_hook(response, *args, **kw):
    patched_template = response.get('template_name')
    if patched_template is None:
        return

    patches = tg.config._pluggable_templates_patches
    template_patches = patches.get(patched_template)
    if template_patches is None:
        return

    root = _html.document_fromstring(response['response'])
    for patch in template_patches:
        for action in patch.actions:
            nodes = action.selector(root)
            if nodes:
                if action.template is not None:
                    content = tg.render_template(tg.request._template_patches_data, action.engine, action.template)
                else:
                    content = ""

            for node in nodes:
                action.apply(node, content)

    response['response'] = _html.tostring(root, doctype=root.getroottree().docinfo.doctype)
示例#19
0
文件: root.py 项目: TurboGears/tg2
 def genshi_manual_rendering_with_doctype(self, doctype=None):
     response.content_type = "text/html"
     response.charset = "utf-8"
     return render_template({}, "genshi", "genshi_doctype.html", doctype=doctype)
示例#20
0
def user_menu(section=None, **kw):
    return render_template(dict(),
                           template_name='ksweb.templates.partials.user_menu')
示例#21
0
def test_render_missing_renderer():
    conf = AppConfig(minimal=True)
    app = conf.make_wsgi_app()

    tg.render_template({}, 'gensh')
def test_render_missing_renderer():
    conf = AppConfig(minimal=True)
    app = conf.make_wsgi_app()

    tg.render_template({}, 'gensh')
示例#23
0
文件: root.py 项目: antsfee/tg2
 def genshi_manual_rendering_with_doctype(self, doctype=None):
     response.content_type = 'text/html'
     response.charset = 'utf-8'
     return render_template({}, 'genshi', 'genshi_doctype.html', doctype=doctype)
示例#24
0
    def getRecord(self, **kw):

        if "state" in kw:
            if kw["state"]=="open":
                OperatorLog.addLog(user_name=kw["user"],group_name=kw["group"],operation=app_globals.viewTrafficData,traffic_id=kw['record'])
        callerEventState = "Y"
        # group = DBSession.query(ListenerUsers).filter_by(user_name=kw["group"]).first()
        # if group is not None:
        #     if group.callerevent == 1:
        #         callerEventState = "Y"
        if 'tz' in kw:
            localtz=kw['tz']
        else:
            localtz="America/Mexico_City"
        comment = ""
        callercomment = ""
        false_alarm = ""

        record = kw['record']
        pendinghistory=""
        traffic = DBSession.query(Traffic).filter_by(id=record).first()
        if traffic is not None:
            operatorlog=[]
            operlog=DBSession.query(OperatorLog).filter_by(traffic_id=record).order_by(asc(OperatorLog.time_stamp)).all()
            for operitem in operlog:
                oper_utc=arrow.get(operitem.time_stamp)
                oper_localtime = oper_utc.to(localtz)
                operatorlog.append(str(oper_localtime)+":"+operitem.user_name+":"+operitem.group_name+":"+app_globals.trafficOperation[operitem.operation])

            pendingarray=[]
            pending= DBSession.query(Pending).filter_by(traffic_id=record).all()
            for items in pending:
                utc = arrow.get(items.pending_date)
                localtime = utc.to(localtz)
                pendingarray.append(localtime)
                pendingarray.append(items.data)
            pendinghistory = render_template({"pending": pendingarray,"operatorlog": operatorlog}, "mako", 'pythondispatchms.templates.traffic.pending')
            #print("Pending:{}".format(pendinghistory))
            comment = traffic.comment
            callercomment = traffic.callercomment
            if (traffic.false_alarm == 1):
                false_alarm = "true"
            else:
                false_alarm = "false"
        imei = traffic.imei
        latitude = traffic.latitude
        longitude = traffic.longitude
        cell_lat = 0
        cell_lon = 0
        icc=""
        if traffic.cellid>0:
            parameters = {}
            parameters["key"] = app_globals.opencellkey
            parameters['mcc'] = str(traffic.mcc)
            parameters['mnc'] = str(traffic.mnc)
            parameters['lac'] = str(traffic.lac)
            parameters['cellid'] = str(traffic.cellid)
            parameters["format"] = "json"
            newSession = requests.session()
            mkw = {'params': parameters,'verify': False, 'timeout': 10}
            response = newSession.get(app_globals.opencell, **mkw)
            values = response.json()
            if "lat" in values:
                cell_lat=values["lat"]
                cell_lon=values["lon"]
                print("latitude:{}".format(latitude))

        plates=''

        imeiInfo=Rest()
        imeiData=imeiInfo.get(app_globals.domainpluto+"/services/imeiInfo", {"imei":imei})
        if imeiData["error"]=="ok":
            #print("IMEI:"+imei)
            icc=imeiData["ccid"]
            list = []
            plates=imeiData["plates"]
            list.append(dict(left=_('IMEI') + ":", right=traffic.imei, id="im"))
            list.append(dict(left=_('Brand') + ":", right=imeiData["brand"], id="br"))
            list.append(dict(left=_('Model') + ":", right=imeiData["model"], id="mo"))
            list.append(dict(left=_('Year') + ":", right=imeiData["year"], id="ye"))
            list.append(dict(left=_('Color') + ":", right=imeiData["color"], id="co"))
            list.append(dict(left=_('Plates') + ":", right=imeiData["plates"], id="pl"))
            list.append(dict(left=_('Vin') + ":", right=imeiData["vin"], id="vi"))
            list.append(dict(left=_('CCID') + ": ", right=imeiData["ccid"], id="cc"))
            list.append(dict(left=_('Phone') + ": ", right=imeiData["phone"], id="ph"))
            list.append(dict(left=_('Eco') + ":", right=imeiData["eco"], id="ec"))
            vehicle = render_template({"list": list}, "mako", 'pythondispatchms.templates.traffic.eventdata')

            serverlink = ''
            if imeiData["server"] == 1:
                serverlink = 'http://server1.gpscontrol.com.mx/GPSControl/index.aspx?username='******'&password='******'http://server2.gpscontrol.com.mx/GPSControl/index.aspx?username='******'&password='******'http://plataforma3.gpscontrol.com.mx/loginV2.aspx?user='******'&password='******'<a href="' + serverlink + '" style="color: #0000EE" target = "_new">Plataform Access</a>'
            #print("platform:"+platform)
            utf8 = URLunicode()
            cc={"id":imeiData["client_id"],"enterprise":imeiData["application"],"rfc":imeiData["rfc"],"folio_sin_nube":imeiData["folio_sinube"],"address":utf8.decode(imeiData["address"]),"exp_date":imeiData["expires"],"created":imeiData["created"],"device":imeiData["device"],"state":imeiData["state"],"phone":imeiData["phone"]}
            list=[]
            list.append(dict(left=_('Client ID') + ":", right=cc["id"]))
            list.append(dict(left=_('Enterprise') + ":", right=cc["enterprise"]))
            list.append(dict(left=_('RFC') + ":", right=cc["rfc"]))
            list.append(dict(left=_('Folio sin nube') + ":", right=cc["folio_sin_nube"]))
            list.append(dict(left=_('Address') + ":", right=cc["address"]))
            list.append(dict(left=_('Expiration Date') + ":", right=cc["exp_date"]))
            list.append(dict(left=_('Created') + ":", right=cc["created"]))
            list.append(dict(left=_('Device') + ":", right=cc["device"]))
            list.append(dict(left=_('State') + ":", right=cc["state"]))
            list.append(dict(left=_('Phone') + ":", right=cc["phone"]))


            account = render_template({"list": list}, "mako", 'pythondispatchms.templates.traffic.account')

            spunit = ''
            if traffic.speedunit is not None:
                spunit = traffic.speedunit
            list = []

            list.append(dict(left=_('Time Stamp') + ":", right=str(traffic.time_stamp), id="ts"))
            list.append(dict(left=_('Event Id') + ":", right=traffic.event_id, id="ei"))
            list.append(dict(left=_('Description') + ":", right=utf8.decode(traffic.event_desc), id="de"))
            list.append(dict(left=_('Priority') + ":", right=traffic.priority, id="pr"))
            list.append(dict(left=_('Speed') + ":", right=str(traffic.speed) + " " + spunit, id="sp"))
            list.append(dict(left=_('Azimuth') + ":", right=traffic.azimuth, id="az"))
            list.append(dict(left=_('Vehicle') + ":", right=traffic.vehicle, id="ve"))
            list.append(dict(left=_('Event Time') + ":", right=str(traffic.event_time), id="et"))

            if traffic.dedicated_id!=0:
                ded = DBSession.query(Dedicated).filter_by(id=traffic.dedicated_id).first()
                if ded is not None:
                    for dev_ele in ded.devices:
                        print("imei:{}".format(dev_ele.imei))
                        if traffic.imei==dev_ele.imei:
                            print("bingo!!")
                            list.append(dict(left=_('Conductor') + ":", right=str(dev_ele.driver_name), id="et"))
                            list.append(dict(left=_('Password') + ":", right=str(dev_ele.password), id="et"))
                            list.append(dict(left=_('Tel1') + ":", right=str(dev_ele.phone1), id="et"))
                            list.append(dict(left=_('Tel2') + ":", right=str(dev_ele.phone2), id="et"))
                            list.append(dict(left=_('Tel3') + ":", right=str(dev_ele.phone3), id="et"))
                            list.append(dict(left=_('Obs') + ":", right=str(dev_ele.obs), id="et"))

            if callercomment != "":
                list.append(dict(left=_('Comment') + ":", right=callercomment, id="cc"))
            searchticket = DBSession.query(Tickets).filter_by(traffic_id=traffic.id).all()
            for item in searchticket:
                list.append(dict(left=_('Venus ticket') + ":", right="(" + str(item.ticket) + ") ----> " + str(
                    item.last_report) + " " + str(item.comment), id="cc"))
            searchpending = DBSession.query(Pending).filter_by(traffic_id=traffic.id).all()
            for item in searchpending:
                list.append(dict(left=_('Pending') + ":",
                                 right=str(item.pending_date.strftime('%Y/%m/%d %H:%M:%S')) + " (" +
                                     item.data + ")", id="cc"))

            searchticket = DBSession.query(Images).filter_by(traffic_id=traffic.id).all()
            imagelist = []
            for item in searchticket:
                image = item.data
                encoded_string = str(b64encode(image),'utf-8')
                imagelist.append(encoded_string)

            images = render_template({"list": imagelist}, "mako", 'pythondispatchms.templates.traffic.images')
            query = DBSession.query(EmailData).filter_by(imei=imei,time_stamp=traffic.event_time).first()
            if query is not None:
                images = query.data

            ts = str(traffic.time_stamp)
            et = str(traffic.event_time)
            event = render_template({"list": list}, "mako", 'pythondispatchms.templates.traffic.eventdata')

            list = []
            contactInfo = Rest()
            contactsList = imeiData["contacts"]

            for eachContact in contactsList:
                list.append(dict(name=eachContact["contact_name"], email=eachContact["contact_email"], phone1=eachContact["phone_one"],
                                 phone2=eachContact["phone_two"], phone3=eachContact["phone_tree"]))

            callerlist = render_template({"list": list}, "mako", 'pythondispatchms.templates.traffic.callerlist')
            list = []
            list.append(dict(event=""))
            history = DBSession.query(Traffic).filter_by(imei=traffic.imei).all()
            for e in history:
                utf8 = URLunicode()
                if e.event_desc is None:
                    ed = utf8.decode(str(e.event_desc))
                else:
                    ed = utf8.decode(e.event_desc)
                utc = arrow.get(e.time_stamp)
                localtime = utc.to(localtz)
                list.append(dict(
                    event="a las: " + str(localtime) + " Cliente " + e.user_name + " Evento " + str(e.event_id) + " " + ed + " Vehiculo " + e.vehicle))
            accounthistory = render_template({"list": list}, "mako", 'pythondispatchms.templates.traffic.history')

        else:
            images = ""
            query = DBSession.query(EmailData).filter_by(imei=imei,time_stamp=traffic.event_time).first()
            if query is not None:
                images = query.data

            list = []
            ts=""
            et=""
            list.append(dict(left="Data not found", right="IMEI " + traffic.imei + " not found"))
            account = render_template({"list": list}, "mako", 'pythondispatchms.templates.traffic.account')
            list = []
            utf8 = URLunicode()

            list.append(dict(left=_('Time Stamp') + ":", right=str(traffic.time_stamp), id=""))
            list.append(dict(left=_('Event Id') + ":", right=traffic.event_id, id=""))
            list.append(dict(left=_('Description') + ":", right=utf8.decode(traffic.event_desc), id=""))
            list.append(dict(left=_('Priority') + ":", right=traffic.priority, id=""))
            list.append(dict(left=_('Speed') + ":", right=traffic.speed, id=""))
            list.append(dict(left=_('Azimuth') + ":", right=traffic.azimuth, id=""))
            list.append(dict(left=_('Vehicle') + ":", right=traffic.vehicle, id=""))
            list.append(dict(left=_('Event Time') + ":", right=str(traffic.event_time), id=""))

            searchpending = DBSession.query(Pending).filter_by(traffic_id=traffic.id).all()
            for item in searchpending:
                utc = arrow.get(item.pending_date)
                localtime = utc.to(localtz)
                list.append(dict(left=_('Pending') + ":",
                                 right=str(localtime.strftime('%Y/%m/%d %H:%M:%S')) + " (" +
                                     item.data + ")", id="cc"))
            event = render_template({"list": list}, "mako", 'pythondispatchms.templates.traffic.eventdata')
            list = []
            list.append(dict(left=_('IMEI') + ":", right=traffic.imei, id=""))
            vehicle = render_template({"list": list}, "mako", 'pythondispatchms.templates.traffic.eventdata')
            list = []
            list.append(dict(name="", email="", phone1="", phone2="", phone3=""))
            callerlist = render_template({"list": list}, "mako", 'pythondispatchms.templates.traffic.callerlist')
            list = []
            list.append(dict(event=""))
            accounthistory = render_template({"list": list}, "mako", 'pythondispatchms.templates.traffic.history')
            list = []
            list.append(dict(event=""))
            platform = ""

        # Search newest instala
        link = 'http://dispatch.dwim.mx/traffic/noreport'
        urllink = "http://instala.dwim.mx/getuuidbyimei/" + imei
        #print("URL:{}".format(urllink))


        try:
            resp = requests.get(urllink)
        except MyError as e:
            pass
        else:
            ans = resp.text
            ans = ans.replace("[", "").replace("]", "")
            jsonanswer = json.loads(ans)
            if jsonanswer['Error'] == u'none':
                uuid = jsonanswer['uuid']
                link = "http://instala.dwim.mx/printinstallpdf/" + uuid
            else:
                # search oldest instala
                pass
                urllink = "http://ci.dwim.mx/getuuidbyimei/" + imei
                try:
                    resp = requests.get(urllink)
                except MyError as e:
                    pass
                else:
                    ans = resp.text
                    ans = ans.replace("[", "").replace("]", "")
                    jsonanswer = json.loads(ans)
                    if jsonanswer['Error'] == u'none':
                        uuid = jsonanswer['uuid']
                        link = "http://ci.dwim.mx/printinstallpdf/" + uuid
                    else:
                        link = "dontHave"



        return dict(account=account, event=event, callerlist=callerlist, accounthistory=accounthistory,
                    latitude=latitude, longitude=longitude, comment=comment, false_alarm=false_alarm,
                    attended_state=traffic.attended_state, link=link, vehicle=vehicle, platform=platform, ts=ts, et=et,
                    images=images, callerEventState=callerEventState,plates=plates,cell_lat=cell_lat,cell_lon=cell_lon,icc=icc,pendinghistory=pendinghistory)
示例#25
0
 def displayLoanTemplate(self, **kw):
     displayloantemplate = render_template(
         {"loanid": kw['id']}, "mako",
         'myproject.templates.makoconnection.displayloantemplate')
     return dict(displayloantemplate=displayloantemplate)
示例#26
0
 def loanTemplate(self, **kw):
     list = []
     loantemplate = render_template(
         {"list": list}, "mako",
         'myproject.templates.makoconnection.loantemplate')
     return dict(loantemplate=loantemplate)
示例#27
0
def render(template_path):
    return render_template({'url': url}, 'mako', template_path)
示例#28
0
def sidebar(section=None, workspace=None, **kw):
    return render_template(dict(workspace=workspace),
                           template_name='ksweb.templates.partials.sidebar')
示例#29
0
 def displayBooks(self, **kw):
     displaybooks = render_template(
         {"list": list}, "mako",
         'myproject.templates.libreria.displaybooks')
     return dict(displaybooks=displaybooks)
示例#30
0
 def prestamosTemplate(self, **kw):
     list = []
     prestamostemplate = render_template(
         {"list": list}, "mako",
         'myproject.templates.libreria.prestamostemplate')
     return dict(prestamostemplate=prestamostemplate)
示例#31
0
 def displayUsuarios(self, **kw):
     displayusuarios = render_template(
         {"list": list}, "mako",
         'myproject.templates.libreria.displayusuarios')
     return dict(displayusuarios=displayusuarios)