• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python utils.web2py_uuid函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中utils.web2py_uuid函数的典型用法代码示例。如果您正苦于以下问题:Python web2py_uuid函数的具体用法?Python web2py_uuid怎么用?Python web2py_uuid使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了web2py_uuid函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: toolbar

 def toolbar(self):
     from html import DIV, SCRIPT, BEAUTIFY, TAG, URL
     BUTTON = TAG.button
     admin = URL("admin","default","design",
                 args=current.request.application)
     from gluon.dal import thread
     if hasattr(thread,'instances'):
         dbstats = [TABLE(*[TR(PRE(row[0]),'%.2fms' % (row[1]*1000)) \
                                for row in i.db._timings]) \
                        for i in thread.instances]
     else:
         dbstats = [] # if no db or on GAE
     u = web2py_uuid()
     return DIV(
         BUTTON('design',_onclick="document.location='%s'" % admin),
         BUTTON('request',_onclick="jQuery('#request-%s').slideToggle()"%u),
         DIV(BEAUTIFY(current.request),_class="hidden",_id="request-%s"%u),
         BUTTON('session',_onclick="jQuery('#session-%s').slideToggle()"%u),
         DIV(BEAUTIFY(current.session),_class="hidden",_id="session-%s"%u),
         BUTTON('response',_onclick="jQuery('#response-%s').slideToggle()"%u),
         DIV(BEAUTIFY(current.response),_class="hidden",_id="response-%s"%u),
         BUTTON('db stats',_onclick="jQuery('#db-stats-%s').slideToggle()"%u),
         DIV(BEAUTIFY(dbstats),_class="hidden",_id="db-stats-%s"%u),
         SCRIPT("jQuery('.hidden').hide()")
         )
开发者ID:LOSC,项目名称:LOSCHome,代码行数:25,代码来源:globals.py


示例2: app_create

def app_create(app, request):
    """
    Create a copy of welcome.w2p (scaffolding) app

    Parameters
    ----------
    app:
        application name
    request:
        the global request object

    """
    did_mkdir = False
    try:
        path = apath(app, request)
        os.mkdir(path)
        did_mkdir = True
        w2p_unpack('welcome.w2p', path)
        db = os.path.join(path,'models/db.py')
        if os.path.exists(db):
            fp = open(db,'r')
            data = fp.read()
            fp.close()
            data = data.replace('<your secret key>','sha512:'+web2py_uuid())
            fp = open(db,'w')
            fp.write(data)
            fp.close()
        return True
    except:
        if did_mkdir:
            rmtree(path)
        return False
开发者ID:BlackgateResearch,项目名称:Pip-Target,代码行数:32,代码来源:admin.py


示例3: log

    def log(self, request):
        """
        logs the exception.
        """

        try:
            a = request.application
            d = {
                'layer': str(self.layer),
                'code': str(self.code),
                'output': str(self.output),
                'traceback': str(self.traceback),
                'snapshot': self.snapshot,
                }
            fmt = '%Y-%m-%d.%H-%M-%S'
            f = '%s.%s.%s' % (request.client.replace(':', '_'),
                              datetime.datetime.now().strftime(fmt),
                              web2py_uuid())

            ticket_storage = TicketStorage(db=request.tickets_db)
            ticket_storage.store(request, f, d)
            return '%s/%s' % (a, f)
        except:
            logging.error(self.traceback)
            return None
开发者ID:fmobus,项目名称:forca-inf,代码行数:25,代码来源:restricted.py


示例4: accepts

    def accepts(
        self,
        vars,
        session=None,
        formname='default',
        keepvalues=False,
        onvalidation=None,
        ):
        self.errors.clear()
        self.request_vars = Storage()
        self.request_vars.update(vars)
        self.session = session
        self.formname = formname
        self.keepvalues = keepvalues

        # if this tag is a form and we are in accepting mode (status=True)
        # check formname and formkey

        status = True
        if self.session and self.session.get('_formkey[%s]'
                 % self.formname, None) != self.request_vars._formkey:
            status = False
        if self.formname != self.request_vars._formname:
            status = False
        status = self._traverse(status)
        if status and onvalidation:
            onvalidation(self)
        if self.errors:
            status = False
        if session != None:
            self.formkey = session['_formkey[%s]' % formname] = web2py_uuid()
        if status and not keepvalues:
            self._traverse(False)
        return status
开发者ID:Viper525,项目名称:sonospy,代码行数:34,代码来源:html.py


示例5: _try_store_in_db

    def _try_store_in_db(self, request, response):
        # don't save if file-based sessions,
        # no session id, or session being forgotten
        # or no changes to session

        if not response.session_db_table or self._forget or self._unchanged():
            if (not response.session_db_table and
                global_settings.db_sessions is not True and
                response.session_masterapp in global_settings.db_sessions):
                global_settings.db_sessions.remove(response.session_masterapp)
            return False

        table = response.session_db_table
        record_id = response.session_db_record_id
        if response.session_new:
            unique_key = web2py_uuid()
        else:
            unique_key = response.session_db_unique_key

        dd = dict(locked=False,
                  client_ip=response.session_client,
                  modified_datetime=request.now,
                  session_data=cPickle.dumps(dict(self)),
                  unique_key=unique_key)
        if record_id:
            table(record_id).update_record(**dd)
        if not record_id:
            record_id = table.insert(**dd)
            response.session_id = '%s:%s' % (record_id, unique_key)
            response.session_db_unique_key = unique_key
            response.session_db_record_id = record_id

        self.save_session_id_cookie()
        return True
开发者ID:abcsun,项目名称:web2py,代码行数:34,代码来源:globals.py


示例6: toolbar

    def toolbar(self):
        from html import DIV, SCRIPT, BEAUTIFY, TAG, URL, A

        BUTTON = TAG.button
        admin = URL("admin", "default", "design", args=current.request.application)
        from gluon.dal import DAL

        dbstats = []
        dbtables = {}
        infos = DAL.get_instances()
        for k, v in infos.iteritems():
            dbstats.append(TABLE(*[TR(PRE(row[0]), "%.2fms" % (row[1] * 1000)) for row in v["dbstats"]]))
            dbtables[k] = dict(
                defined=v["dbtables"]["defined"] or "[no defined tables]",
                lazy=v["dbtables"]["lazy"] or "[no lazy tables]",
            )
        u = web2py_uuid()
        backtotop = A("Back to top", _href="#totop-%s" % u)
        return DIV(
            BUTTON("design", _onclick="document.location='%s'" % admin),
            BUTTON("request", _onclick="jQuery('#request-%s').slideToggle()" % u),
            BUTTON("response", _onclick="jQuery('#response-%s').slideToggle()" % u),
            BUTTON("session", _onclick="jQuery('#session-%s').slideToggle()" % u),
            BUTTON("db tables", _onclick="jQuery('#db-tables-%s').slideToggle()" % u),
            BUTTON("db stats", _onclick="jQuery('#db-stats-%s').slideToggle()" % u),
            DIV(BEAUTIFY(current.request), backtotop, _class="hidden", _id="request-%s" % u),
            DIV(BEAUTIFY(current.session), backtotop, _class="hidden", _id="session-%s" % u),
            DIV(BEAUTIFY(current.response), backtotop, _class="hidden", _id="response-%s" % u),
            DIV(BEAUTIFY(dbtables), backtotop, _class="hidden", _id="db-tables-%s" % u),
            DIV(BEAUTIFY(dbstats), backtotop, _class="hidden", _id="db-stats-%s" % u),
            SCRIPT("jQuery('.hidden').hide()"),
            _id="totop-%s" % u,
        )
开发者ID:jeffreywugz,项目名称:web2py,代码行数:33,代码来源:globals.py


示例7: compute_uuid

 def compute_uuid(self):
     self.uuid = "%s/%s.%s.%s" % (
         self.application,
         self.client.replace(":", "_"),
         self.now.strftime("%Y-%m-%d.%H-%M-%S"),
         web2py_uuid(),
     )
     return self.uuid
开发者ID:owenwaller,项目名称:web2py,代码行数:8,代码来源:globals.py


示例8: app_create

def app_create(app, request, force=False, key=None, info=False):
    """
    Create a copy of welcome.w2p (scaffolding) app

    Parameters
    ----------
    app:
        application name
    request:
        the global request object

    """
    path = apath(app, request)
    if not os.path.exists(path):
        try:
            os.mkdir(path)
        except:
            if info:
                return False, traceback.format_exc(sys.exc_info)
            else:
                return False
    elif not force:
        if info:
            return False, "Application exists"
        else:
            return False
    try:
        w2p_unpack('welcome.w2p', path)
        for subfolder in [
            'models', 'views', 'controllers', 'databases',
            'modules', 'cron', 'errors', 'sessions', 'cache',
            'languages', 'static', 'private', 'uploads']:
            subpath = os.path.join(path, subfolder)
            if not os.path.exists(subpath):
                os.mkdir(subpath)
        db = os.path.join(path, 'models', 'db.py')
        if os.path.exists(db):
            data = read_file(db)
            data = data.replace('<your secret key>',
                                'sha512:' + (key or web2py_uuid()))
            write_file(db, data)
        if info:
            return True, None
        else:
            return True
    except:
        rmtree(path)
        if info:
            return False, traceback.format_exc(sys.exc_info)
        else:
            return False
开发者ID:PopoWow,项目名称:web2py,代码行数:51,代码来源:admin.py


示例9: run

def run(
    appname,
    plain=False,
    import_models=False,
    startfile=None,
    ):
    """
    Start interactive shell or run Python script (startfile) in web2py
    controller environment. appname is formatted like:

    a      web2py application name
    a/c    exec the controller c into the application environment
    """

    (a, c, f) = parse_path_info(appname)
    errmsg = 'invalid application name: %s' % appname
    if not a:
        die(errmsg)
    adir = os.path.join('applications', a)
    if not os.path.exists(adir):
        if raw_input('application %s does not exist, create (y/n)?'
                      % a).lower() in ['y', 'yes']:
            os.mkdir(adir)
            w2p_unpack('welcome.w2p', adir)
            db = os.path.join(adir,'models/db.py')
            if os.path.exists(db):
                fp = open(db,'r')
                data = fp.read()
                fp.close()
                data = data.replace('<your secret key>','sha512:'+web2py_uuid())
                fp = open(db,'w')
                fp.write(data)
                fp.close()

    if c:
        import_models = True
    _env = env(a, c=c, import_models=import_models)
    if c:
        cfile = os.path.join('applications', a, 'controllers', c + '.py')
        if not os.path.isfile(cfile):
            die(errmsg)
        execfile(cfile, _env)

    if f:
        exec ('print %s()' % f, _env)
    elif startfile:
        exec_pythonrc()
        try:
            execfile(startfile, _env)
        except RestrictedError, e:
            print e.traceback
开发者ID:BlackgateResearch,项目名称:Pip-Target,代码行数:51,代码来源:shell.py


示例10: POST

    def POST(rp_user):
        doc = POST.func_doc
        return_dict = dict(doc=doc)
        user_dict = {}

        logger.debug("rp_user: " + str(rp_user))

        user_mail = rp_user["mail"]
        table_user = auth.settings.table_user
        user = auth.db(table_user.email == user_mail).select().first()
        if not user:
            msg = "Cannot reset password. Mail not registered"
            return_dict["err_found"] = True
            return_dict["err_msg"] = msg
            return gluon.contrib.simplejson.dumps(return_dict)
        elif user.registration_key in ["pending", "disabled"]:
            msg = "Cannot reset password. User registration pending or disabled"
            return_dict["err_found"] = True
            return_dict["err_msg"] = msg
            return gluon.contrib.simplejson.dumps(return_dict)

        reset_password_key = str(int(time.time())) + "-" + web2py_uuid()

        # link = auth.url(auth.settings.function,
        #                 args=('reset_password',),
        #                 vars={'key': reset_password_key},
        #                 scheme=True)
        # d = dict(user)
        # d.update(dict(key=reset_password_key, link=link))

        main_url = "http://" + str(request.env.http_host) + "/" + str(request.application)
        reset_msg = (
            "Click on the link "
            + main_url
            + "/routes/#/logging/user_resetpasswd?key="
            + reset_password_key
            + " to reset your password"
        )
        if auth.settings.mailer and auth.settings.mailer.send(
            to=user_mail, subject=auth.messages.reset_password_subject, message=reset_msg
        ):
            # message=auth.messages.reset_password % d):
            user.update_record(reset_password_key=reset_password_key)
        else:
            msg = "Cannot complete the password reset request. Cannot send mail"
            return_dict["err_found"] = True
            return_dict["err_msg"] = msg
            return gluon.contrib.simplejson.dumps(return_dict)

        return gluon.contrib.simplejson.dumps(return_dict)
开发者ID:francescosalvadore,项目名称:web2py_angularized,代码行数:50,代码来源:logging.py


示例11: toolbar

 def toolbar(self):
     from html import DIV, SCRIPT, BEAUTIFY, TAG, URL, A
     BUTTON = TAG.button
     admin = URL("admin", "default", "design",
                 args=current.request.application)
     from gluon.dal import DAL
     dbstats = []
     dbtables = {}
     infos = DAL.get_instances()
     for k,v in infos.iteritems():
         dbstats.append(TABLE(*[TR(PRE(row[0]),'%.2fms' %
                                       (row[1]*1000))
                                        for row in v['dbstats']]))
         dbtables[k] = dict(defined=v['dbtables']['defined'] or '[no defined tables]',
                            lazy=v['dbtables']['lazy'] or '[no lazy tables]')
     u = web2py_uuid()
     backtotop = A('Back to top', _href="#totop-%s" % u)
     # Convert lazy request.vars from property to Storage so they
     # will be displayed in the toolbar.
     request = copy.copy(current.request)
     request.update(vars=current.request.vars,
         get_vars=current.request.get_vars,
         post_vars=current.request.post_vars)
     return DIV(
         BUTTON('design', _onclick="document.location='%s'" % admin),
         BUTTON('request',
                _onclick="jQuery('#request-%s').slideToggle()" % u),
         BUTTON('response',
                _onclick="jQuery('#response-%s').slideToggle()" % u),
         BUTTON('session',
                _onclick="jQuery('#session-%s').slideToggle()" % u),
         BUTTON('db tables',
                _onclick="jQuery('#db-tables-%s').slideToggle()" % u),
         BUTTON('db stats',
                _onclick="jQuery('#db-stats-%s').slideToggle()" % u),
         DIV(BEAUTIFY(request), backtotop,
             _class="hidden", _id="request-%s" % u),
         DIV(BEAUTIFY(current.session), backtotop,
             _class="hidden", _id="session-%s" % u),
         DIV(BEAUTIFY(current.response), backtotop,
             _class="hidden", _id="response-%s" % u),
         DIV(BEAUTIFY(dbtables), backtotop, _class="hidden",
             _id="db-tables-%s" % u),
         DIV(BEAUTIFY(
             dbstats), backtotop, _class="hidden", _id="db-stats-%s" % u),
         SCRIPT("jQuery('.hidden').hide()"), _id="totop-%s" % u
     )
开发者ID:hungl,项目名称:web2py,代码行数:47,代码来源:globals.py


示例12: app_with_logging

    def app_with_logging(environ, responder):
        """
        a wsgi app that does logging and profiling and calls wsgibase
        """
        status_headers = []

        def responder2(s, h):
            """
            wsgi responder app
            """
            status_headers.append(s)
            status_headers.append(h)
            return responder(s, h)

        time_in = time.time()
        ret = [0]
        if not profiler_dir:
            ret[0] = wsgiapp(environ, responder2)
        else:
            import cProfile
            prof = cProfile.Profile()
            prof.enable()
            ret[0] = wsgiapp(environ, responder2)
            prof.disable()
            destfile = pjoin(profiler_dir, "req_%s.prof" % web2py_uuid())
            prof.dump_stats(destfile)

        try:
            line = '%s, %s, %s, %s, %s, %s, %f\n' % (
                environ['REMOTE_ADDR'],
                datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S'),
                environ['REQUEST_METHOD'],
                environ['PATH_INFO'].replace(',', '%2C'),
                environ['SERVER_PROTOCOL'],
                (status_headers[0])[:3],
                time.time() - time_in,
            )
            if not logfilename:
                sys.stdout.write(line)
            elif isinstance(logfilename, str):
                write_file(logfilename, line, 'a')
            else:
                logfilename.write(line)
        except:
            pass
        return ret[0]
开发者ID:hungl,项目名称:web2py,代码行数:46,代码来源:main.py


示例13: app_create

def app_create(app, request,force=False,key=None):
    """
    Create a copy of welcome.w2p (scaffolding) app

    Parameters
    ----------
    app:
        application name
    request:
        the global request object

    """
    did_mkdir = False
    try:
        path = apath(app, request)
        os.mkdir(path)
    except:
        if not force:
            return False
    try:
        w2p_unpack('welcome.w2p', path)
        for subfolder in ['models','views','controllers', 'databases',
                          'modules','cron','errors','sessions',
                          'languages','static','private','uploads']:
            subpath =  os.path.join(path,subfolder)
            if not os.path.exists(subpath):
                os.mkdir(subpath)
        db = os.path.join(path, 'models', 'db.py')
        if os.path.exists(db):
            fp = open(db,'r')
            data = fp.read()
            fp.close()
            data = data.replace('<your secret key>',
                                'sha512:'+(key or web2py_uuid()))
            fp = open(db,'w')
            fp.write(data)
            fp.close()
        return True
    except:
        rmtree(path)
        return False
开发者ID:trosa,项目名称:listool,代码行数:41,代码来源:admin.py


示例14: connect

    def connect(
        self,
        request,
        response,
        db=None,
        tablename='web2py_session',
        masterapp=None,
        migrate=True,
        ):
        self._unlock(response)
        if not masterapp:
            masterapp = request.application
        response.session_id_name = 'session_id_%s' % masterapp
        if not db:
            if response.session_id_name in request.cookies:
                response.session_id = \
                    request.cookies[response.session_id_name].value
                if regex_session_id.match(response.session_id):
                    response.session_filename = \
                        os.path.join(up(request.folder), masterapp,
                            'sessions', response.session_id)
                else:
                    response.session_id = None
            if response.session_id:
                try:
                    response.session_file = \
                        open(response.session_filename, 'rb+')
                    portalocker.lock(response.session_file,
                            portalocker.LOCK_EX)
                    self.update(cPickle.load(response.session_file))
                    response.session_file.seek(0)
                except:
                    self._unlock(response)
                    response.session_id = None
            if not response.session_id:
                response.session_id = '%s-%s'\
                     % (request.client.replace(':', '-').replace('.',
                        '-'), web2py_uuid())
                response.session_filename = \
                    os.path.join(up(request.folder), masterapp,
                                 'sessions', response.session_id)
                response.session_new = True
        else:
            if settings.web2py_runtime_gae:
                # in principle this could work without GAE
                request.tickets_db = db
            if masterapp == request.application:
                table_migrate = migrate
            else:
                table_migrate = False
            tname = tablename + '_' + masterapp
            table = db.get(tname, None)
            if table is None:
                table = db.define_table(
                    tname,
                    db.Field('locked', 'boolean', default=False),
                    db.Field('client_ip', length=64),
                    db.Field('created_datetime', 'datetime',
                             default=request.now),
                    db.Field('modified_datetime', 'datetime'),
                    db.Field('unique_key', length=64),
                    db.Field('session_data', 'blob'),
                    migrate=table_migrate,
                    )
            try:
                key = request.cookies[response.session_id_name].value
                (record_id, unique_key) = key.split(':')
                if record_id == '0':
                    raise Exception, 'record_id == 0'
                rows = db(table.id == record_id).select()
                if len(rows) == 0 or rows[0].unique_key != unique_key:
                    raise Exception, 'No record'

                 # rows[0].update_record(locked=True)

                session_data = cPickle.loads(rows[0].session_data)
                self.update(session_data)
            except Exception:
                record_id = None
                unique_key = web2py_uuid()
                session_data = {}
            response._dbtable_and_field = \
                (response.session_id_name, table, record_id, unique_key)
            response.session_id = '%s:%s' % (record_id, unique_key)
        response.cookies[response.session_id_name] = response.session_id
        response.cookies[response.session_id_name]['path'] = '/'
        if self.flash:
            (response.flash, self.flash) = (self.flash, None)
开发者ID:Viper525,项目名称:sonospy,代码行数:88,代码来源:globals.py


示例15: run

def run(appname, plain=False, import_models=False, startfile=None, bpython=False, python_code=False):
    """
    Start interactive shell or run Python script (startfile) in web2py
    controller environment. appname is formatted like:

    a      web2py application name
    a/c    exec the controller c into the application environment
    """

    (a, c, f) = parse_path_info(appname)
    errmsg = "invalid application name: %s" % appname
    if not a:
        die(errmsg)
    adir = os.path.join("applications", a)
    if not os.path.exists(adir):
        if raw_input("application %s does not exist, create (y/n)?" % a).lower() in ["y", "yes"]:
            os.mkdir(adir)
            w2p_unpack("welcome.w2p", adir)
            for subfolder in [
                "models",
                "views",
                "controllers",
                "databases",
                "modules",
                "cron",
                "errors",
                "sessions",
                "languages",
                "static",
                "private",
                "uploads",
            ]:
                subpath = os.path.join(adir, subfolder)
                if not os.path.exists(subpath):
                    os.mkdir(subpath)
            db = os.path.join(adir, "models/db.py")
            if os.path.exists(db):
                data = fileutils.read_file(db)
                data = data.replace("<your secret key>", "sha512:" + web2py_uuid())
                fileutils.write_file(db, data)

    if c:
        import_models = True
    _env = env(a, c=c, f=f, import_models=import_models)
    if c:
        cfile = os.path.join("applications", a, "controllers", c + ".py")
        if not os.path.isfile(cfile):
            cfile = os.path.join("applications", a, "compiled", "controllers_%s_%s.pyc" % (c, f))
            if not os.path.isfile(cfile):
                die(errmsg)
            else:
                exec read_pyc(cfile) in _env
        else:
            execfile(cfile, _env)

    if f:
        exec ("print %s()" % f, _env)
        return

    # "woodoo magic" workaround: reinitialize main.py
    g = {}
    exec "import main" in g
    del g

    _env.update(exec_pythonrc())
    if startfile:
        try:
            execfile(startfile, _env)
            if import_models:
                BaseAdapter.close_all_instances("commit")
        except Exception, e:
            print traceback.format_exc()
            if import_models:
                BaseAdapter.close_all_instances("rollback")
开发者ID:toomim,项目名称:utility,代码行数:74,代码来源:shell.py


示例16: run

def run(
    appname,
    plain=False,
    import_models=False,
    startfile=None,
    bpython=False,
    python_code=False,
    cronjob=False):
    """
    Start interactive shell or run Python script (startfile) in web2py
    controller environment. appname is formatted like:

    a      web2py application name
    a/c    exec the controller c into the application environment
    """

    (a, c, f, args, vars) = parse_path_info(appname, av=True)
    errmsg = 'invalid application name: %s' % appname
    if not a:
        die(errmsg)
    adir = os.path.join('applications', a)

    if not os.path.exists(adir):
        if sys.stdin and not sys.stdin.name == '/dev/null':
            confirm = raw_input(
                'application %s does not exist, create (y/n)?' % a)
        else:
            logging.warn('application does not exist and will not be created')
            return
        if confirm.lower() in ['y', 'yes']:

            os.mkdir(adir)
            w2p_unpack('welcome.w2p', adir)
            for subfolder in ['models', 'views', 'controllers', 'databases',
                              'modules', 'cron', 'errors', 'sessions',
                              'languages', 'static', 'private', 'uploads']:
                subpath = os.path.join(adir, subfolder)
                if not os.path.exists(subpath):
                    os.mkdir(subpath)
            db = os.path.join(adir, 'models/db.py')
            if os.path.exists(db):
                data = fileutils.read_file(db)
                data = data.replace(
                    '<your secret key>', 'sha512:' + web2py_uuid())
                fileutils.write_file(db, data)

    if c:
        import_models = True
    extra_request = {}
    if args:
        extra_request['args'] = args
    if vars:
        extra_request['vars'] = vars
    _env = env(a, c=c, f=f, import_models=import_models, extra_request=extra_request)
    if c:
        pyfile = os.path.join('applications', a, 'controllers', c + '.py')
        pycfile = os.path.join('applications', a, 'compiled',
                                 "controllers_%s_%s.pyc" % (c, f))
        if ((cronjob and os.path.isfile(pycfile)) 
            or not os.path.isfile(pyfile)):
            exec read_pyc(pycfile) in _env
        elif os.path.isfile(pyfile):
            execfile(pyfile, _env)
        else:
            die(errmsg)

    if f:
        exec ('print %s()' % f, _env)
        return

    _env.update(exec_pythonrc())
    if startfile:
        try:
            ccode = None
            if startfile.endswith('.pyc'):
                ccode = read_pyc(startfile)
                exec ccode in _env
            else:
                execfile(startfile, _env)

            if import_models:
                BaseAdapter.close_all_instances('commit')
        except Exception, e:
            print traceback.format_exc()
            if import_models:
                BaseAdapter.close_all_instances('rollback')
开发者ID:BinweiRu,项目名称:web2py,代码行数:86,代码来源:shell.py


示例17: connect

    def connect(
        self,
        request,
        response,
        db=None,
        tablename='web2py_session',
        masterapp=None,
        migrate=True,
        separate = None,
        check_client=False,
        ):
        """
        separate can be separate=lambda(session_name): session_name[-2:]
        and it is used to determine a session prefix.
        separate can be True and it is set to session_name[-2:]
        """
        if separate == True:
            separate = lambda session_name: session_name[-2:]
        self._unlock(response)
        if not masterapp:
            masterapp = request.application
        response.session_id_name = 'session_id_%s' % masterapp.lower()

        if not db:
            if global_settings.db_sessions is True or masterapp in global_settings.db_sessions:
                return
            response.session_new = False
            client = request.client and request.client.replace(':', '.')
            if response.session_id_name in request.cookies:
                response.session_id = \
                    request.cookies[response.session_id_name].value
                if regex_session_id.match(response.session_id):
                    response.session_filename = \
                        os.path.join(up(request.folder), masterapp,
                            'sessions', response.session_id)
                else:
                    response.session_id = None
            if response.session_id:
                try:
                    response.session_file = \
                        open(response.session_filename, 'rb+')
                    try:
                        portalocker.lock(response.session_file,portalocker.LOCK_EX)
                        response.session_locked = True
                        self.update(cPickle.load(response.session_file))
                        response.session_file.seek(0)
                        oc = response.session_filename.split('/')[-1].split('-')[0]
                        if check_client and client!=oc:
                            raise Exception, "cookie attack"
                    finally:
                        pass
                        #This causes admin login to break. Must find out why.
                        #self._close(response)
                except:
                    response.session_id = None
            if not response.session_id:
                uuid = web2py_uuid()
                response.session_id = '%s-%s' % (client, uuid)
                if separate:
                    prefix = separate(response.session_id)
                    response.session_id = '%s/%s' % (prefix,response.session_id)
                response.session_filename = \
                    os.path.join(up(request.folder), masterapp,
                                 'sessions', response.session_id)
                response.session_new = True
        else:
            if global_settings.db_sessions is not True:
                global_settings.db_sessions.add(masterapp)
            response.session_db = True
            if response.session_file:
                self._close(response)
            if settings.global_settings.web2py_runtime_gae:
                # in principle this could work without GAE
                request.tickets_db = db
            if masterapp == request.application:
                table_migrate = migrate
            else:
                table_migrate = False
            tname = tablename + '_' + masterapp
            table = db.get(tname, None)
            if table is None:
                table = db.define_table(
                    tname,
                    db.Field('locked', 'boolean', default=False),
                    db.Field('client_ip', length=64),
                    db.Field('created_datetime', 'datetime',
                             default=request.now),
                    db.Field('modified_datetime', 'datetime'),
                    db.Field('unique_key', length=64),
                    db.Field('session_data', 'blob'),
                    migrate=table_migrate,
                    )
            try:
                key = request.cookies[response.session_id_name].value
                (record_id, unique_key) = key.split(':')
                if record_id == '0':
                    raise Exception, 'record_id == 0'
                rows = db(table.id == record_id).select()
                if len(rows) == 0 or rows[0].unique_key != unique_key:
                    raise Exception, 'No record'
#.........这里部分代码省略.........
开发者ID:LOSC,项目名称:LOSCHome,代码行数:101,代码来源:globals.py


示例18: connect

    def connect(
        self,
        request,
        response,
        db=None,
        tablename='web2py_session',
        masterapp=None,
        migrate=True,
        separate = None,
        check_client=False,
        cookie_key=None,
        ):
        """
        separate can be separate=lambda(session_name): session_name[-2:]
        and it is used to determine a session prefix.
        separate can be True and it is set to session_name[-2:]
        """
        if separate == True:
            separate = lambda session_name: session_name[-2:]
        self._unlock(response)
        if not masterapp:
            masterapp = request.application
        response.session_id_name = 'session_id_%s' % masterapp.lower()

        # Load session data from cookie
        cookies = request.cookies
            
        if cookie_key:
            response.session_cookie_key = cookie_key
            response.session_cookie_key2 = hashlib.md5(cookie_key).digest()
            cookie_name = masterapp.lower()+'_session_data'
            response.session_cookie_name = cookie_name
            if cookie_name in cookies:
                cookie_value = cookies[cookie_name].value
                cookie_parts = cookie_value.split(":")
                enc = cookie_parts[2]
                cipher = AES.new(cookie_key)
                decrypted = cipher.decrypt(base64.b64decode(enc)).rstrip('{')
                check = hmac.new(response.session_cookie_key2,enc).hexdigest()
                if cookie_parts[0] == check:
                    session_data = cPickle.loads(decrypted)
                    self.update(session_data)
            else:
                return

        if not db:
            if global_settings.db_sessions is True \
                    or masterapp in global_settings.db_sessions:
                return
            response.session_new = False
            client = request.client and request.client.replace(':', '.')
            if response.session_id_name in cookies:
                response.session_id = \
                    cookies[response.session_id_name].value
                if regex_session_id.match(response.session_id):
                    response.session_filename = \
                        os.path.join(up(request.folder), masterapp,
                            'sessions', response.session_id)
                else:
                    response.session_id = None
            if response.session_id:
                try:
                    response.session_file = \
                        open(response.session_filename, 'rb+')
                    try:
                        portalocker.lock(response.session_file,
                                         portalocker.LOCK_EX)
                        response.session_locked = True
                        self.update(cPickle.load(response.session_file))
                        response.session_file.seek(0)
                        oc = response.session_filename.split('/')[-1]\
                            .split('-')[0]
                        if check_client and client!=oc:
                            raise Exception, "cookie attack"
                    finally:
                        pass
                        #This causes admin login to break. Must find out why.
                        #self._close(response)
                except:
                    response.session_id = None
            if not response.session_id:
                uuid = web2py_uuid()
                response.session_id = '%s-%s' % (client, uuid)
                if separate:
                    prefix = separate(response.session_id)
                    response.session_id = '%s/%s' % \
                        (prefix,response.session_id)
                response.session_filename = \
                    os.path.join(up(request.folder), masterapp,
                                 'sessions', response.session_id)
                response.session_new = True
        else:
            if global_settings.db_sessions is not True:
                global_settings.db_sessions.add(masterapp)
            response.session_db = True
            if response.session_file:
                self._close(response)
            if settings.global_settings.web2py_runtime_gae:
                # in principle this could work without GAE
                request.tickets_db = db
#.........这里部分代码省略.........
开发者ID:mycguo,项目名称:Charles-Web2Py,代码行数:101,代码来源:globals.py


示例19: app_create

def app_create(app, request, force=False, key=None, info=False):
    """
    Create a copy of welcome.w2p (scaffolding) app

    Parameters
    ----------
    app:
        application name
    request:
        the global request object

    """
    path = apath(app, request)
    if not os.path.exists(path):
        try:
            os.mkdir(path)
        except:
            if info:
                return False, traceback.format_exc(sys.exc_info)
            else:
                return False
    elif not force:
        if info:
            return False, "Application exists"
        else:
            return False
    try:
        w2p_unpack("welcome.w2p", path)
        for subfolder in [
            "models",
            "views",
            "controllers",
  

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python utils.which函数代码示例发布时间:2022-05-27
下一篇:
Python utils.warning函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap