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 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 CONFIRM_BOX(request, session, title="Delete Record", label="Are you sure you want to delete this record?", content="", func_yes=lambda v: v, func_no=lambda v: v): form = FORM( DIV( P(LABEL(label), _class="centered"), P(BUTTON("Yes", _type="submit", _name="yes", _value="yes"), _class="centered"), P(BUTTON("No", _type="submit", _name="no", _value="no"), _class="centered"), )) html = DIV( H2(title), DIV(DIV(form, P(content), _id="padding"), _id="user_action"), ) if form.accepts(request.vars, session): if request.vars.yes == "yes": func_yes() else: func_no() elif form.errors: response.flash = "There were errors with the form" return html
def createDatabase(): if session.auth.user.username == "demo": return P( SPAN(T("Demo user: This action is not allowed!"), _style="color:red;")) if request.vars.alias == None: return str(T("Error: Missing alias parameter!")) return P(dbtool.createDatabase(request.vars.alias))
def create_db(): response.subtitle = T("Database Creation") response.view = 'nas/index.html' alias = db( (db.databases.deleted == False)).select(db.databases.id, db.databases.alias, orderby=db.databases.alias) cmb_alias = SELECT( *[OPTION(field["alias"], _value=field["alias"]) for field in alias], _id="cmb_alias", _style="margin-top: 0px;") if len(cmb_alias) == 0: cmb_alias.insert(0, OPTION("", _value="")) gform = DIV( HR(), P(SPAN(T('1. Create a new database alias. See ')), A("Customer Databases", _href=URL("databases"), _style="color:#0069D6;font-style: italic;"), BR(), SPAN( T('2. The sqlite and Google SQL databases are created automatically.' )), BR(), SPAN( T('3. Other types of databases must be created manually before.') ), BR(), SPAN(T('4. Please select an alias, and start the creation:')), _style="font-style: italic;"), DIV( SPAN(T('Database alias:'), _style="padding-right: 15px;padding-left: 15px;"), cmb_alias, P(SPAN(T('Starting the process?'), _id="msg_result", _style="font-style: italic;"), ui.control.get_mobil_button(label=T("Start"), href="#", onclick="createDatabase();", cformat=None, icon="check", theme="b", style="width: 100px;"), _style="padding-top: 0px;")), HR(), _style="font-weight: bold;", _align="left") return dict(form=gform)
def test_DIV(self): # Empty DIV() self.assertEqual(DIV().xml(), b'<div></div>') self.assertEqual(DIV('<>', _a='1', _b='2').xml(), b'<div a="1" b="2"><></div>') # attributes can be updated like in a dict div = DIV('<>', _a='1') div['_b'] = '2' self.assertEqual(div.xml(), b'<div a="1" b="2"><></div>') # also with a mapping div.update(_b=2, _c=3) self.assertEqual(div.xml(), b'<div a="1" b="2" c="3"><></div>') # length of the DIV is the number of components self.assertEqual(len(DIV('a', 'bc')), 2) # also if empty, DIV is True in a boolean evaluation self.assertTrue(True if DIV() else False) # parent and siblings a = DIV(SPAN('a'), DIV('b')) s = a.element('span') d = s.parent d['_class'] = 'abc' self.assertEqual(a.xml(), b'<div class="abc"><span>a</span><div>b</div></div>') self.assertEqual([el.xml() for el in s.siblings()], [b'<div>b</div>']) self.assertEqual(s.sibling().xml(), b'<div>b</div>') # siblings with wrong args self.assertEqual(s.siblings('a'), []) # siblings with good args self.assertEqual(s.siblings('div')[0].xml(), b'<div>b</div>') # Check for siblings with wrong kargs and value self.assertEqual(s.siblings(a='d'), []) # Check for siblings with good kargs and value # Can't figure this one out what is a right value here?? # Commented for now... # self.assertEqual(s.siblings(div='<div>b</div>'), ???) # No other sibling should return None self.assertEqual(DIV(P('First element')).element('p').sibling(), None) # -------------------------------------------------------------------------------------------------------------- # This use unicode to hit xmlescape() line : # """ # elif isinstance(data, unicode): # data = data.encode('utf8', 'xmlcharrefreplace') # """ self.assertEqual(DIV(u'Texte en français avec des caractères accentués...').xml(), b'<div>Texte en fran\xc3\xa7ais avec des caract\xc3\xa8res accentu\xc3\xa9s...</div>') # -------------------------------------------------------------------------------------------------------------- self.assertEqual(DIV('Test with an ID', _id='id-of-the-element').xml(), b'<div id="id-of-the-element">Test with an ID</div>') self.assertEqual(DIV().element('p'), None) # Corner case for raise coverage of one line # I think such assert fail cause of python 2.6 # Work under python 2.7 # with self.assertRaises(SyntaxError) as cm: # DIV(BR('<>')).xml() # self.assertEqual(cm.exception[0], '<br/> tags cannot have components') # test .get('attrib') self.assertEqual(DIV('<p>Test</p>', _class="class_test").get('_class'), 'class_test')
def _inner(form, fields): form.add_class('form-horizontal') label_col_class = "col-sm-%d" % col_label_size col_class = "col-sm-%d" % (12 - col_label_size - col_help_size) col_class_rest = "col-sm-%d" % (12 - col_label_size) offset_class = "col-sm-offset-%d" % col_label_size help_class = "col-sm-%d" % col_help_size parent = CAT() for id, label, controls, help in fields: # wrappers _help = DIV(SPAN(help, _class='help-block'), _class="%s" % (help_class)) # embed _help into _controls _controls = DIV(controls, _class="%s" % (col_class)) if isinstance(controls, INPUT): if controls['_type'] == 'submit': controls.add_class('btn btn-primary') _controls = DIV(DIV(controls, _class="btn-group-sm"), _class="%s %s" % (col_class_rest, offset_class)) if controls['_type'] == 'button': controls.add_class('btn btn-default') elif controls['_type'] == 'file': controls.add_class('input-file') controls.add_class(input_class) elif controls['_type'] in ('text', 'password'): controls.add_class('form-control') controls.add_class(input_class) elif controls['_type'] == 'checkbox': label['_for'] = None label.insert(0, controls) label.insert(1, ' ') _controls = DIV(DIV(label, _class="checkbox"), _class="%s %s" % (offset_class, col_class)) label = '' elif isinstance(controls, (SELECT, TEXTAREA)): controls.add_class('form-control') controls.add_class(input_class) elif isinstance(controls, SPAN): _controls = P(controls.components, _class="form-control-static %s" % col_class) elif isinstance(controls, UL): for e in controls.elements("input"): e.add_class('form-control') else: _controls = DIV(controls, _class="small %s" % (col_class)) if isinstance(label, LABEL): label['_class'] = add_class( label.get('_class'), '%s %s' % (control_label, label_col_class)) parent.append(DIV(label, _controls, _help, _class='row', _id=id)) return DIV(parent, _class='form-group')
def test_BEAUTIFY(self): #self.assertEqual(BEAUTIFY(['a', 'b', {'hello': 'world'}]).xml(), # '<div><table><tr><td><div>a</div></td></tr><tr><td><div>b</div></td></tr><tr><td><div><table><tr><td style="font-weight:bold;vertical-align:top;">hello</td><td style="vertical-align:top;">:</td><td><div>world</div></td></tr></table></div></td></tr></table></div>') # unicode self.assertEqual( BEAUTIFY([P(u'àéèûôç'), 'a', 'b', { 'hello': 'world' }]).xml(), b'<div><table><tr><td><div><p>\xc3\xa0\xc3\xa9\xc3\xa8\xc3\xbb\xc3\xb4\xc3\xa7</p></div></td></tr><tr><td><div>a</div></td></tr><tr><td><div>b</div></td></tr><tr><td><div><table><tr><td style="font-weight:bold;vertical-align:top;">hello</td><td style="vertical-align:top;">:</td><td><div>world</div></td></tr></table></div></td></tr></table></div>' )
def custom_formstyle(form, fields): col_label_size = 4 label_col_class = "col-sm-%d" % col_label_size col_class = "col-sm-%d" % (12 - col_label_size) offset_class = "col-sm-offset-%d" % col_label_size parent = TABLE(_class='table table-sm', _style='margin-top: 1.5rem') for id, label, controls, help in fields: # wrappers _help = SPAN(help, _class='help-block') # embed _help into _controls _controls = DIV(controls, _help, _class="%s" % (col_class)) if isinstance(controls, INPUT): if controls['_type'] == 'submit': controls.add_class('btn btn-primary') _controls = DIV(controls, _class="%s %s" % (col_class, offset_class)) if controls['_type'] == 'button': controls.add_class('btn btn-secondary') elif controls['_type'] == 'file': controls.add_class('input-file') elif controls['_type'] in ('text', 'password'): controls.add_class('form-control') elif controls['_type'] == 'checkbox' or controls[ '_type'] == 'radio': controls.add_class('form-check-input') label.add_class('form-check-label') label.insert(0, controls) _controls = DIV(DIV(label, _help, _class="form-check"), _class="%s" % col_class) label = DIV(_class="sm-hidden %s" % label_col_class) elif isinstance(controls, SELECT): controls.add_class('custom-select') elif isinstance(controls, TEXTAREA): controls.add_class('form-control') elif isinstance(controls, SPAN): _controls = P(controls.components, _class="form-control-plaintext %s" % col_class) elif isinstance(controls, UL): for e in controls.elements("input"): e.add_class('form-control') elif isinstance(controls, CAT) and isinstance(controls[0], INPUT): controls[0].add_class('form-control') if isinstance(label, LABEL): label.add_class('form-control-label font-weight-bold %s' % label_col_class) parent.append(DIV(label, _controls, _class='form-group row', _id=id)) return parent
def mybootstrap(form, fields): ''' bootstrap format form layout ''' form.add_class('form-horizontal') parent = FIELDSET() for id, label, controls, help in fields: # wrappers _help = None if help: _help = SPAN(help, _class='help-block') if isinstance(controls, (str, int, SPAN)): controls = P(controls, _class="form-control-static") # submit unflag by default _submit = False if isinstance(controls, INPUT): if controls['_type'] == 'submit': # flag submit button _submit = True controls['_class'] = 'btn btn-primary' if controls['_type'] == 'file': controls['_class'] = 'input-file' if isinstance(label, LABEL): label['_class'] = 'col-sm-2 control-label' if _submit: # submit button has unwrapped label and controls, different class parent.append(DIV(DIV(controls,_class="col-sm-offset-2 col-sm-10"), _class='form-group form-group-sm', _id=id)) # unflag submit (possible side effect) _submit = False else: # unwrapped label if _help: parent.append(DIV(label, DIV(controls, _help, _class="col-sm-10"), _class='form-group form-group-sm', _id=id)) else: parent.append(DIV(label, DIV(controls, _class="col-sm-10"), _class='form-group form-group-sm', _id=id)) return parent
def __call__(self): output = {} T = current.T request = current.request response = current.response s3 = response.s3 # Check logged in and permissions auth = current.auth settings = current.deployment_settings roles = current.session.s3.roles system_roles = auth.get_system_roles() AUTHENTICATED = system_roles.AUTHENTICATED # Login/Registration forms self_registration = current.deployment_settings.get_security_registration_visible( ) registered = False login_form = None login_div = None register_form = None register_div = None # Contact Form request_email = settings.get_frontpage("request_email") if request_email: from s3dal import Field from gluon.validators import IS_NOT_EMPTY from gluon.sqlhtml import SQLFORM fields = [ Field( "name", label="Your name", requires=IS_NOT_EMPTY(), ), Field( "address", label="Your e-mail address", requires=IS_NOT_EMPTY(), ), Field( "subject", label="Subject", requires=IS_NOT_EMPTY(), ), Field( "message", "text", label="Message", requires=IS_NOT_EMPTY(), ), ] from s3 import s3_mark_required labels, required = s3_mark_required(fields) s3.has_required = required response.form_label_separator = "" contact_form = SQLFORM.factory( formstyle=settings.get_ui_formstyle(), submit_button=T("Submit"), labels=labels, separator="", table_name="contact", # Dummy table name _id="mailform", *fields) if contact_form.accepts(request.post_vars, current.session, formname="contact_form", keepvalues=False, hideerror=False): # Processs Contact Form form_vars = contact_form.vars sender = "%s <%s>" % (form_vars.name, form_vars.address) result = current.msg.send_email( to=request_email, sender=sender, subject=form_vars.subject, message=form_vars.message, reply_to=form_vars.address, ) if result: response.confirmation = "Thank you for your message - we'll be in touch shortly" if s3.cdn: if s3.debug: s3.scripts.append( "http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js" ) else: s3.scripts.append( "http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js" ) else: if s3.debug: s3.scripts.append("/%s/static/scripts/jquery.validate.js" % request.application) else: s3.scripts.append( "/%s/static/scripts/jquery.validate.min.js" % request.application) validation_script = ''' $('#mailform').validate({ errorClass:'req', rules:{ name:{ required:true }, address: { required:true, email:true }, subject:{ required:true }, message:{ required:true } }, messages:{ name:"Enter your name", subject:"Enter a subject", message:"Enter a message", address:{ required:"Please enter a valid email address", email:"Please enter a valid email address" } }, errorPlacement:function(error,element){ error.appendTo(element.parents('div.controls')) }, submitHandler:function(form){ form.submit() } })''' s3.jquery_ready.append(validation_script) else: contact_form = "" if AUTHENTICATED not in roles: login_buttons = DIV(A(T("Login"), _id="show-login", _class="tiny secondary button"), _id="login-buttons") script = ''' $('#show-mailform').click(function(e){ e.preventDefault() $('#intro').slideDown(400, function() { $('#login_box').hide() }); }) $('#show-login').click(function(e){ e.preventDefault() $('#login_form').show() $('#register_form').hide() $('#login_box').show() $('#intro').slideUp() })''' s3.jquery_ready.append(script) # This user isn't yet logged-in if "registered" in request.cookies: # This browser has logged-in before registered = True if self_registration is True: # Provide a Registration box on front page login_buttons.append( A(T("Register"), _id="show-register", _class="tiny secondary button", _style="margin-left:5px")) script = ''' $('#show-register').click(function(e){ e.preventDefault() $('#login_form').hide() $('#register_form').show() $('#login_box').show() $('#intro').slideUp() })''' s3.jquery_ready.append(script) register_form = auth.register() register_div = DIV( H3(T("Register")), P( XML( T("If you would like to help, then please <b>sign up now</b>" )))) register_script = ''' $('#register-btn').click(function(e){ e.preventDefault() $('#register_form').show() $('#login_form').hide() }) $('#login-btn').click(function(e){ e.preventDefault() $('#register_form').hide() $('#login_form').show() })''' s3.jquery_ready.append(register_script) # Provide a login box on front page auth.messages.submit_button = T("Login") login_form = auth.login(inline=True) login_div = DIV( H3(T("Login")), P( XML( T("Registered users can <b>login</b> to access the system" )))) else: login_buttons = "" output["login_buttons"] = login_buttons output["self_registration"] = self_registration output["registered"] = registered output["login_div"] = login_div output["login_form"] = login_form output["register_div"] = register_div output["register_form"] = register_form output["contact_form"] = contact_form # Slick slider if s3.debug: s3.scripts.append("/%s/static/scripts/slick.js" % request.application) else: s3.scripts.append("/%s/static/scripts/slick.min.js" % request.application) script = ''' $(document).ready(function(){ $('#title-image').slick({ autoplay:true, autoplaySpeed:5000, speed:1000, fade:true, cssEase:'linear' }); });''' s3.jquery_ready.append(script) s3.stylesheets.append("../themes/%s/homepage.css" % THEME) self._view(THEME, "index.html") return output
def test_P(self): self.assertEqual( P('<>', _a='1', _b='2').xml(), b'<p a="1" b="2"><></p>') # test cr2br self.assertEqual(P('a\nb').xml(), b'<p>a\nb</p>') self.assertEqual(P('a\nb', cr2br=True).xml(), b'<p>a<br />b</p>')
def rdrt_member_profile_header(r): """ Custom profile header to allow update of RDRT roster status """ record = r.record if not record: return "" person_id = record.person_id from s3 import s3_fullname, s3_avatar_represent name = s3_fullname(person_id) table = r.table # Organisation comments = table.organisation_id.represent(record.organisation_id) from s3 import s3_unicode from gluon.html import A, DIV, H2, LABEL, P, SPAN # Add job title if present job_title_id = record.job_title_id if job_title_id: comments = (SPAN("%s, " % \ s3_unicode(table.job_title_id.represent(job_title_id))), comments) # Determine the current roster membership status (active/inactive) atable = current.s3db.deploy_application status = atable.active query = atable.human_resource_id == r.id row = current.db(query).select(atable.id, atable.active, limitby=(0, 1)).first() if row: active = 1 if row.active else 0 status_id = row.id roster_status = status.represent(row.active) else: active = None status_id = None roster_status = current.messages.UNKNOWN_OPT if status_id and \ current.auth.s3_has_permission("update", "deploy_application", record_id=status_id): # Make inline-editable roster_status = A(roster_status, data = {"status": active}, _id = "rdrt-roster-status", _title = T("Click to edit"), ) s3 = current.response.s3 script = "/%s/static/themes/IFRC/js/rdrt.js" % r.application if script not in s3.scripts: s3.scripts.append(script) script = '''$.rdrtStatus('%(url)s','%(active)s','%(inactive)s','%(submit)s')''' from gluon import URL options = {"url": URL(c="deploy", f="application", args=["%s.s3json" % status_id]), "active": status.represent(True), "inactive": status.represent(False), "submit": T("Save"), } s3.jquery_ready.append(script % options) else: # Read-only roster_status = SPAN(roster_status) # Render profile header return DIV(A(s3_avatar_represent(person_id, tablename="pr_person", _class="media-object", ), _class="pull-left", ), H2(name), P(comments), DIV(LABEL(status.label + ": "), roster_status), _class="profile-header", )
def __call__(self): output = {} T = current.T request = current.request response = current.response s3 = response.s3 # Check logged in and permissions auth = current.auth settings = current.deployment_settings roles = current.session.s3.roles system_roles = auth.get_system_roles() AUTHENTICATED = system_roles.AUTHENTICATED # Login/Registration forms self_registration = current.deployment_settings.get_security_registration_visible() registered = False login_form = None login_div = None register_form = None register_div = None if AUTHENTICATED not in roles: #login_buttons = DIV(A(T("Login"), # _id = "show-login", # _class = "tiny secondary button", # ), # _id = "login-buttons" # ) script = ''' $('#show-mailform').click(function(e){ e.preventDefault() $('#intro').slideDown(400, function() { $('#login_box').hide() }); }) $('#show-login').click(function(e){ e.preventDefault() $('#login_form').show() $('#register_form').hide() $('#login_box').show() $('#intro').slideUp() })''' s3.jquery_ready.append(script) # This user isn't yet logged-in if "registered" in request.cookies: # This browser has logged-in before registered = True if self_registration is True: # Provide a Registration box on front page #login_buttons.append(A(T("Register"), # _id = "show-register", # _class = "tiny secondary button", # _style = "margin-left:5px", # )) #script = ''' #$('#show-register').click(function(e){ # e.preventDefault() # $('#login_form').hide() # $('#register_form').show() # $('#login_box').show() # $('#intro').slideUp() #})''' #s3.jquery_ready.append(script) register_form = auth.register() register_div = DIV(H3(T("Register")), P(XML(T("If you would like to help, then please <b>sign up now</b>")))) register_script = ''' $('#register-btn').click(function(e){ e.preventDefault() $('#register_form').show() $('#login_form').hide() }) $('#login-btn').click(function(e){ e.preventDefault() $('#register_form').hide() $('#login_form').show() })''' s3.jquery_ready.append(register_script) # Provide a login box on front page auth.messages.submit_button = T("Login") login_form = auth.login(inline=True) login_div = DIV(H3(T("Login")), P(XML(T("Registered users can <b>login</b> to access the system")))) #else: # login_buttons = "" #output["login_buttons"] = login_buttons output["self_registration"] = self_registration output["registered"] = registered output["login_div"] = login_div output["login_form"] = login_form output["register_div"] = register_div output["register_form"] = register_form # Slick slider if s3.debug: s3.scripts.append("/%s/static/scripts/slick.js" % request.application) else: s3.scripts.append("/%s/static/scripts/slick.min.js" % request.application) script = ''' $(document).ready(function(){ $('#title-image').slick({ autoplay:true, autoplaySpeed:5000, speed:1000, fade:true, cssEase:'linear' }); });''' s3.jquery_ready.append(script) s3.stylesheets.append("../themes/%s/homepage.css" % THEME) self._view(THEME, "index.html") return output
def create_backup(): response.subtitle = T("Create a Backup") response.view = 'nas/index.html' alias = db( (db.databases.deleted == False)).select(db.databases.id, db.databases.alias, orderby=db.databases.alias) cmb_alias = SELECT( *[OPTION(field["alias"], _value=field["alias"]) for field in alias], _id="cmb_alias") if len(cmb_alias) == 0: cmb_alias.insert(0, OPTION("", _value="")) cmb_format = SELECT( [OPTION(T("backup"), _value="backup"), OPTION(T("XML"), _value="xml")], _id="cmb_format") if len(cmb_format) == 0: cmb_format.insert(0, OPTION("", _value="")) cmb_filename = SELECT([ OPTION(T("Alias"), _value=""), OPTION(T("Download"), _value="download"), OPTION(T("Custom"), _value="custom") ], _id="cmb_filename") if request.env.web2py_runtime_gae: cmb_filename = SELECT([OPTION(T("Download"), _value="download")], _id="cmb_filename") cust_filename = "" else: cust_filename = INPUT(_type="text", _value="", _id="cust_filename") gform = DIV( HR(), P( SPAN(T('Nervatura backup: '), _style="color:brown;"), BR(), SPAN(T('NOM objects: '), _style="color:green;"), SPAN( "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" ), BR(), SPAN(T('Settings objects: '), _style="color:green;"), SPAN("ui_audit, ui_language, \ ui_menu, ui_menufields, ui_message, ui_report, ui_reportfields, \ ui_reportsources, ui_userconfig"), BR(), SPAN(T('Not included: '), _style="color:red;"), SPAN("ui_printqueue"), BR(), BR(), SPAN(T( "Independent from the database type and version of the NAS server." ), _style="font-style: italic;")), DIV( DIV( SPAN(T('Database alias:'), _style="padding-right: 15px;padding-left: 15px;"), cmb_alias), DIV(SPAN(T('Filename:'), _style="padding-right: 15px;padding-left: 15px;"), cmb_filename, SPAN(" "), cust_filename, _style="padding-top: 10px;"), DIV(SPAN(T('Backup format:'), _style="padding-right: 15px;padding-left: 15px;"), cmb_format, _style="padding-top: 10px;"), P(SPAN(T('Starting the process?'), _id="msg_result", _style="font-style: italic;"), ui.control.get_mobil_button( label=T("Start"), href="#", onclick="createDataBackup();", cformat=None, icon="check", theme="b", style="width: 100px;", title=ns.T('Start customer backup creation')), _style="padding-top: 5px;")), HR(), _style="font-weight: bold;", _align="left") return dict(form=gform)
def ccache(): form = FORM( P(TAG.BUTTON("Clear CACHE?", _type="submit", _name="yes", _value="yes")), P(TAG.BUTTON("Clear RAM", _type="submit", _name="ram", _value="ram")), P(TAG.BUTTON("Clear DISK", _type="submit", _name="disk", _value="disk")), ) if form.accepts(request.vars, session): clear_ram = False clear_disk = False session.flash = "" if request.vars.yes: clear_ram = clear_disk = True if request.vars.ram: clear_ram = True if request.vars.disk: clear_disk = True if clear_ram: cache.ram.clear() session.flash += "Ram Cleared " if clear_disk: cache.disk.clear() session.flash += "Disk Cleared" redirect(URL(r=request)) try: from guppy import hpy hp = hpy() except ImportError: hp = False import shelve, os, copy, time, math from gluon import portalocker ram = { 'bytes': 0, 'objects': 0, 'hits': 0, 'misses': 0, 'ratio': 0, 'oldest': time.time() } disk = copy.copy(ram) total = copy.copy(ram) for key, value in cache.ram.storage.items(): if isinstance(value, dict): ram['hits'] = value['hit_total'] - value['misses'] ram['misses'] = value['misses'] try: ram['ratio'] = ram['hits'] * 100 / value['hit_total'] except (KeyError, ZeroDivisionError): ram['ratio'] = 0 else: if hp: ram['bytes'] += hp.iso(value[1]).size ram['objects'] += hp.iso(value[1]).count if value[0] < ram['oldest']: ram['oldest'] = value[0] locker = open(os.path.join(request.folder, 'cache/cache.lock'), 'a') portalocker.lock(locker, portalocker.LOCK_EX) disk_storage = shelve.open( os.path.join(request.folder, 'cache/cache.shelve')) try: for key, value in disk_storage.items(): if isinstance(value, dict): disk['hits'] = value['hit_total'] - value['misses'] disk['misses'] = value['misses'] try: disk['ratio'] = disk['hits'] * 100 / value['hit_total'] except (KeyError, ZeroDivisionError): disk['ratio'] = 0 else: if hp: disk['bytes'] += hp.iso(value[1]).size disk['objects'] += hp.iso(value[1]).count if value[0] < disk['oldest']: disk['oldest'] = value[0] finally: portalocker.unlock(locker) locker.close() disk_storage.close() total['bytes'] = ram['bytes'] + disk['bytes'] total['objects'] = ram['objects'] + disk['objects'] total['hits'] = ram['hits'] + disk['hits'] total['misses'] = ram['misses'] + disk['misses'] try: total['ratio'] = total['hits'] * 100 / (total['hits'] + total['misses']) except (KeyError, ZeroDivisionError): total['ratio'] = 0 if disk['oldest'] < ram['oldest']: total['oldest'] = disk['oldest'] else: total['oldest'] = ram['oldest'] def GetInHMS(seconds): hours = math.floor(seconds / 3600) seconds -= hours * 3600 minutes = math.floor(seconds / 60) seconds -= minutes * 60 seconds = math.floor(seconds) return (hours, minutes, seconds) ram['oldest'] = GetInHMS(time.time() - ram['oldest']) disk['oldest'] = GetInHMS(time.time() - disk['oldest']) total['oldest'] = GetInHMS(time.time() - total['oldest']) return dict(form=form, total=total, ram=ram, disk=disk)
def restore_backup(): response.subtitle = T("Restore the Customer Data") response.view = 'nas/index.html' msg_result = T('Starting the process?') if request.post_vars: if request.post_vars.alias == None or request.post_vars.alias == "": msg_result = T("Error: Missing alias parameter!") if request.post_vars.has_key("frm_file"): if request.post_vars.bfile == "": msg_result = T("Error: Missing upload file!") else: msg_result = dbtool.loadBackupData( alias=request.vars.alias, bfile=request.post_vars.bfile) else: if request.post_vars.filename == "": msg_result = T("Error: Missing upload filename!") else: msg_result = dbtool.loadBackupData( alias=request.vars.alias, filename=request.post_vars.filename) request.post_vars = None alias = db( (db.databases.deleted == False)).select(db.databases.id, db.databases.alias, orderby=db.databases.alias) cmb_alias = SELECT( *[OPTION(field["alias"], _value=field["alias"]) for field in alias], _name="alias", _id="cmb_alias") if len(cmb_alias) == 0: cmb_alias.insert(0, OPTION("", _value="")) dfiles = os.listdir(os.path.join(ns.request.folder, 'static/backup')) files = [] for dfile in dfiles: if str(dfile).endswith(".backup") or str(dfile).endswith(".xml"): files.append(dfile) files.sort() cmb_files = SELECT(*files, _id="cmb_files", _name="filename") if len(cmb_files) == 0: cmb_files.insert(0, OPTION("", _value="")) cmd_filename = INPUT( _type="submit", _name="frm_filename", _title=ns.T('Start restore from local backup file'), _value=T("Start restore"), _onclick="msg_result.innerHTML='" + T("Process started. Waiting for the server to respond ...") + "';") cmd_filename["_data-theme"] = "b" cmd_filename["_data-icon"] = "check" cmd_file = INPUT( _type="submit", _name="frm_file", _title=ns.T('Upload file and Start restore'), _value=T("Upload and Start restore"), _onclick="msg_result.innerHTML='" + T("Process started. Waiting for the server to respond ...") + "';") cmd_file["_data-theme"] = "b" cmd_file["_data-icon"] = "check" cmd_file["_data-ajax"] = "false" if request.env.web2py_runtime_gae: gform = DIV( HR(), P( SPAN( T('The sqlite and Google SQL databases are created automatically. Other types of databases must be created manually before.' ))), FORM(DIV( SPAN(T('Database alias:'), _style="padding-right: 15px;padding-left: 15px;"), cmb_alias), DIV(SPAN(T('File:'), _style="padding-right: 15px;padding-left: 15px;"), INPUT(_type='file', _name='bfile', _id='bfile', _requires=IS_NOT_EMPTY()), SPAN("", _style="padding-left: 15px;"), cmd_file, _style="padding-top: 8px;"), _id="frm_upload_files", _name="frm_upload", **{"_data-ajax": "false"}), P( SPAN(msg_result, _id="msg_result", _style= "padding-left: 15px;font-style: italic;padding-top: 5px;") ), HR(), _style="font-weight: bold;", _align="left") else: gform = DIV( HR(), P( SPAN( T('The sqlite and Google SQL databases are created automatically. Other types of databases must be created manually before.' ))), FORM(DIV( SPAN(T('Database alias:'), _style="padding-right: 15px;padding-left: 15px;"), cmb_alias), DIV(SPAN(T('Filename:'), _style="padding-right: 15px;padding-left: 15px;"), cmb_files, SPAN("", _style="padding-left: 15px;"), cmd_filename, _style="padding-top: 8px;"), DIV(SPAN(T('File:'), _style="padding-right: 15px;padding-left: 15px;"), INPUT(_type='file', _name='bfile', _id='bfile', _requires=IS_NOT_EMPTY()), SPAN("", _style="padding-left: 15px;"), cmd_file, _style="padding-top: 8px;"), _id="frm_upload_files", _name="frm_upload", **{"_data-ajax": "false"}), P( SPAN(msg_result, _id="msg_result", _style= "padding-left: 15px;font-style: italic;padding-top: 5px;") ), HR(), _style="font-weight: bold;", _align="left") return dict(form=gform)