def custom_postp(r, output): # Call standard postp if callable(standard_postp): output = standard_postp(r, output) if r.interactive and isinstance(output, dict): # Modify Open Button url = URL(c="default", f="index", args=["subscriptions"], vars={"subscription_id": "[id]"}) if not (has_role("ALERT_EDITOR") or \ has_role("ALERT_APPROVER")): S3CRUD.action_buttons(r, read_url=url) else: S3CRUD.action_buttons(r, update_url=url) # Modify Add Button if "form" in output: add_btn = A(T("Create Subscription"), _class="action-btn", _href=URL(c="default", f="index", args=["subscriptions"])) output["showadd_btn"] = add_btn return output
def auth_ini(self, controller, use_username=True, reset_password=False, register=False): self.auth = Auth(self.ui.db, controller=controller, function="login") self.auth.settings.extra_fields[self.auth.settings.table_user_name] = [ Field('agree', 'boolean', default=True, label='I agree to the Terms and Conditions', requires=IS_NOT_EMPTY(error_message='You must agree this!')) ] self.auth.define_tables(username=use_username, migrate=False, fake_migrate=False) self.auth.settings.remember_me_form = False self.auth.settings.reset_password_requires_verification = True if not reset_password: self.auth.settings.actions_disabled.append( 'request_reset_password') if not register: self.auth.settings.actions_disabled.append('register') self.auth.settings.register_next = URL('index', **{'user_signature': True}) self.auth.settings.change_password_next = URL( 'index', **{'user_signature': True}) self.auth.settings.formstyle = 'table3cols' self.auth.settings.allow_basic_login = True self.auth.settings.login_onaccept.append(self.login_onaccept) return self.auth
def update(): (db, table) = get_table(request) keyed = hasattr(db[table], '_primarykey') record = None if keyed: key = [f for f in request.vars if f in db[table]._primarykey] if key: record = db( db[table][key[0]] == request.vars[key[0]]).select().first() else: record = db(db[table].id == request.args(2)).select().first() if not record: qry = query_by_table_type(table, db) session.flash = T('record does not exist') redirect(URL('select', args=request.args[:1], vars=dict(query=qry))) if keyed: for k in db[table]._primarykey: db[table][k].writable = False form = SQLFORM(db[table], record, deletable=True, delete_label=T('Check to delete'), ignore_rw=ignore_rw and not keyed, linkto=URL('select', args=request.args[:1]), upload=URL(r=request, f='download', args=request.args[:1])) if form.accepts(request.vars, session): session.flash = T('done!') qry = query_by_table_type(table, db) redirect(URL('select', args=request.args[:1], vars=dict(query=qry))) return dict(form=form, table=db[table])
def createDataBackup(): if request.vars.alias == None: return P(str(T("Error: Missing alias parameter!"))) if request.vars.bformat: bformat = str(request.vars.bformat) else: bformat = "backup" if ns.local.setEngine(request.vars.alias, True, False) == False: if request.vars.filename == "download": session.flash = str(ns.error_message) redirect(URL("create_backup")) else: return P("Error: " + str(ns.error_message)) retbc = dbtool.createDataBackup(alias=request.vars.alias, bformat=bformat, filename=request.vars.filename, verNo=response.verNo) if request.vars.filename == "download": if (not str(retbc).startswith("<span")) and ( not str(retbc).startswith("<div")): import time response.headers['Content-Type'] = 'application/octet-stream' response.headers[ 'Content-Disposition'] = 'attachment;filename="' + str( request.vars.alias) + '_' + time.strftime( "%Y%m%d_%H%M") + '.' + bformat + '"' return retbc else: session.flash = str(retbc) redirect(URL("create_backup")) return P(retbc)
def host_a_maker(record=None): """ Give a host record, return a A object that will open a new window to that host record """ from gluon.html import A, I, URL, SPAN if record is None: return A() if isinstance(record, type([str, int])): record = get_host_record(record) host_a = A(host_title_maker(record), _target="host_detail_%s" % (record.id), _href=URL('hosts', 'detail', extension='html', args=record.id)) info_a = SPAN(A(I(_class='icon-info-sign'), _href='#', _class='withajaxpopover', **{ '_data-load': URL('hosts', 'popover.json', args=record.id), '_data-trigger': 'hover', '_data-delay': "{show: 500, hide: 100}", '_data-placement': 'right', '_data-html': 'true', '_data-container': '#popoverwrap' }), _id="popoverwrap") return SPAN(host_a, info_a)
def build_graphics(self): if self.reference: m_ = self.reference m = self.adapt(m_) else: m = self.adapt(self.info) ul = UL(_class="brewer") if m.resolution: ul.append( A(IMG(_alt=m.resolution, _src=URL('static', 'images/flagging/video/%s.png' % m.resolution, extension=False))) ) if m.videocodec: ul.append( A(IMG(_alt=m.videocodec, _src=URL('static', 'images/flagging/video/%s.png' % m.videocodec, extension=False))) ) if m.audiocodec: ul.append( A(IMG(_alt=m.audiocodec, _src=URL('static', 'images/flagging/audio/%s.png' % m.audiocodec, extension=False))) ) if m.channels: ul.append( A(IMG(_alt=m.channels, _src=URL('static', 'images/flagging/audio/%s.png' % m.channels, extension=False))) ) if m.aspect: ul.append( A(IMG(_alt=m.aspect, _src=URL('static', 'images/flagging/aspectratio/%s.png' % m.aspect, extension=False))) ) #if m.length: # ul.append( # H5(m.length) # ) return ul
def __init__(self, **attributes): """ Init """ self.components = [] self.attributes = attributes self.cssbase = URL('static', 'plugins/dropdown/dropdown.css') self.csstheme = URL('static', 'plugins/dropdown/themes/skeleton.css') self.root = MenuRoot()
def contact(): from models.contact import Contact db = application.db(models=[Contact]) form = SQLFORM(db.Contact, _action=URL('experiments', 'default', 'contact')) if form.process(session=application.session).accepted: redirect(URL()) return {'form': form}
def test_StaticURL(self): # test response.static_version coupled with response.static_version_urls self.assertEqual(URL('a', 'c', 'f'), '/a/c/f') self.assertEqual(URL('a', 'static', 'design.css'), '/a/static/design.css') response = Storage() response.static_version = '1.2.3' from gluon.globals import current current.response = response self.assertEqual(URL('a', 'static', 'design.css'), '/a/static/design.css') response.static_version_urls = True self.assertEqual(URL('a', 'static', 'design.css'), '/a/static/_1.2.3/design.css')
def file_upload(): form = SQLFORM.factory(Field('file', 'upload', uploadfolder=application.config.upload_folder, requires=IS_IMAGE(extensions=('jpg', 'jpeg'))), _action=URL()) if form.process().accepted: redirect(URL()) return {'form': form}
def handleQueryForTableView(session, request, db, def_orderby, query, selectArgs, step=5, doCount=True, **args): if request.vars.start: start = int(request.vars.start) else: start = 0 stop = start + step nrows = None rows = [] orderby = request.vars.orderby if orderby: if orderby[0] == '~': orderby = '~db.' + orderby[1:] else: orderby = 'db.' + orderby #if orderby == session.last_orderby: # if orderby[0] == '~': orderby = orderby[1:] # else: orderby = '~' + orderby else: orderby = def_orderby session.last_orderby = orderby if doCount: nrows = db(*query).count() if orderby: args.update(dict(orderby=eval(orderby), limitby=(start, stop))) else: args.update(dict(limitby=(start, stop))) rows = db(*query).select(*selectArgs, **args) orderby = re.sub("db\.", "", orderby) prevLink = A( 'prev %d rows' % step, #% ((start-step if start-step>0 else 0),(start-step if start-step>0 else 0)+step), _href=URL(r=request, vars=dict(orderby=orderby, start=max( start - step, 0)))) if start > 0 else None nextLink = A( 'next %d rows' % step, #((start+step),(start+step+step)), _href=URL(r=request, vars=dict( orderby=orderby, start=start + step))) if (stop < nrows) | (nrows == None) else None return dict(records=rows, prevLink=prevLink, nextLink=nextLink, nrows=nrows, start=start, stop=stop)
def edit(): form = SQLFORM.factory( Field('first_name', 'string', requires=IS_NOT_EMPTY(error_message='Please enter first name')), Field('last_name', 'string', requires=IS_NOT_EMPTY(error_message='Please enter last name')), _action=URL('experiments', 'default', 'edit')) if form.process(session=application.session).accepted: redirect(URL()) return {'form': form}
def index(): response.view = 'nas/index.html' response.subtitle = T("Home") gform = DIV( P("Nervatura NAS Admin", _style="font-weight: bold;"), P(SPAN(T("Username: "******"font-weight: bold;"), session.auth.user.username), P(SPAN("Ver.No: " + response.verNo, _class="vernum")), TABLE( TR( TD(IMG(_style="vertical-align: bottom;", _src=URL('static', 'images/icon64_ntura_te.png')), _style="width: 64px;padding-right: 0px;"), TD("OPEN SOURCE", BR(), "BUSINESS", BR(), "MANAGEMENT", _style= "width: 120px;color: #616161;vertical-align: middle;font-size: 13px;" ))), P( A("©2011-2015 Nervatura Framework", _href="http://www.nervatura.com", _target="_blank", _title="Nervatura", _style="font-weight: bold;")), _align="center", _style="padding-top:30px;") return dict(form=gform)
def make_adder(self, wrappername, linktable): '''Build link for adding a new entry to the linked table''' try: attrs = { '_href': URL('plugin_ajaxselect', 'linked_create_form.load', args=self.uargs, vars=self.uvars) } adder = MODAL( u'\u200B', 'Add new {} item'.format(self.linktable), 'Content', trigger_classes='add_trigger badge badge-success icon-plus', trigger_type='link', modal_classes='plugin_ajaxselect modal_adder', attributes=attrs, id='{}_adder'.format(wrappername)) add_trigger = adder[0] add_modal = adder[1] return add_trigger, add_modal except Exception: print 'error in make_adder' print traceback.format_exc(5)
def get_sidebar_tags(self): # Kids, never use code to generate html. Having said that, here we go start_px = 22 cnt = 0 bold_toggle = True tag_cnt = self.db.question_tags.id.count() tags = self.db(self.db.tags.id == self.db.question_tags.tag_id).select( self.db.tags.tagname, tag_cnt, groupby=self.db.tags.id, orderby=~tag_cnt, limitby=(0, 12)) html = '' for tag in tags: tagname = tag.tags.tagname tag_cnt = tag['COUNT(question_tags.id)'] if bold_toggle: html_stub = 'font-weight:bold;' bold_toggle = False else: html_stub = '' bold_toggle = True url = URL(r=self.request, c='default', f='index', args=['tags'], vars=dict(tag=tagname)) html += '<span style="font-size:%spx;%s">\ <a href="%s" title=""\ >%s</a></span>  \n' % (start_px, html_stub, url, tagname) if cnt % 2: start_px -= 2 cnt += 1 return html
def wrapper(): " Add X-Pingback HTTP Header to decorated function's response " url_base = '%(wsgi_url_scheme)s://%(http_host)s' % request.env url_path = URL(args=['x-pingback']) response.headers['X-Pingback'] = url_base + url_path return controller()
def translate(): return FORM(SELECT( _id="translate", _onchange="document.location='%s?_language='+jQuery(this).val()" \ % URL(r=request,args=request.args), value=session._language, *[OPTION(k,_value=v) for v,k in languages]))
def get_table(request): db = get_database(request) if len(request.args) > 1 and request.args[1] in db.tables: return (db, request.args[1]) else: session.flash = T('invalid request') redirect(URL('index'))
def _make_refresher(self, wrappername, linktable, uargs, uvars): ''' Return link to refresh this widget via ajax. The widget is always created, since its href attribute is used to pass several values to the client-side javascripts. If the widget is instantiated with the 'refresher' parameter set to False, then the link is hidden via CSS. ''' refresher_id = '{}_refresh_trigger'.format(linktable) # prepare to hide 'refresh' button via CSS if necessary rstyle = '' if self.refresher in (False, 'False'): rstyle = 'display:none' comp_url = URL('plugin_ajaxselect', 'get_values', args=self.uargs, vars=self.uvars) ajs = 'ajax("{url}", ["{n}"], "{wn}"); ' \ 'return false;'.format(url=comp_url, wn=self.wrappername, n=self.fieldset[1]) refresh_link = A(SPAN(_class='glyphicon glyphicon-refresh'), _onclick=ajs, _href=comp_url, _id=refresher_id, _class='refresh_trigger badge badge-info ', _style=rstyle) return refresh_link
def f(*args, **kwargs): if not self.has_role(roles): return redirect( URL(r=self.request, c='members', f='login', vars=dict(err='needrole'))) return func(*args, **kwargs)
def f(*args, **kwargs): if not self.is_auth(): return redirect( URL(r=self.request, c='members', f='login', vars=dict(err='needlogin'))) return func(*args, **kwargs)
def generate_links(self): self.backward = A( '<< previous()', _href=URL(r=self.r, args=self.r.args, vars={'p': self.current - self.display_count })) if self.current else '<< previous(False)' self.forward = A( 'next() >>', _href=URL(r=self.r, args=self.r.args, vars={'p': self.current + self.display_count}) ) if self.total_results > self.current + self.display_count else 'next(False) >>' self.location = 'Showing %d to %d out of %d records' % ( self.current + 1, self.current + self.num_results, self.total_results) return (self.backward, self.forward, self.location)
def __call__(self): gtable = current.s3db.gis_location syria = current.db(gtable.name == "Syrian Arab Republic").select(gtable.id, limitby=(0, 1) ).first() redirect(URL(c="gis", f="location", args=[syria.id, "profile"]))
def qc_list(): if 'flash' in request.vars: response.flash= request.vars['flash'] if not db(db.episode.created_by == auth.user.id).count()>0: message= "You do not have any QC. Upload a QC first ;)" redirect(URL('default','add_qc?flash='+message)) else: return locals()
def _URL(*args, **kwargs): if kwargs.has_key('r'): r = kwargs['r'] del kwargs['r'] else: r = request return URL(r=r, *args, **kwargs)
def __init__(self, ref_field, configuration={'*': ''}, minchar=2, max_item_length=40, text_confirm_empty_form_field=None, **attributes): # reference field (table we will query to autocomplete) self.ref_field = ref_field # minimum characters to start autocompletion self.minchar = minchar # max suggestions displayed self.max_item_length = max_item_length # a dictionary containing configuration options self.configuration = configuration # an uid to identify the widget self.uid = uuid4().hex # widget images self.image_insert_url = URL('static', 'images/cmw_insert.png') self.image_select_url = URL('static', 'images/cmw_select.png') self.image_delete_url = URL('static', 'images/cmw_delete.png') self.image_disable_url = URL('static', 'images/field_disable.png') # widget strings self.text_confirm_empty_form_field = current.T( u'confirm empty field' ) if text_confirm_empty_form_field is None else text_confirm_empty_form_field self.text_delete = current.T(u'delete item') self.text_no_item_selected = current.T(u'no item selected') self.text_item_already_selected = current.T(u'item already selected') self.text_submit = current.T(u'submit') self.text_close_list = current.T(u'close list') # other attributes self.attributes = attributes if '_class' not in attributes.keys(): self.attributes['_class'] = 'not_required' mylogger.debug(message='ref_field._tablename:%s' % (str(ref_field._tablename))) mylogger.debug(message='ref_field.name:%s' % (str(ref_field.name))) mylogger.debug(message='ref_field.type:%s' % (str(ref_field.type)))
def install(self): """ Load need it to run """ response = current.response response.files.append( URL('static', 'plugins/colorbox/js/jquery.colorbox-min.js')) response.files.append(self.css_theme) return self
def buttonsDownload(buttons): ret = '' if buttons: for button in buttons: ret += ((' ' if not ret else ' ') + str(A(button[0], _class='button', _href=URL(button[1])))) return ret
def getAppl(): if request.vars.appl: file_name = os.path.join(request.folder, 'static/resources/application', str(request.vars.appl)) if not os.path.isfile(file_name): return "Missing application!" redirect(URL('static/resources/application', str(request.vars.appl))) else: return "Missing appl parameter!"
def index(): response.title=T('NDI Wizard') response.subtitle=T('Data Interface Wizard') lst_nom = ["address","barcode","contact","currency","customer","deffield","employee","event","fieldvalue","groups","item","link", "log","movement","numberdef","pattern","payment","place","price","product","project","rate","tax","tool","trans","sql"] response.lst_nom = SELECT(*[OPTION(str(nom).upper(), _value=nom) for nom in lst_nom], _id="lst_nom", _size=len(lst_nom),_style="width: 100%;font-weight: bold;", _onchange="changeItem();setLabels(this.value.toUpperCase()+'" +T(" fieldname and type values")+"','"+URL('ndr','getResource')+"?file_name=docs/ndi/ndi&content=view&lang=auto#'+this.value+'_fields');") return dict()