class Mailer(Mail): def __init__(self): Mail.__init__(self) self.config = AppConfig() self.settings.tls = self.config.take('smtp.tls') self.settings.server = self.config.take('smtp.server') self.settings.sender = self.config.take('smtp.sender') if self.config.take('smtp.login'): self.settings.login = self.config.take('smtp.login') self.request = current.request
class Mailer(Mail): def __init__(self,): Mail.__init__(self) self.config = AppConfig() self.settings.tls = self.config.take("smtp.tls") self.settings.server = self.config.take("smtp.server") self.settings.sender = self.config.take("smtp.sender") if self.config.take("smtp.login"): self.settings.login = self.config.take("smtp.login") self.request = current.request def build_message_from_template(self, event_type, render_html=True, **kwargs): from gluon.html import XML from gluon.template import render path = self.request.folder + "/" + "private/email_templates/" + event_type + ".html" template = str(XML(open(path).read())) if not template: logger.warning( "App notification message, you need to define an email template for %s event \n %s" % (event_type, str(kwargs)) ) self.render = lambda text: render(text, context=dict(event_type=event_type, **kwargs)) try: if render_html: html_message = self.render(template) import html2text plain_message = html2text.html2text(html_message) except Exception as e: html_message = "" logger.warning("Render email template %s. Please, edit the email template carefully" % event_type) logger.warning(str(e)) return dict(message=[plain_message, html_message], reply_to=self.config.take("smtp.reply_to")) def send_email(self, to, subject, event_type, attachments=[], render_html=True, **kwargs): message = self.build_message_from_template(event_type, render_html, **kwargs) try: if attachments: attachment = [] for i in attachments: attachment.append(self.Attachment(i)) params = dict( to=to, subject=subject, attachments=attachment, bcc=self.config.take("smtp.bcc_to"), **message ) else: params = dict(to=to, subject=subject, bcc=self.config.take("smtp.bcc_to"), **message) sent = self.send(**params) except Exception, e: logger.error("Fail sending email to: %s" % to) logger.error(str(e)) sent = False return sent
def test_appconfig(self): """ Test for the appconfig module """ from gluon import current s = Storage({'application': 'admin', 'folder': 'applications/admin'}) current.request = s simple_config = '{"config1" : "abc", "config2" : "bcd", "config3" : { "key1" : 1, "key2" : 2} }' with open('appconfig.json', 'w') as g: g.write(simple_config) myappconfig = AppConfig('appconfig.json') self.assertEqual(myappconfig['config1'], 'abc') self.assertEqual(myappconfig['config2'], 'bcd') self.assertEqual(myappconfig.take('config1'), 'abc') self.assertEqual(myappconfig.take('config3.key1', cast=str), '1') # once parsed, can't be casted to other types self.assertEqual(myappconfig.take('config3.key1', cast=int), '1') self.assertEqual(myappconfig.take('config3.key2'), 2) current.request = {}
# -*- coding: utf-8 -*- __author__ = 'Naptin' if False: from gluon import * from datetime import date, datetime from gluon.tools import request,response, session, cache, DAL,Auth, Service, PluginManager #from gluon.tools import from gluon.contrib.appconfig import AppConfig myconf = AppConfig(reload=True) db = DAL(myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['all']) auth = Auth(db) service = Service() plugins = PluginManager() from db import * ## create all tables needed by auth if not custom tables #auth.define_tables(username=False, signature=False) from time import ctime db.define_table('rev_wallet', Field('revnumber', requires=IS_LENGTH(16, 16)), Field('month_issued', 'integer', requires=IS_INT_IN_RANGE(1, 12)), Field('year_issued', 'integer', requires=IS_INT_IN_RANGE(2015, 2099)), Field('month_expired', 'integer', requires=IS_INT_IN_RANGE(1, 12)), Field('year_expired', 'integer', requires=IS_INT_IN_RANGE(2015, 2099)), Field('amount', 'float'), ) db.define_table('device',
# -*- coding: utf-8 -*- ## if SSL/HTTPS is properly configured and you want all HTTP requests to ## be redirected to HTTPS, uncomment the line below: # request.requires_https() ## app configuration made easy. Look inside private/appconfig.ini from gluon.contrib.appconfig import AppConfig from images import THUMB ## once in production, remove reload=True to gain full speed myconf = AppConfig(reload=True) db = DAL(myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['all']) ## by default give a view/generic.extension to all actions from localhost ## none otherwise. a pattern can be 'controller/function.extension' response.generic_patterns = ['*'] if request.is_local else [] ## choose a style for forms response.formstyle = myconf.take( 'forms.formstyle') # or 'bootstrap3_stacked' or 'bootstrap2' or other response.form_label_separator = myconf.take('forms.separator') ## (optional) optimize handling of static files # response.optimize_css = 'concat,minify,inline' # response.optimize_js = 'concat,minify,inline' ## (optional) static assets folder versioning
# coding: utf8 from time import strptime,strftime,sleep from urllib import urlencode,urlretrieve import tmdbsimple as tmdb import os,cPickle import traceback from gluon.contrib.appconfig import AppConfig ## once in production, remove reload=True to gain full speed myconf = AppConfig(reload=False) tmdb.API_KEY = myconf.take('tmdb.key') #try: # apikey_filepath = os.path.join(request.folder, "private", "themoviedb.key") # with open(apikey_filepath, 'rb') as tmdb_api_keyfile: # TMDB_API_KEY = cPickle.load(tmdb_api_keyfile) #except: # logger.warning('Unable to load API key from %s' % apikey_filepath) #tmdb.API_KEY = TMDB_API_KEY def slugify(text): return IS_SLUG(check=False)(text.encode('utf-8'))[0] def add_person_to_db(name,tmdb_id): logger.debug('Adding %s to cast database' % name) try: p = db.moviecast.update_or_insert(nome=name,tmdb_id=tmdb_id,slug=slugify(name)) except: logger.error('Error %s to cast database' % name) return False
# -*- coding: utf-8 -*- # this file is released under public domain and you can use without limitations ######################################################################### ## This is a sample controller ## - index is the default action of any application ## - user is required for authentication and authorization ## - download is for downloading files uploaded in the db (does streaming) ######################################################################### if False: from gluon import * from gluon.tools import request, response, session, cache, Auth, DAL, Service, Crud, PluginManager from gluon.contrib.appconfig import AppConfig myconf = AppConfig(reload=True) db = DAL(myconf.take("db.uri"), pool_size=myconf.take("db.pool_size", cast=int), check_reserved=["all"]) # db = DAL('sqlite://storage.sqlite',pool_size=1,check_reserved=['all']) auth = Auth(db) service = Service() plugins = PluginManager() def index(): """ example action using the internationalization operator T and flash rendered by views/default/index.html or views/generic.html if you need a simple wiki simply replace the two lines below with: return auth.wiki() """
menu_lateral = MenuLateral(list()) menu_migas = MenuMigas() from gluon.storage import Storage from agiscore.gui.mic import Accion, grid_simple # TODO: remove response.menu = [] menu_lateral.append(Accion(T('Tipos de pagos'), URL('index'), True), ['index']) menu_lateral.append(Accion(T('Control de pagos'), URL('pagos'), auth.has_membership(role=myconf.take('roles.admin'))), ['pagos']) @auth.requires(auth.has_membership(role=myconf.take('roles.admin'))) def index(): C = Storage() C.escuela = db.escuela(1) menu_migas.append(T("Tipos de pagos")) C.titulo = T("Registro de tipos de pago") # permisos puede_editar = auth.has_membership(role=myconf.take('roles.admin')) # puede_borrar = auth.has_membership(role=myconf.take('roles.admin')) puede_crear = auth.has_membership(role=myconf.take('roles.admin'))
######################################################################### ## if SSL/HTTPS is properly configured and you want all HTTP requests to ## be redirected to HTTPS, uncomment the line below: # request.requires_https() ## app configuration made easy. Look inside private/appconfig.ini from gluon.contrib.appconfig import AppConfig ## once in production, remove reload=True to gain full speed myconf = AppConfig(reload=True) if not request.env.web2py_runtime_gae: ## if NOT running on Google App Engine use SQLite or other DB db = DAL( myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['all']) else: ## connect to Google BigTable (optional 'google:datastore://namespace') db = DAL('google:datastore+ndb') ## store sessions and tickets there session.connect(request, response, db=db) ## or store session in Memcache, Redis, etc. ## from gluon.contrib.memdb import MEMDB ## from google.appengine.api.memcache import Client ## session.connect(request, response, db = MEMDB(Client())) ## by default give a view/generic.extension to all actions from localhost ## none otherwise. a pattern can be 'controller/function.extension'
from gluon import * from gluon.tools import request, response, session, cache, DAL from gluon.contrib.appconfig import AppConfig myconf = AppConfig(reload=True) # db = DAL(myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['all']) db = DAL("sqlite://storage.sqlite", pool_size=1, check_reserved=["all"]) # from gluon.contrib.appconfig import AppConfig ## once in production, remove reload=True to gain full speed # myconf = AppConfig(reload=True) if not request.env.web2py_runtime_gae: ## if NOT running on Google App Engine use SQLite or other DB db = DAL(myconf.take("db.uri"), pool_size=myconf.take("db.pool_size", cast=int), check_reserved=["all"]) # db = DAL('sqlite://storage.sqlite',pool_size=1,check_reserved=['all']) else: ## connect to Google BigTable (optional 'google:datastore://namespace') db = DAL("google:datastore+ndb") ## store sessions and tickets there session.connect(request, response, db=db) ## or store session in Memcache, Redis, etc. ## from gluon.contrib.memdb import MEMDB ## from google.appengine.api.memcache import Client ## session.connect(request, response, db = MEMDB(Client())) ## by default give a view/generic.extension to all actions from localhost ## none otherwise. a pattern can be 'controller/function.extension' response.generic_patterns = ["*"] if request.is_local else [] ## choose a style for forms
# IAPT Spring Assessment - Group 13 from gluon.contrib.appconfig import AppConfig import re import os APP_NAME = 'Shortboxes' myconf = AppConfig(reload=True) # see private/appconfig.ini for settings # Set up the database db = DAL(myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['all']) # Set the response style for forms response.formstyle = myconf.take('forms.formstyle') response.form_label_separator = myconf.take('forms.separator') uploadfolder = os.path.join(request.folder, 'uploads') # Define a custom validator for currency values class IS_CURRENCY_VALUE(object): def __call__(self, value): error_str = 'Enter a currency value, e.g. "2.50"' if value is None or type(value) != str: return None, error_str regex = re.compile(r"^([0-9]+)(\.[0-9]{1,2})?$") match = regex.match(value)
http://..../[app]/default/user/login http://..../[app]/default/user/logout http://..../[app]/default/user/register http://..../[app]/default/user/profile http://..../[app]/default/user/retrieve_password http://..../[app]/default/user/change_password http://..../[app]/default/user/manage_users (requires membership in use @auth.requires_login() @auth.requires_membership('group name') @auth.requires_permission('read','table name',record_id) to decorate functions that need access control """ return dict(form=auth()) @auth.requires_membership(myconf.take("roles.admin")) def editar_persona(): """componente para la edición de los datos de una persona""" if not request.vars.persona_id: raise HTTP(404) from agiscore.gui import persona as p_gui p = db.persona(int(request.vars.persona_id)) c, f = p_gui.form_editar(p.uuid) if f.process().accepted: response.flash = T("Cambios guardados") response.js = "jQuery('#%s').get(0).reload()" % request.cid return dict(componente=c) @auth.requires_membership(myconf.take("roles.admin"))
## from google.appengine.api.memcache import Client ## session.connect(request, response, db = MEMDB(Client())) # so that modules can use it current.db = db current.gdb = gdb ## These are the site admins. site_admins = myconf.get('users.admins') current.site_admins = site_admins ## by default give a view/generic.extension to all actions from localhost ## none otherwise. a pattern can be 'controller/function.extension' response.generic_patterns = ['*'] if request.is_local else [] ## choose a style for forms response.formstyle = myconf.take( 'forms.formstyle') # or 'bootstrap3_stacked' or 'bootstrap2' or other response.form_label_separator = myconf.take('forms.separator') ## (optional) optimize handling of static files # response.optimize_css = 'concat,minify,inline' # response.optimize_js = 'concat,minify,inline' ## (optional) static assets folder versioning # response.static_version = '0.0.0' ######################################################################### ## Here is sample code if you need for ## - email capabilities ## - authentication (registration, login, logout, ... ) ## - authorization (role based authorization) ## - services (xml, csv, json, xmlrpc, jsonrpc, amf, rss) ## - old style crud actions ## (more options discussed in gluon/tools.py)
from ndsfunctions import generate_thumbnail filename = 'private/appconfig.ini' path = os.path.join(request.folder, filename) if os.path.exists(path): useappconfig = True else: useappconfig = False usecategory = True if useappconfig: from gluon.contrib.appconfig import AppConfig # once in production, remove reload=True to gain full speed myconf = AppConfig(reload=False) debug = myconf.take('developer.debug', cast=int) else: debug = False if not request.env.web2py_runtime_gae: if useappconfig: db = DAL(myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['all']) else: db = DAL('sqlite://storage.sqlite') else: db = DAL('google:datastore+ndb') # store sessions and tickets there session.connect(request, response, db=db) current.db = db
'Analytics', 'Sale orders', 'Stock transfers', 'Offers', 'Accounts payable', 'Accounts receivable', 'Highlights', 'Cash out', 'Product loss', 'Safe config' ] }) ], {}) ] WORKFLOW_DATA = get_workflows() # sale events SALE_DEFERED = 'defered' SALE_DELIVERED = 'delivered' SALE_CREATED = 'created' SALE_PAID = 'paid' BAG_ACTIVE = 0 BAG_COMPLETE = 1 BAG_FOR_ORDER = 2 BAG_ORDER_COMPLETE = 3 # cache names CACHED_POPULAR_ITEMS = 0 TAX_TRANSFER = 1 TAX_RETAIN = 2 STRIPE_PK = CONF.take('stripe.public_key') STRIPE_SK = CONF.take('stripe.secure_key')
### поэтому все операции с сессией в файле ниже ДБ ##if request.is_https: ## redirect(URL(args=request.args, vars=request.vars, scheme='http', host=True)) from gluon import current current.PARTNER_MIN = PARTNER_MIN = 10 PARTNER_GO = 77 CACHE_EXP_TIME = request.is_local and 5 or 360 ## app configuration made easy. Look inside private/appconfig.ini from gluon.contrib.appconfig import AppConfig ## once in production, remove reload=True to gain full speed myconf = AppConfig(reload=True) DEVELOP = myconf.take('app.develop', cast=bool) TO_BUY_ID = myconf.take('deals.buy') TO_WALLET_ID = myconf.take('deals.wallet') TO_COIN_ID = myconf.take('deals.coin') TO_PHONE7_ID = myconf.take('deals.phone_7') TRUST_IP = myconf.take('app.trust_ip') if DEVELOP: print '0.py - app.DEVELOP' current.IS_LOCAL = IS_LOCAL = request.is_local current.IS_MOBILE = IS_MOBILE = request.user_agent().is_mobile current.IS_TABLET = IS_TABLET = request.user_agent().is_tablet ADMIN = request.controller == 'appadmin' ##print ADMIN
# -*- coding: utf-8 -*- from gluon.tools import Auth from gluon.contrib.appconfig import AppConfig myconf = AppConfig(reload=True) DEVELOPMENT = myconf.take('app.development').lower() == 'true' AS_SERVICE = myconf.take('app.as_service').lower() == 'true' DEBUG_MODE = myconf.take('app.debug_mode').lower() == 'true' SCHEME = 'http' # if DEVELOPMENT else 'https' db = DAL(myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['all']) response.generic_patterns = [] response.formstyle = myconf.take( 'forms.formstyle') # or 'bootstrap3_stacked' or 'bootstrap2' or other response.form_label_separator = myconf.take('forms.separator') auth = Auth(db) ## configure email mail = auth.settings.mailer mail.settings.server = myconf.take('smtp.server') mail.settings.sender = myconf.take('smtp.sender') mail.settings.login = myconf.take('smtp.login') ## configure auth policy auth.settings.registration_requires_verification = not DEVELOPMENT
## app configuration made easy. Look inside private/appconfig.ini from gluon.contrib.appconfig import AppConfig ## once in production, remove reload=True to gain full speed myappconfig = AppConfig(reload=True) from gluon.tools import Auth, Service service = Service() response.generic_patterns = ["*"] if request.is_local else [] mode = myappconfig.take("ssis_dash.mode") response.formstyle = myappconfig.take("forms.formstyle") # or 'bootstrap3_stacked' or 'bootstrap2' or other response.form_label_separator = myappconfig.take("forms.separator") if mode == "protected": db = DAL(myappconfig.take("db.uri"), pool_size=myappconfig.take("db.pool_size", cast=int), check_reserved=["all"]) auth = Auth(db) ## create all tables needed by auth if not custom tables auth.define_tables(username=False, signature=False) ## configure email mail = auth.settings.mailer
# be redirected to HTTPS, uncomment the line below: # ------------------------------------------------------------------------- # request.requires_https() # ------------------------------------------------------------------------- # app configuration made easy. Look inside private/appconfig.ini # ------------------------------------------------------------------------- from gluon.contrib.appconfig import AppConfig # ------------------------------------------------------------------------- # once in production, remove reload=True to gain full speed # ------------------------------------------------------------------------- myconf = AppConfig(reload=True) GMAPKEY = myconf.get('google_maps.key') if myconf.take('site.require_https', cast=int): request.requires_https() if not request.env.web2py_runtime_gae: # --------------------------------------------------------------------- # if NOT running on Google App Engine use SQLite or other DB # --------------------------------------------------------------------- db = DAL(myconf.get('db.uri'), pool_size=myconf.get('db.pool_size'), migrate_enabled=myconf.get('db.migrate'), check_reserved=['all']) else: # --------------------------------------------------------------------- # connect to Google BigTable (optional 'google:datastore://namespace') # --------------------------------------------------------------------- db = DAL('google:datastore+ndb')
if not request.env.web2py_runtime_gae: # --------------------------------------------------------------------- # if NOT running on Google App Engine use SQLite or other DB # --------------------------------------------------------------------- ## if NOT running on Google App Engine use SQLite or other DB if web2pytest.is_running_under_test(request, request.application): # When running under test, db cannot be ':memory:' # because it is recreated in each request and a webclient test # can make many requests to validate a single scenario. db = DAL('sqlite://%s.sqlite' % request.application, folder=os.path.dirname(web2pytest.testfile_name()), pool_size=1, check_reserved=['all']) else: db = DAL('sqlite://api.sqlite', pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['all']) # # db = DAL(myconf.get('db.uri'), # pool_size=myconf.get('db.pool_size', cast=int), # check_reserved=['all']) else: # --------------------------------------------------------------------- # connect to Google BigTable (optional 'google:datastore://namespace') # --------------------------------------------------------------------- db = DAL('google:datastore+ndb') # --------------------------------------------------------------------- # store sessions and tickets there # --------------------------------------------------------------------- session.connect(request, response, db=db) # ---------------------------------------------------------------------
######################################################################### ## This scaffolding model makes your app work on Google App Engine too ## File is released under public domain and you can use without limitations ######################################################################### ## if SSL/HTTPS is properly configured and you want all HTTP requests to ## be redirected to HTTPS, uncomment the line below: # request.requires_https() ## get application configuration from gluon.contrib.appconfig import AppConfig ## once in production, remove reload=True to gain full speed concoct_conf = AppConfig(reload=True) db = DAL(concoct_conf.take('db.uri'), pool_size=concoct_conf.take('db.pool_size', cast=int), check_reserved=['all']) ## by default give a view/generic.extension to all actions from localhost ## none otherwise. a pattern can be 'controller/function.extension' #response.generic_patterns=['*.json'] response.generic_patterns = ['*'] if request.is_local else [] ## choose a style for forms response.formstyle = concoct_conf.take('forms.formstyle') # or 'bootstrap3_stacked' or 'bootstrap2' or other response.form_label_separator = concoct_conf.take('forms.separator') ## (optional) optimize handling of static files # response.optimize_css = 'concat,minify,inline' # response.optimize_js = 'concat,minify,inline' ## (optional) static assets folder versioning # response.static_version = '0.0.0'
## from google.appengine.api.memcache import Client ## session.connect(request, response, db = MEMDB(Client())) # so that modules can use it current.db = db current.gdb = gdb ## These are the site admins. site_admins = myconf.get('users.admins') current.site_admins = site_admins ## by default give a view/generic.extension to all actions from localhost ## none otherwise. a pattern can be 'controller/function.extension' response.generic_patterns = ['*'] if request.is_local else [] ## choose a style for forms response.formstyle = myconf.take('forms.formstyle') # or 'bootstrap3_stacked' or 'bootstrap2' or other response.form_label_separator = myconf.take('forms.separator') ## (optional) optimize handling of static files # response.optimize_css = 'concat,minify,inline' # response.optimize_js = 'concat,minify,inline' ## (optional) static assets folder versioning # response.static_version = '0.0.0' ######################################################################### ## Here is sample code if you need for ## - email capabilities ## - authentication (registration, login, logout, ... ) ## - authorization (role based authorization) ## - services (xml, csv, json, xmlrpc, jsonrpc, amf, rss) ## - old style crud actions ## (more options discussed in gluon/tools.py)
# ------------------------------------------------------------------------- # configure auth policy # ------------------------------------------------------------------------- auth.settings.registration_requires_verification = True auth.settings.registration_requires_approval = True auth.settings.reset_password_requires_verification = True auth.settings.login_url = URL('index') auth.settings.login_next = URL('redireccionando') # ------------------------------------------------------------------------- # Tipos de ingreso de estudiantes # ------------------------------------------------------------------------- # Lista de tipos de ingresos. TIPOS_INGRESO = myconf.take('tipos_estudiante') # ------------------------------------------------------------------------- # Define your tables below (or better in another model file) for example # # >>> db.define_table('mytable', Field('myfield', 'string')) # # Fields can be 'string','text','password','integer','double','boolean' # 'date','time','datetime','blob','upload', 'reference TABLENAME' # There is an implicit 'id integer autoincrement' field # Consult manual for more options, validators, etc. # # More API examples for controllers: # # >>> db.mytable.insert(myfield='value') # >>> rows = db(db.mytable.myfield == 'value').select(db.mytable.ALL)
## File is released under public domain and you can use without limitations ######################################################################### ## if SSL/HTTPS is properly configured and you want all HTTP requests to ## be redirected to HTTPS, uncomment the line below: # request.requires_https() ## app configuration made easy. Look inside private/appconfig.ini from gluon.contrib.appconfig import AppConfig ## once in production, remove reload=True to gain full speed myconf = AppConfig(reload=True) if not request.env.web2py_runtime_gae: ## if NOT running on Google App Engine use SQLite or other DB db = DAL(myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['all']) else: ## connect to Google BigTable (optional 'google:datastore://namespace') db = DAL('google:datastore+ndb') ## store sessions and tickets there session.connect(request, response, db=db) ## or store session in Memcache, Redis, etc. ## from gluon.contrib.memdb import MEMDB ## from google.appengine.api.memcache import Client ## session.connect(request, response, db = MEMDB(Client())) ## by default give a view/generic.extension to all actions from localhost ## none otherwise. a pattern can be 'controller/function.extension' response.generic_patterns = ['*'] if request.is_local else [] ## choose a style for forms response.generic_patterns = ['*']
from plugin_ckeditor import CKEditor # LOAD THE CONFIG to get DB and mail settings. This file is not under # version control, so can be different on production and development servers # once in production, remove reload=True to gain full speed myconf = AppConfig(reload=True) # ---------------------------------------------------------------------------- # DB connection definitions # -- both connections (local/remote) need to have a created database in order # to create and populate tables # ---------------------------------------------------------------------------- # PG setup db = DAL(myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), lazy_tables=False) # by default give a view/generic.extension to all actions from localhost # none otherwise. a pattern can be 'controller/function.extension' response.generic_patterns = ['*'] if request.is_local else [] # choose a style for forms response.formstyle = myconf.take('forms.formstyle') response.form_label_separator = myconf.take('forms.separator') # ---------------------------------------------------------------------------- # ENABLE AUTH # - authentication (registration, login, logout, ... ) # - authorization (role based authorization)
# -*- coding: utf-8 -*- from gluon.tools import Auth from gluon.tools import prettydate from gluon.contrib.appconfig import AppConfig # app configuration made easy. Look inside private/appconfig.ini # once in production, remove reload=True to gain full speed myconf = AppConfig(reload=True) db = DAL( myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['all'], migrate=myconf.take('db.migrate', cast=bool) ) response.formstyle = myconf.take('forms.formstyle') response.form_label_separator = myconf.take('forms.separator') # AUTH auth = Auth(db, controller='admin', function='user') # create all tables needed by auth if not custom tables auth.define_tables(username=False, signature=False) # configure auth policy auth.settings.registration_requires_verification = False auth.settings.registration_requires_approval = False auth.settings.reset_password_requires_verification = True
def loadAppConfig(self): myconf = AppConfig(reload=False) self.credentials['clientid'] = myconf.take('app.clientid') self.credentials['clientsecret'] = myconf.take('app.clientsecret')
from gluon.contrib.appconfig import AppConfig from cloudant import CouchDB app_conf = AppConfig(reload=False) COUCHDB_DATABASE = app_conf.take("monitutor_env.couchdb_database") COUCHDB_HOST = app_conf.take("monitutor_env.couchdb_host") COUCHDB_USERNAME = app_conf.take("monitutor_env.couchdb_username") COUCHDB_PASSWORD = app_conf.take("monitutor_env.couchdb_password") class ResultDatabase(): def __init__(self, couchdb_host, couchdb_database, couchdb_username, couchdb_password): self.couchdb = CouchDB(couchdb_username, couchdb_password, url=couchdb_host) self.couchdb_database = couchdb_database def _get_db_handle(self): self.couchdb.connect() return self.couchdb[self.couchdb_database] def _get_ddoc(self): couchdb_database = self._get_db_handle() return couchdb_database.get_design_document("results") def _get_result_history(self): result_ddoc = self._get_ddoc() return result_ddoc.get_view("check_result_history") def _get_results(self): result_ddoc = self._get_ddoc()
# -*- coding: utf-8 -*- from gluon.tools import Auth from gluon.contrib.appconfig import AppConfig myconf = AppConfig(reload=True) DEVELOPMENT = myconf.take('app.development').lower()=='true' AS_SERVICE = myconf.take('app.as_service').lower()=='true' DEBUG_MODE = myconf.take('app.debug_mode').lower()=='true' SCHEME = True if DEVELOPMENT else 'https' db = DAL(myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['all']) response.generic_patterns = [] response.formstyle = myconf.take('forms.formstyle') # or 'bootstrap3_stacked' or 'bootstrap2' or other response.form_label_separator = myconf.take('forms.separator') auth = Auth(db) ## configure email mail = auth.settings.mailer mail.settings.server = 'logging' if request.is_local else myconf.take('smtp.server') mail.settings.sender = myconf.take('smtp.sender') mail.settings.login = myconf.take('smtp.login') ## configure auth policy auth.settings.registration_requires_verification = not DEVELOPMENT auth.settings.registration_requires_approval = False auth.settings.reset_password_requires_verification = True
# -*- coding: utf-8 -*- from gluon.tools import Auth from gluon.contrib.appconfig import AppConfig myconf = AppConfig(reload=True) DEVELOPMENT = myconf.take('app.development').lower()=='true' AS_SERVICE = myconf.take('app.as_service').lower()=='true' DEBUG_MODE = myconf.take('app.debug_mode').lower()=='true' SCHEME = 'http' # if DEVELOPMENT else 'https' db = DAL(myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['all']) response.generic_patterns = [] response.formstyle = myconf.take('forms.formstyle') # or 'bootstrap3_stacked' or 'bootstrap2' or other response.form_label_separator = myconf.take('forms.separator') auth = Auth(db) ## configure email mail = auth.settings.mailer mail.settings.server = 'logging' if request.is_local else myconf.take('smtp.server') mail.settings.sender = myconf.take('smtp.sender') mail.settings.login = myconf.take('smtp.login') ## configure auth policy auth.settings.registration_requires_verification = not DEVELOPMENT auth.settings.registration_requires_approval = False auth.settings.reset_password_requires_verification = True
class Access(object): def __init__(self, db, auth): self.db = db self.auth = auth self.config = AppConfig() self.session = current.session self.request = current.request # Not allow self.auth.settings.actions_disabled.append("register") self.auth.settings.actions_disabled.append("request_reset_password") self.auth.settings.actions_disabled.append("retrieve_password") self.auth.settings.actions_disabled.append("profile") self.auth.settings.registration_requires_approval = False self.auth.settings.registration_requires_verification = False # Set general settings self.auth.settings.expiration = int(self.config.take("general.session_expiration")) self.auth.settings.remember_me_form = self.config.take("general.remember_me_form") if self.config.take("general.auth_type") == "ldap": self.auth.settings.login_onvalidation = [lambda form: self.__define_domain(form.vars.email.split("@")[1])] elif self.config.take("general.auth_type") == "local": if str2bool(self.config.take("auth_local.enable_change_password")) is not True: self.auth.settings.actions_disabled.append("change_password") # Disable group for each user self.auth.settings.create_user_groups = False self.auth.settings.login_next = URL("home", "index") def __define_domain(self, domain): domain = domain.lower() try: count = 1 while True: ldap_connection = "auth_ldap_0" + str(count) if self.config.__getattribute__(ldap_connection).is_active: if self.config.__getattribute__(ldap_connection).domain == domain: self.__load_ldap_connection(ldap_connection) break count += 1 except Exception as e: # from log import logger # logger.warning("Not possible to connect to LDAP.") raise PRETTYHTTP(400, "Upppss, the domain you have type, I could not find it...") def __load_ldap_connection(self, ldap): try: if self.config.__getattribute__(ldap).is_active: from gluon.contrib.login_methods.ldap_auth import ldap_auth if self.config.auth.auth_local_database: self.auth.settings.login_methods.append( ldap_auth( mode=self.config.__getattribute__(ldap).mode, secure=self.config.__getattribute__(ldap).secure, server=self.config.__getattribute__(ldap).server, port=self.config.__getattribute__(ldap).port, base_dn=self.config.__getattribute__(ldap).base_dn, allowed_groups=self.config.__getattribute__(ldap).allowed_groups, group_dn=self.config.__getattribute__(ldap).group_dn, group_name_attrib=self.config.__getattribute__(ldap).group_name_attrib, group_member_attrib=self.config.__getattribute__(ldap).group_member_attrib, group_filterstr=self.config.__getattribute__(ldap).group_filterstr, manage_user=True, user_firstname_attrib="cn:1", user_lastname_attrib="cn:2", user_mail_attrib="mail", db=self.db, ) ) else: self.auth.settings.login_methods = [ ( ldap_auth( mode=self.config.__getattribute__(ldap).mode, secure=self.config.__getattribute__(ldap).secure, server=self.config.__getattribute__(ldap).server, port=self.config.__getattribute__(ldap).port, base_dn=self.config.__getattribute__(ldap).base_dn, allowed_groups=self.config.__getattribute__(ldap).allowed_groups, group_dn=self.config.__getattribute__(ldap).group_dn, group_name_attrib=self.config.__getattribute__(ldap).group_name_attrib, group_member_attrib=self.config.__getattribute__(ldap).group_member_attrib, group_filterstr=self.config.__getattribute__(ldap).group_filterstr, manage_user=True, user_firstname_attrib="cn:1", user_lastname_attrib="cn:2", user_mail_attrib="mail", db=self.db, ) ) ] except Exception as e: # from log import logger # logger.warning("Not possible to connect to LDAP.") raise PRETTYHTTP(500, e)
# -*- coding: utf-8 -*- u"""Contém as configurações do sistema. Contém configurações do sitema como conexão ao banco de dados, autenticação, linguagem e outros. """ from gluon.tools import Auth from gluon.contrib.appconfig import AppConfig from gluon import DAL, current, URL # app configuration made easy. Look inside private/appconfig.ini # once in production, remove reload=True to gain full speed myconf = AppConfig(reload=True) db = DAL( myconf.take("db.uri"), pool_size=myconf.take("db.pool_size", cast=int), check_reserved=["all"], migrate=myconf.take("db.migrate", cast=bool), ) current.response.formstyle = myconf.take("forms.formstyle") current.response.form_label_separator = myconf.take("forms.separator") # AUTH auth = Auth(db, controller="admin", function="user") # create all tables needed by auth if not custom tables auth.define_tables(username=False, signature=False)
# -*- coding: utf-8 -*- ## if SSL/HTTPS is properly configured and you want all HTTP requests to ## be redirected to HTTPS, uncomment the line below: # request.requires_https() ## get application configuration from gluon.contrib.appconfig import AppConfig ## once in production, remove reload=True to gain full speed upload_conf = AppConfig(reload=True) ## create database connection using SQLite db = DAL(upload_conf.take('db.uri'), pool_size=upload_conf.take('db.pool_size', cast=int), check_reserved=['all']) ## by default give a view/generic.extension to all actions from localhost ## none otherwise. a pattern can be 'controller/function.extension' response.generic_patterns = ['*'] if request.is_local else [] ## choose a style for forms response.formstyle = upload_conf.take( 'forms.formstyle') # or 'bootstrap3_stacked' or 'bootstrap2' or other response.form_label_separator = upload_conf.take('forms.separator') ## optimize handling of static files #response.optimize_css = 'concat,minify,inline' #response.optimize_js = 'concat,minify,inline' from gluon.tools import Auth, Service, PluginManager, Recaptcha auth = Auth(db)
'groups': ['Manager', 'Inventories', 'Purchases', 'Items management', 'Items prices', 'Items info', 'Sales bags', 'Sales checkout', 'Sales invoices', 'Sales delivery', 'Sales returns', 'Sales invoices', 'VIP seller', 'Analytics', 'Sale orders', 'Stock transfers', 'Offers', 'Accounts payable', 'Accounts receivable', 'Highlights', 'Cash out', 'Product loss', 'Safe config' ] }) ], {}) ] WORKFLOW_DATA = get_workflows() # sale events SALE_DEFERED = 'defered' SALE_DELIVERED = 'delivered' SALE_CREATED = 'created' SALE_PAID = 'paid' BAG_ACTIVE = 0 BAG_COMPLETE = 1 BAG_FOR_ORDER = 2 BAG_ORDER_COMPLETE = 3 # cache names CACHED_POPULAR_ITEMS = 0 TAX_TRANSFER = 1 TAX_RETAIN = 2 STRIPE_PK = CONF.take('stripe.public_key') STRIPE_SK = CONF.take('stripe.secure_key')
## File is released under public domain and you can use without limitations ######################################################################### ## if SSL/HTTPS is properly configured and you want all HTTP requests to ## be redirected to HTTPS, uncomment the line below: # request.requires_https() ## app configuration made easy. Look inside private/appconfig.ini from gluon.contrib.appconfig import AppConfig ## once in production, remove reload=True to gain full speed myconf = AppConfig(reload=True) if not request.env.web2py_runtime_gae: ## if NOT running on Google App Engine use SQLite or other DB db = DAL(myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['all']) else: ## connect to Google BigTable (optional 'google:datastore://namespace') db = DAL('google:datastore+ndb') ## store sessions and tickets there session.connect(request, response, db=db) ## or store session in Memcache, Redis, etc. ## from gluon.contrib.memdb import MEMDB ## from google.appengine.api.memcache import Client ## session.connect(request, response, db = MEMDB(Client())) ## by default give a view/generic.extension to all actions from localhost ## none otherwise. a pattern can be 'controller/function.extension' response.generic_patterns = ['*'] if request.is_local else [] ## choose a style for forms response.formstyle = myconf.take('forms.formstyle') # or 'bootstrap3_stacked' or 'bootstrap2' or other
##if request.is_https: ## redirect(URL(args=request.args, vars=request.vars, scheme='http', host=True)) from gluon import current current.CODE_UTF = 'utf8' #'cp1251' current.PARTNER_MIN = PARTNER_MIN = 10 PARTNER_GO = 77 CACHE_EXP_TIME = request.is_local and 5 or 360 ## app configuration made easy. Look inside private/appconfig.ini from gluon.contrib.appconfig import AppConfig ## once in production, remove reload=True to gain full speed myconf = AppConfig(reload=True) DOMEN = myconf.take('app.domen') DEVELOP = myconf.take('app.develop', cast=bool) USE_TO_PHONE = myconf.take('mode.use_to_phone') USE_EXCHANGE = myconf.take('mode.use_exchange') USE_BUY_SELL = myconf.take('mode.use_buy_sell') USE_TO_DEALS = myconf.take('mode.use_to_deals') current.TO_BUY_ID = TO_BUY_ID = myconf.take('deals.buy') current.TO_WALLET_ID = TO_WALLET_ID = myconf.take('deals.wallet') current.TO_COIN_ID = TO_COIN_ID = myconf.take('deals.coin') current.TO_PHONE7_ID = TO_PHONE7_ID = myconf.take('deals.phone_7') current.CURR_USD_ID = CURR_USD_ID = myconf.take('currs.usd_id') current.CURR_USD_ID = CURR_RUB_ID = myconf.take('currs.rub_id') current.CURR_USD_ID = CURR_BTC_ID = myconf.take('currs.btc_id')
db = DAL("sqlite://storage.sqlite") # -*- coding: utf-8 -*- from gluon.contrib.appconfig import AppConfig myconf = AppConfig(reload=True) response.generic_patterns = ['*'] if request.is_local else [] response.formstyle = myconf.take('forms.formstyle') response.form_label_separator = myconf.take('forms.separator') from gluon.tools import Auth, Service, PluginManager, prettydate from gluon.tools import Crud crud = Crud(db) auth = Auth(db) service = Service() plugins = PluginManager() request.env.http_host = 'www.cakarcafehouse.com' ## create all tables needed by auth if not custom tables auth.define_tables(username=False, signature=False) ## configure email mail = auth.settings.mailer mail.settings.server = 'logging' if request.is_local else myconf.take('smtp.server') mail.settings.sender = myconf.take('smtp.sender') mail.settings.login = myconf.take('smtp.login') ## configure auth policy auth.settings.registration_requires_verification = False auth.settings.registration_requires_approval = False
# db = DAL(myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['all']) else: ## connect to Google BigTable (optional 'google:datastore://namespace') db = DAL('google:datastore+ndb') ## store sessions and tickets there session.connect(request, response, db=db) ## or store session in Memcache, Redis, etc. ## from gluon.contrib.memdb import MEMDB ## from google.appengine.api.memcache import Client ## session.connect(request, response, db = MEMDB(Client())) ## by default give a view/generic.extension to all actions from localhost ## none otherwise. a pattern can be 'controller/function.extension' response.generic_patterns = ['*'] ## choose a style for forms response.formstyle = myconf.take( 'forms.formstyle') # or 'bootstrap3_stacked' or 'bootstrap2' or other response.form_label_separator = myconf.take('forms.separator') ## (optional) optimize handling of static files # response.optimize_css = 'concat,minify,inline' # response.optimize_js = 'concat,minify,inline' ## (optional) static assets folder versioning # response.static_version = '0.0.0' ######################################################################### ## Here is sample code if you need for ## - email capabilities ## - authentication (registration, login, logout, ... ) ## - authorization (role based authorization) ## - services (xml, csv, json, xmlrpc, jsonrpc, amf, rss) ## - old style crud actions ## (more options discussed in gluon/tools.py)
######################################################################### ## if SSL/HTTPS is properly configured and you want all HTTP requests to ## be redirected to HTTPS, uncomment the line below: # request.requires_https() ## app configuration made easy. Look inside private/appconfig.ini from gluon.contrib.appconfig import AppConfig from gluon import current ## once in production, remove reload=True to gain full speed myconf = AppConfig(reload=True) if not request.env.web2py_runtime_gae: ## if NOT running on Google App Engine use SQLite or other DB db = DAL(myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['all'],migrate=True) else: ## connect to Google BigTable (optional 'google:datastore://namespace') db = DAL('google:datastore+ndb') ## store sessions and tickets there session.connect(request, response, db=db) ## or store session in Memcache, Redis, etc. ## from gluon.contrib.memdb import MEMDB ## from google.appengine.api.memcache import Client ## session.connect(request, response, db = MEMDB(Client())) current.db = db ## by default give a view/generic.extension to all actions from localhost ## none otherwise. a pattern can be 'controller/function.extension' response.generic_patterns = ['*'] if request.is_local else []
if not request.env.web2py_runtime_gae: # --------------------------------------------------------------------- # if NOT running on Google App Engine use SQLite or other DB # --------------------------------------------------------------------- ## if NOT running on Google App Engine use SQLite or other DB if web2pytest.is_running_under_test(request, request.application): # When running under test, db cannot be ':memory:' # because it is recreated in each request and a webclient test # can make many requests to validate a single scenario. db = DAL('sqlite://%s.sqlite' % request.application, folder=os.path.dirname(web2pytest.testfile_name()), pool_size=1, check_reserved=['all']) else: db = DAL(myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['all']) # # db = DAL(myconf.get('db.uri'), # pool_size=myconf.get('db.pool_size', cast=int), # check_reserved=['all']) else: # --------------------------------------------------------------------- # connect to Google BigTable (optional 'google:datastore://namespace') # --------------------------------------------------------------------- db = DAL('google:datastore+ndb') # --------------------------------------------------------------------- # store sessions and tickets there # --------------------------------------------------------------------- session.connect(request, response, db=db)
from gluon.contrib.appconfig import AppConfig import uuid app_conf = AppConfig(reload=True) DATABASE_NAME = app_conf.take("monitutor_env.database_name") DATABASE_USER = app_conf.take("monitutor_env.database_user") DATABASE_PASSWORD = app_conf.take("monitutor_env.database_password") DATABASE_HOST = app_conf.take("monitutor_env.database_host") tutordb = DAL("postgres://" + DATABASE_USER + ":" + DATABASE_PASSWORD + "@" + DATABASE_HOST + "/" + DATABASE_NAME) from gluon.tools import Auth auth = Auth(tutordb) auth.settings.extra_fields['auth_user']= [ Field('hmac_secret', length=512, default=lambda:str(uuid.uuid4()).replace("-","")[:16]), Field('image', type='upload') ] auth.define_tables(username=True) if not tutordb.auth_group[1]: tutordb.auth_group.insert(role="admin") tutordb.define_table('monitutor_scenarios', Field('scenario_id', type='id'), Field('uuid', length=64, default=lambda:str(uuid.uuid4())), Field('name', type='string', requires=IS_ALPHANUMERIC()), Field('display_name', type='string', required=True), Field('description', type='text', required=True), Field('goal', type='text'), Field('hidden', type='boolean', default=True),
class SEO(object): def __init__(self, row, locale=None, type="website", url=None): """ :param row: Storage object :param locale: :param type: :param url: """ self.config = AppConfig() self.title = self.config.take('metadata.site_name') self.url = url or URL(args=current.request.args, host=True) self.type = type self.locale= locale self.row = row self.response = current.response def set(self): self._set_meta() self._set_open_graph() self._set_twitter_card() def _set_meta(self): description = self.config.take('metadata.description') keywords = self.config.take('metadata.keywords') author = self.config.take('metadata.author') data = locals() for name in ['title', 'description', 'keywords', 'author']: if name == 'title': self.response.meta[name] = self.title elif data[name]: self.response.meta[name] = data[name] def _set_open_graph(self): for name in ['type', 'title', 'url', 'description', 'site_name', 'locale', 'locale_alternate', 'image']: dict = OrderedDict() if name == 'type': content = self.type elif name == 'site_name': content = self.title elif name == 'url': content = self.url elif name == 'locale': content = self.locale elif name == 'locale_alternate': content = self.config.take('general.locale_alternate') else: try: content = self.row['f_'+name] except AttributeError as e: logger.warning("%s attribute have been not set" % name) content = None if content: dict['name'] = "og:"+name dict['content'] = content self.response.meta['og_'+name] = dict def _set_twitter_card(self): ''' <meta name="twitter:title" content="Linux-Cambodia" /> <meta name="twitter:description" content="Linux-Cambodia is a non-profit project committed with the current and emergent technology trends in Cambodia, with the Internet, with education...Behind the headings, the products and the services offered by Linux Cambodia there is a team of professionals with sound experience on information technologies, online marketing, events management, video producing, social media, training, web developing... The initiative is rooted in the idea that every person has the right to access information and knowledge. In this sense and due to the lack of these contents in the Cambodian market, this project is launched with the hope of reaching all audiences who are passionate about open source." /> <meta name="twitter:image" content="http://www.linux-cambodia.com/default/download/new.picture.98d62da3eccd8100.77656c636f6d652e6a7067_thumb.jpg" /> ''' for name in ['image', 'title', 'description']: dict = OrderedDict() if name == 'title': content = self.title else: try: content = self.row['f_'+name] except AttributeError as e: logger.warning("%s attribute have been not set" % name) content = None if content: dict['property'] = "twitter:"+name dict['content'] = content self.response.meta['tc_'+name] = dict
service = Service() plugins = PluginManager() auth.settings.extra_fields['auth_user']= [ Field('phone_number', 'string', requires = IS_MATCH('^\d{3}-?\d{3}-?\d{4}$', error_message='example: 111-555-2345')), Field('phone_provider', 'string', requires = IS_IN_SET(('AT&T','Metro PCS','Sprint PCS', 'T-Mobile USA (tmail)', 'Verizon Wireless (vtext)', 'Virgin Mobile USA'))), Field('daily_message', 'boolean', default=False), Field('get_texts', 'boolean', default=False), Field('netWorth', 'double', writable=False,) ] ## create all tables needed by auth if not custom tables auth.define_tables(username=False, signature=False) ## configure email mail = auth.settings.mailer mail.settings.server = 'logging' if request.is_local else myconf.take('smtp.server') mail.settings.sender = myconf.take('smtp.sender') mail.settings.login = myconf.take('smtp.login') ## configure auth policy auth.settings.registration_requires_verification = False auth.settings.registration_requires_approval = False auth.settings.reset_password_requires_verification = True auth.settings.login_next = URL('profile') db.define_table('historic', Field('ticker', 'string'), Field('Date', 'date'), Field('Open', 'double'), Field('High', 'double'),
import json from gluon.tools import AuthJWT, AuthAPI import requests import hashlib from gluon.contrib.appconfig import AppConfig from gluon.tools import Mail import uuid myconf = AppConfig() myjwt = AuthJWT(auth, secret_key='secret') mail = Mail() mail.settings.server = myconf.take('smtp.server') mail.settings.sender = myconf.take('smtp.sender') mail.settings.login = myconf.take('smtp.login') def api_requires_extension(func): def wrapper(*args): if request.extension != 'html': response.view = 'generic.' + request.extension else: response.view = 'generic.json' return func(*args) return wrapper @api_requires_extension @myjwt.allows_jwt() def api_requires_login(func):
from gluon.storage import Storage from agiscore.gui.mic import Accion, grid_simple from agiscore.gui.evento import form_configurar_evento from agiscore.db.evento import esta_activo from agiscore.db import pais as pais_model from agiscore.db.matricula import SIN_MATRICULAR, SIN_MATRICULAR_CON_DEUDA from agiscore.db.matricula import MATRICULADO, MATRICULADO_CON_DEUDAS from agiscore.db.candidatura import NO_ADMITIDO, ADMITIDO from agiscore.validators import IS_DATE_LT # TODO: remove response.menu = [] menu_lateral.append(Accion(T('Configurar evento'), URL('configurar', args=[request.args(0)]), auth.has_membership(role=myconf.take('roles.admin'))), ['configurar']) menu_lateral.append(Accion(T('Registro de admitidos'), URL('index', args=[request.args(0)]), auth.user is not None), ['index', 'pago', 'matricular']) @auth.requires(auth.has_membership(role=myconf.take('roles.admin'))) def configurar(): """Configuración del evento""" C = Storage() C.evento = db.evento(request.args(0)) C.ano = db.ano_academico(C.evento.ano_academico_id) C.unidad = db.unidad_organica(C.ano.unidad_organica_id) C.escuela = db.escuela(C.unidad.escuela_id)
# if SSL/HTTPS is properly configured and you want all HTTP requests to # be redirected to HTTPS, uncomment the line below: # request.requires_https() # app configuration made easy. Look inside private/appconfig.ini from gluon.contrib.appconfig import AppConfig from gluon.tools import Auth, Service, PluginManager, Crud # once in production, remove reload=True to gain full speed myconf = AppConfig(reload=True) if not request.env.web2py_runtime_gae: # if NOT running on Google App Engine use SQLite or other DB db = DAL( myconf.take('db.uri'), pool_size=myconf.take( 'db.pool_size', cast=int), check_reserved=None,lazy_tables=True) else: # connect to Google BigTable (optional 'google:datastore://namespace') db = DAL('google:datastore+ndb') # store sessions and tickets there session.connect(request, response, db=db) # or store session in Memcache, Redis, etc. # from gluon.contrib.memdb import MEMDB # from google.appengine.api.memcache import Client # session.connect(request, response, db = MEMDB(Client())) # by default give a view/generic.extension to all actions from localhost
# db = DAL(myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['all']) else: ## connect to Google BigTable (optional 'google:datastore://namespace') db = DAL('google:datastore+ndb') ## store sessions and tickets there session.connect(request, response, db=db) ## or store session in Memcache, Redis, etc. ## from gluon.contrib.memdb import MEMDB ## from google.appengine.api.memcache import Client ## session.connect(request, response, db = MEMDB(Client())) ## by default give a view/generic.extension to all actions from localhost ## none otherwise. a pattern can be 'controller/function.extension' response.generic_patterns = ['*'] ## choose a style for forms response.formstyle = myconf.take('forms.formstyle') # or 'bootstrap3_stacked' or 'bootstrap2' or other response.form_label_separator = myconf.take('forms.separator') ## (optional) optimize handling of static files # response.optimize_css = 'concat,minify,inline' # response.optimize_js = 'concat,minify,inline' ## (optional) static assets folder versioning # response.static_version = '0.0.0' ######################################################################### ## Here is sample code if you need for ## - email capabilities ## - authentication (registration, login, logout, ... ) ## - authorization (role based authorization) ## - services (xml, csv, json, xmlrpc, jsonrpc, amf, rss) ## - old style crud actions ## (more options discussed in gluon/tools.py)
load_graph = False filename = 'private/appconfig.ini' path = os.path.join(request.folder, filename) if os.path.exists(path): useappconfig = True else: useappconfig = False usecategory = True if useappconfig: from gluon.contrib.appconfig import AppConfig # once in production, remove reload=True to gain full speed myconf = AppConfig(reload=False) debug = myconf.take('developer.debug', cast=int) backend = myconf.take('search.backend') # removed as now set on pythonanywhere #if myconf.take('site.require_https', cast=int): # request.requires_https() else: debug = False backend = 'SimpleBackend' # once in production change to False track_changes(debug) response.static_version = '2.0.0' if not request.env.web2py_runtime_gae: if useappconfig: db = DAL(myconf.take('db.uri'),
# Adjust settings depending on environment settings = dict() if request.env.http_host in ('127.0.0.1:8000', 'localhost:8000', '192.168.0.8:8000'): settings['is_development'] = True myconf = AppConfig(reload=True) else: # Production settings settings['is_development'] = False myconf = AppConfig() request.requires_https() # response.optimize_css = 'concat,minify,inline' # response.optimize_js = 'concat,minify,inline' # Setup db db = DAL( myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['mysql']) db_scheduler = DAL(myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['mysql']) # Add db to current current.db = db ## by default give a view/generic.extension to all actions from localhost ## none otherwise. a pattern can be 'controller/function.extension' response.generic_patterns = ['*'] if request.is_local else [] ## choose a style for forms response.formstyle = myconf.take('forms.formstyle') # or 'bootstrap3_stacked' or 'bootstrap2' or other response.form_label_separator = myconf.take('forms.separator')
db = DAL('sqlite://storage.db') else: ## connect to Google BigTable (optional 'google:datastore://namespace') db = DAL('google:datastore+ndb') ## store sessions and tickets there session.connect(request, response, db=db) ## or store session in Memcache, Redis, etc. ## from gluon.contrib.memdb import MEMDB ## from google.appengine.api.memcache import Client ## session.connect(request, response, db = MEMDB(Client())) ## by default give a view/generic.extension to all actions from localhost ## none otherwise. a pattern can be 'controller/function.extension' response.generic_patterns = ['*'] if request.is_local else [] ## choose a style for forms response.formstyle = myconf.take('forms.formstyle') # or 'bootstrap3_stacked' or 'bootstrap2' or other response.form_label_separator = myconf.take('forms.separator') ## (optional) optimize handling of static files # response.optimize_css = 'concat,minify,inline' # response.optimize_js = 'concat,minify,inline' ## (optional) static assets folder versioning # response.static_version = '0.0.0' ######################################################################### ## Here is sample code if you need for ## - email capabilities ## - authentication (registration, login, logout, ... ) ## - authorization (role based authorization) ## - services (xml, csv, json, xmlrpc, jsonrpc, amf, rss) ## - old style crud actions
#db = DAL(myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['all']) #else: ## connect to Google BigTable (optional 'google:datastore://namespace') #db = DAL('google:datastore+ndb') ## store sessions and tickets there #session.connect(request, response, db=db) ## or store session in Memcache, Redis, etc. ## from gluon.contrib.memdb import MEMDB ## from google.appengine.api.memcache import Client ## session.connect(request, response, db = MEMDB(Client())) ## by default give a view/generic.extension to all actions from localhost ## none otherwise. a pattern can be 'controller/function.extension' response.generic_patterns = ['*'] if request.is_local else [] ## choose a style for forms response.formstyle = myconf.take('forms.formstyle') # or 'bootstrap3_stacked' or 'bootstrap2' or other response.form_label_separator = myconf.take('forms.separator') ## (optional) optimize handling of static files # response.optimize_css = 'concat,minify,inline' # response.optimize_js = 'concat,minify,inline' ## (optional) static assets folder versioning # response.static_version = '0.0.0' ######################################################################### ## Here is sample code if you need for ## - email capabilities ## - authentication (registration, login, logout, ... ) ## - authorization (role based authorization) ## - services (xml, csv, json, xmlrpc, jsonrpc, amf, rss) ## - old style crud actions
menu_migas = MenuMigas() from gluon.storage import Storage from agiscore.gui.mic import Accion, grid_simple from agiscore import tools # TODO: remove response.menu = [] menu_lateral.append(Accion(T('Asignación de aulas'), URL('index', args=[request.args(0)]), True), ['index']) menu_lateral.append(Accion(T('Codificación de los estudiantes'), URL('codificacion', args=[request.args(0)]), auth.has_membership(role=myconf.take('roles.admin')) or auth.has_membership(role=myconf.take('roles.oexamen'))), ['codificacion']) menu_lateral.append(Accion(T('Asignación de notas'), URL('notas', args=[request.args(0)]), True), ['notas']) menu_lateral.append(Accion(T('Reporte de notas'), URL('notas_reporte', args=[request.args(0)]), auth.has_membership(role=myconf.take('roles.admin')) or auth.has_membership(role=myconf.take('roles.admdocente'))), ['notas_reporte']) menu_lateral.append(Accion(T('Distribución por aulas'), URL('distribucion', args=[request.args(0)]), True), ['distribucion'])
######################################################################### ## if SSL/HTTPS is properly configured and you want all HTTP requests to ## be redirected to HTTPS, uncomment the line below: # request.requires_https() ## app configuration made easy. Look inside private/appconfig.ini from gluon.contrib.appconfig import AppConfig ## once in production, remove reload=True to gain full speed myconf = AppConfig(reload=True) if not request.env.web2py_runtime_gae: ## if NOT running on Google App Engine use SQLite or other DB db = DAL(myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['all']) else: ## connect to Google BigTable (optional 'google:datastore://namespace') db = DAL('google:datastore+ndb') ## store sessions and tickets there session.connect(request, response, db=db) ## or store session in Memcache, Redis, etc. ## from gluon.contrib.memdb import MEMDB ## from google.appengine.api.memcache import Client ## session.connect(request, response, db = MEMDB(Client())) ## by default give a view/generic.extension to all actions from localhost ## none otherwise. a pattern can be 'controller/function.extension' response.generic_patterns = ['*'] if request.is_local else [] ## choose a style for forms response.formstyle = myconf.take('forms.formstyle') # or 'bootstrap3_stacked' or 'bootstrap2' or other
('AT&T', 'Metro PCS', 'Sprint PCS', 'T-Mobile USA (tmail)', 'Verizon Wireless (vtext)', 'Virgin Mobile USA'))), Field('daily_message', 'boolean', default=False), Field('get_texts', 'boolean', default=False), Field( 'netWorth', 'double', writable=False, ) ] ## create all tables needed by auth if not custom tables auth.define_tables(username=False, signature=False) ## configure email mail = auth.settings.mailer mail.settings.server = 'logging' if request.is_local else myconf.take( 'smtp.server') mail.settings.sender = myconf.take('smtp.sender') mail.settings.login = myconf.take('smtp.login') ## configure auth policy auth.settings.registration_requires_verification = False auth.settings.registration_requires_approval = False auth.settings.reset_password_requires_verification = True auth.settings.login_next = URL('profile') ######################################################################### ## Define your tables below (or better in another model file) for example ## ## >>> db.define_table('mytable',Field('myfield','string')) ##
import logging from gluon.contrib.appconfig import AppConfig from gluon.storage import Storage from tbox_interface import TBoxInterface from abox_interface import ABoxInterface # Doesn't work well anyway even for dev/testing # from gluon.custom_import import track_changes # track_changes(True) SETTINGS = Storage() MYCONF = AppConfig(reload=False) # read values from private/config.ini SETTINGS.app_view_name = MYCONF.take('app.view_name', cast=str) SETTINGS.app_name = MYCONF.take('app.app_name', cast=str) SETTINGS.maintainer_eml = MYCONF.take('app.maintainer_eml', cast=str) SETTINGS.base_url = MYCONF.take('app.base_url', cast=str) SETTINGS.document_endpoint = MYCONF.take('app.document_endpoint', cast=str) SETTINGS.id_gen_endpoint = MYCONF.take('app.id_gen_endpoint', cast=str) SETTINGS.inheritance_query_endpoint = MYCONF.take( 'app.inheritance_query_endpoint', cast=str) SETTINGS.create_activity_endpoint = MYCONF.take('app.create_activity_endpoint', cast=str) SETTINGS.db_url_login = MYCONF.take('auth_db.db_url_login', cast=str) SETTINGS.migrate = MYCONF.take('auth_db.migrate', cast=bool) SETTINGS.fake_migrate_all = MYCONF.take('auth_db.fake_migrate_all', cast=bool) SETTINGS.admn_grp = MYCONF.take('auth_db.admn_grp', cast=str)