Esempio n. 1
0
def index():
    response.view = 'wizard/step.html'
    reset(session)
    apps = os.listdir(os.path.join(request.folder, '..'))
    form = SQLFORM.factory(Field('name', requires=[IS_NOT_EMPTY(),
                                                   IS_ALPHANUMERIC()]), _class='span5 well well-small')
    if form.accepts(request.vars):
        app = form.vars.name
        session.app['name'] = app
        if MULTI_USER_MODE and db(db.app.name == app)(db.app.owner != auth.user.id).count():
            session.flash = 'App belongs already to other user'
        elif app in apps:
            meta = os.path.normpath(
                os.path.join(os.path.normpath(request.folder),
                             '..', app, 'wizard.metadata'))
            if os.path.exists(meta):
                try:
                    metafile = open_file(meta, 'rb')
                    try:
                        session.app = pickle.load(metafile)
                    finally:
                        metafile.close()
                    session.flash = T("The app exists, was created by wizard, continue to overwrite!")
                except:
                    session.flash = T("The app exists, was NOT created by wizard, continue to overwrite!")
        redirect(URL('step1'))
    return dict(step='Start', form=form)
Esempio n. 2
0
def index():
    response.view = 'wizard/step.html'
    reset(session)
    apps = os.listdir(os.path.join(request.folder, '..'))
    form = SQLFORM.factory(Field('name',
                                 requires=[IS_NOT_EMPTY(),
                                           IS_ALPHANUMERIC()]),
                           _class='span5 well well-small')
    if form.accepts(request.vars):
        app = form.vars.name
        session.app['name'] = app
        if MULTI_USER_MODE and db(db.app.name == app)(
                db.app.owner != auth.user.id).count():
            session.flash = 'App belongs already to other user'
        elif app in apps:
            meta = os.path.normpath(
                os.path.join(os.path.normpath(request.folder), '..', app,
                             'wizard.metadata'))
            if os.path.exists(meta):
                try:
                    metafile = open_file(meta, 'rb')
                    try:
                        session.app = pickle.load(metafile)
                    finally:
                        metafile.close()
                    session.flash = T(
                        "The app exists, was created by wizard, continue to overwrite!"
                    )
                except:
                    session.flash = T(
                        "The app exists, was NOT created by wizard, continue to overwrite!"
                    )
        redirect(URL('step1'))
    return dict(step='Start', form=form)
Esempio n. 3
0
    def copyDB(self):
        other_db = DAL("%s://%s" % (self.targetdbType, self.targetdbName),
                       folder=self.targetFolder)

        print 'creating tables...'

        for table in self.db:
            other_db.define_table(table._tablename,
                                  *[field for field in table])
            '''
            should there be an option to truncAte target DB?
            if yes, then change args to allow for choice
            and set self.trancate to the art value

            if self.truncate==True:
                other_db[table._tablename].truncate()
            '''

        print 'exporting data...'
        self.db.export_to_csv_file(open('tmp.sql', 'wb'))

        print 'importing data...'
        other_db.import_from_csv_file(open_file('tmp.sql', 'rb'))
        other_db.commit()
        print 'done!'
        print 'Attention: do not run this program again or you end up with duplicate records'
Esempio n. 4
0
    def copyDB(self):
        other_db = DAL("%s://%s" % (
            self.targetdbType, self.targetdbName), folder=self.targetFolder)

        print 'creating tables...'

        for table in self.db:
            other_db.define_table(
                table._tablename, *[field for field in table])
            '''
            should there be an option to truncAte target DB?
            if yes, then change args to allow for choice
            and set self.trancate to the art value

            if self.truncate==True:
                other_db[table._tablename].truncate()
            '''

        print 'exporting data...'
        self.db.export_to_csv_file(open('tmp.sql', 'wb'))

        print 'importing data...'
        other_db.import_from_csv_file(open_file('tmp.sql', 'rb'))
        other_db.commit()
        print 'done!'
        print 'Attention: do not run this program again or you end up with duplicate records'
Esempio n. 5
0
def interact():
    app = request.args(0) or 'admin'
    reset()

    # process all pending messages in the frontend
    web_debugger.run()

    # if debugging, filename and lineno should have valid values
    filename = web_debugger.filename
    lineno = web_debugger.lineno
    if filename:
        # prevent IOError 2 on some circuntances (EAFP instead of os.access)
        try:
            lines = open_file(filename, 'r').readlines()
        except:
            lines = ""
        lines = dict([
            (i + 1, l)
            for (i, l) in enumerate([l.strip("\n").strip("\r") for l in lines])
        ])
        filename = os.path.basename(filename)
    else:
        lines = {}

    if filename:
        web_debugger.set_burst(2)
        env = web_debugger.do_environment()
        f_locals = env['locals']
        f_globals = {}
        for name, value in env['globals'].items():
            if name not in gluon.html.__all__ and \
                name not in gluon.validators.__all__:
                f_globals[name] = pydoc.text.repr(value)
    else:
        f_locals = {}
        f_globals = {}
        response.headers['refresh'] = "3"

    if web_debugger.exception_info:
        response.flash = T('"User Exception" debug mode. '
                           'An error ticket could be issued!')

    return dict(app=app,
                data="",
                filename=web_debugger.filename,
                lines=lines,
                lineno=lineno,
                f_globals=f_globals,
                f_locals=f_locals,
                exception=web_debugger.exception_info)
Esempio n. 6
0
def interact():
    app = request.args(0) or 'admin'
    reset()

    # process all pending messages in the frontend
    web_debugger.run()

    # if debugging, filename and lineno should have valid values
    filename = web_debugger.filename
    lineno = web_debugger.lineno
    if filename:
        # prevent IOError 2 on some circuntances (EAFP instead of os.access)
        try:
            lines = open_file(filename, 'r').readlines()
        except:
            lines = ""
        lines = dict([(i + 1, l) for (i, l) in enumerate(
            [l.strip("\n").strip("\r") for l in lines])])
        filename = os.path.basename(filename)
    else:
        lines = {}

    if filename:
        web_debugger.set_burst(2)
        env = web_debugger.do_environment()
        f_locals = env['locals']
        f_globals = {}
        for name, value in env['globals'].items():
            if name not in gluon.html.__all__ and \
                name not in gluon.validators.__all__:
                f_globals[name] = pydoc.text.repr(value)
    else:
        f_locals = {}
        f_globals = {}
        response.headers['refresh'] = "3"

    if web_debugger.exception_info:
        response.flash = T('"User Exception" debug mode. '
                           'An error ticket could be issued!')

    return dict(app=app, data="",
                filename=web_debugger.filename, lines=lines, lineno=lineno,
                f_globals=f_globals, f_locals=f_locals,
                exception=web_debugger.exception_info)
Esempio n. 7
0
    def acquire(self, startup=False):
        """
        Returns the time when the lock is acquired or
        None if cron already running

        lock is implemented by writing a pickle (start, stop) in cron.master
        start is time when cron job starts and stop is time when cron completed
        stop == 0 if job started but did not yet complete
        if a cron job started within less than 60 seconds, acquire returns None
        if a cron job started before 60 seconds and did not stop,
        a warning is issue "Stale cron.master detected"
        """
        if sys.platform == 'win32':
            locktime = 59.5
        else:
            locktime = 59.99
        if portalocker.LOCK_EX is None:
            logger.warning('cron disabled because no file locking')
            return None
        self.master = fileutils.open_file(self.path, 'rb+')
        try:
            ret = None
            portalocker.lock(self.master, portalocker.LOCK_EX)
            try:
                (start, stop) = pickle.load(self.master)
            except:
                start = 0
                stop = 1
            if startup or self.now - start > locktime:
                ret = self.now
                if not stop:
                    # this happens if previous cron job longer than 1 minute
                    logger.warning('stale cron.master detected')
                logger.debug('acquiring lock')
                self.master.seek(0)
                pickle.dump((self.now, 0), self.master)
                self.master.flush()
        finally:
            portalocker.unlock(self.master)
        if not ret:
            # do this so no need to release
            self.master.close()
        return ret
Esempio n. 8
0
    def acquire(self, startup=False):
        """
        Returns the time when the lock is acquired or
        None if cron already running

        lock is implemented by writing a pickle (start, stop) in cron.master
        start is time when cron job starts and stop is time when cron completed
        stop == 0 if job started but did not yet complete
        if a cron job started within less than 60 seconds, acquire returns None
        if a cron job started before 60 seconds and did not stop,
        a warning is issued ("Stale cron.master detected")
        """
        if sys.platform == 'win32':
            locktime = 59.5
        else:
            locktime = 59.99
        if portalocker.LOCK_EX is None:
            self.logger.warning('cron disabled because no file locking')
            return None
        self.master = fileutils.open_file(self.path, 'rb+')
        ret = None
        try:
            portalocker.lock(self.master, portalocker.LOCK_EX)
            try:
                (start, stop) = pickle.load(self.master)
            except:
                start = 0
                stop = 1
            if startup or self.now - start > locktime:
                ret = self.now
                if not stop:
                    # this happens if previous cron job longer than 1 minute
                    self.logger.warning('stale cron.master detected')
                self.logger.debug('acquiring lock')
                self.master.seek(0)
                pickle.dump((self.now, 0), self.master)
                self.master.flush()
        finally:
            portalocker.unlock(self.master)
        if not ret:
            # do this so no need to release
            self.master.close()
        return ret
Esempio n. 9
0
 def run_view_file_stream(self):
     view_path = os.path.join(self.env['request'].folder, 'views', 'appadmin.html')
     self.env['response'].view = open_file(view_path, 'r')
     return run_view_in(self.env)
Esempio n. 10
0
def create(options):
    if DEMO_MODE:
        session.flash = T('disabled in demo mode')
        redirect(URL('step6'))
    params = dict(session.app['params'])
    app = session.app['name']
    if app_create(app, request, force=True, key=params['security_key']):
        if MULTI_USER_MODE:
            db.app.insert(name=app, owner=auth.user.id)
    else:
        session.flash = 'Failure to create application'
        redirect(URL('step6'))

    ### save metadata in newapp/wizard.metadata
    try:
        meta = os.path.join(request.folder, '..', app, 'wizard.metadata')
        file = open_file(meta, 'wb')
        pickle.dump(session.app, file)
        file.close()
    except IOError:
        session.flash = 'Failure to write wizard metadata'
        redirect(URL('step6'))

    ### apply theme
    if options.apply_layout and params['layout_theme'] != 'Default':
        try:
            fn = 'web2py.plugin.layout_%s.w2p' % params['layout_theme']
            theme = urllib.urlopen(
                LAYOUTS_APP + '/static/plugin_layouts/plugins/' + fn)
            plugin_install(app, theme, request, fn)
        except:
            session.flash = T("unable to download layout")

    ### apply plugins
    for plugin in params['plugins']:
        try:
            plugin_name = 'web2py.plugin.' + plugin + '.w2p'
            stream = urllib.urlopen(PLUGINS_APP + '/static/' + plugin_name)
            plugin_install(app, stream, request, plugin_name)
        except Exception as e:
            session.flash = T("unable to download plugin: %s" % plugin)

    ### write configuration file into newapp/models/0.py
    model = os.path.join(request.folder, '..', app, 'models', '0.py')
    file = open_file(model, 'w')
    try:
        file.write("from gluon.storage import Storage\n")
        file.write("settings = Storage()\n\n")
        file.write("settings.migrate = True\n")
        for key, value in session.app['params']:
            file.write("settings.%s = %s\n" % (key, repr(value)))
    finally:
        file.close()

    ### write configuration file into newapp/models/menu.py
    if options.generate_menu:
        model = os.path.join(request.folder, '..', app, 'models', 'menu.py')
        file = open_file(model, 'w')
        try:
            file.write(make_menu(session.app['pages']))
        finally:
            file.close()

    ### customize the auth_user table
    model = os.path.join(request.folder, '..', app, 'models', 'db.py')
    fix_db(model)

    ### create newapp/models/db_wizard.py
    if options.generate_model:
        model = os.path.join(
            request.folder, '..', app, 'models', 'db_wizard.py')
        file = open_file(model, 'w')
        try:
            file.write('### we prepend t_ to tablenames and f_ to fieldnames for disambiguity\n\n')
            tables = sort_tables(session.app['tables'])
            for table in tables:
                if table == 'auth_user':
                    continue
                file.write(make_table(table, session.app['table_' + table]))
        finally:
            file.close()

    model = os.path.join(request.folder, '..', app,
                         'models', 'db_wizard_populate.py')
    if os.path.exists(model):
        os.unlink(model)
    if options.populate_database and session.app['tables']:
        file = open_file(model, 'w')
        try:
            file.write(populate(session.app['tables']))
        finally:
            file.close()

    ### create newapp/controllers/default.py
    if options.generate_controller:
        controller = os.path.join(
            request.folder, '..', app, 'controllers', 'default.py')
        file = open_file(controller, 'w')
        try:
            file.write("""# -*- coding: utf-8 -*-
### required - do no delete
def user(): return dict(form=auth())
def download(): return response.download(request,db)
def call(): return service()
### end requires
""")
            for page in session.app['pages']:
                file.write(
                    make_page(page, session.app.get('page_' + page, '')))
        finally:
            file.close()

    ### create newapp/views/default/*.html
    if options.generate_views:
        for page in session.app['pages']:
            view = os.path.join(
                request.folder, '..', app, 'views', 'default', page + '.html')
            file = open_file(view, 'w')
            try:
                file.write(
                    make_view(page, session.app.get('page_' + page, '')))
            finally:
                file.close()

    if options.erase_database:
        path = os.path.join(request.folder, '..', app, 'databases', '*')
        for file in glob.glob(path):
            os.unlink(file)
Esempio n. 11
0
 def run_view_file_stream(self):
     view_path = os.path.join(self.env['request'].folder, 'views',
                              'appadmin.html')
     self.env['response'].view = open_file(view_path, 'r')
     return run_view_in(self.env)
Esempio n. 12
0
def create(options):
    if DEMO_MODE:
        session.flash = T('disabled in demo mode')
        redirect(URL('step6'))
    params = dict(session.app['params'])
    app = session.app['name']
    if app_create(app, request, force=True, key=params['security_key']):
        if MULTI_USER_MODE:
            db.app.insert(name=app, owner=auth.user.id)
    else:
        session.flash = 'Failure to create application'
        redirect(URL('step6'))

    ### save metadata in newapp/wizard.metadata
    try:
        meta = os.path.join(request.folder, '..', app, 'wizard.metadata')
        file = open_file(meta, 'wb')
        pickle.dump(session.app, file)
        file.close()
    except IOError:
        session.flash = 'Failure to write wizard metadata'
        redirect(URL('step6'))

    ### apply theme
    if options.apply_layout and params['layout_theme'] != 'Default':
        try:
            fn = 'web2py.plugin.layout_%s.w2p' % params['layout_theme']
            theme = urllib.urlopen(LAYOUTS_APP +
                                   '/static/plugin_layouts/plugins/' + fn)
            plugin_install(app, theme, request, fn)
        except:
            session.flash = T("unable to download layout")

    ### apply plugins
    for plugin in params['plugins']:
        try:
            plugin_name = 'web2py.plugin.' + plugin + '.w2p'
            stream = urllib.urlopen(PLUGINS_APP + '/static/' + plugin_name)
            plugin_install(app, stream, request, plugin_name)
        except Exception as e:
            session.flash = T("unable to download plugin: %s" % plugin)

    ### write configuration file into newapp/models/0.py
    model = os.path.join(request.folder, '..', app, 'models', '0.py')
    file = open_file(model, 'w')
    try:
        file.write("from gluon.storage import Storage\n")
        file.write("settings = Storage()\n\n")
        file.write("settings.migrate = True\n")
        for key, value in session.app['params']:
            file.write("settings.%s = %s\n" % (key, repr(value)))
    finally:
        file.close()

    ### write configuration file into newapp/models/menu.py
    if options.generate_menu:
        model = os.path.join(request.folder, '..', app, 'models', 'menu.py')
        file = open_file(model, 'w')
        try:
            file.write(make_menu(session.app['pages']))
        finally:
            file.close()

    ### customize the auth_user table
    model = os.path.join(request.folder, '..', app, 'models', 'db.py')
    fix_db(model)

    ### create newapp/models/db_wizard.py
    if options.generate_model:
        model = os.path.join(request.folder, '..', app, 'models',
                             'db_wizard.py')
        file = open_file(model, 'w')
        try:
            file.write(
                '### we prepend t_ to tablenames and f_ to fieldnames for disambiguity\n\n'
            )
            tables = sort_tables(session.app['tables'])
            for table in tables:
                if table == 'auth_user':
                    continue
                file.write(make_table(table, session.app['table_' + table]))
        finally:
            file.close()

    model = os.path.join(request.folder, '..', app, 'models',
                         'db_wizard_populate.py')
    if os.path.exists(model):
        os.unlink(model)
    if options.populate_database and session.app['tables']:
        file = open_file(model, 'w')
        try:
            file.write(populate(session.app['tables']))
        finally:
            file.close()

    ### create newapp/controllers/default.py
    if options.generate_controller:
        controller = os.path.join(request.folder, '..', app, 'controllers',
                                  'default.py')
        file = open_file(controller, 'w')
        try:
            file.write("""# -*- coding: utf-8 -*-
### required - do no delete
def user(): return dict(form=auth())
def download(): return response.download(request,db)
def call(): return service()
### end requires
""")
            for page in session.app['pages']:
                file.write(make_page(page, session.app.get('page_' + page,
                                                           '')))
        finally:
            file.close()

    ### create newapp/views/default/*.html
    if options.generate_views:
        for page in session.app['pages']:
            view = os.path.join(request.folder, '..', app, 'views', 'default',
                                page + '.html')
            file = open_file(view, 'w')
            try:
                file.write(make_view(page, session.app.get('page_' + page,
                                                           '')))
            finally:
                file.close()

    if options.erase_database:
        path = os.path.join(request.folder, '..', app, 'databases', '*')
        for file in glob.glob(path):
            os.unlink(file)
Esempio n. 13
0
 def openfile():
     import os
     path = os.path.join(request.folder, 'private', 'content', l, c, f,
                         b + '.' + format)
     return open_file(path, mode='r')
Esempio n. 14
0
 def openfile():
     import os
     path = os.path.join(
         request.folder, 'private', 'content', l, c, f, b + '.' + format)
     return open_file(path, mode='r')