예제 #1
0
파일: Url.py 프로젝트: JPilarr/tapyr
 def __init__(self, value, fs_path=False):
     if isinstance(value, Url):
         self._value = value._value
         self._parsed = TFL.Record(**value._parsed._kw)
     elif self._matcher.match(value):
         self._value = value
         attrs        = dict \
             ( (k, v or "")
             for (k, v) in pyk.iteritems (self._matcher.groupdict ())
             )
         self._parsed = p = TFL.Record(**attrs)
         if fs_path and p.path.startswith("/"):
             p.path = p.path[1:]
     else:
         raise ValueError(value)
예제 #2
0
 def _setup_attr (soc, E_Type, fn, name, op, value, q = None) :
     if q is None :
         try :
             q   = getattr (E_Type.AQ, name)
         except AttributeError as exc :
             raise AttributeError \
                 ( _T ("%s doesn't have an attribute named `%s`")
                 % (E_Type.type_name, name)
                 )
         else :
             ### XXX remove this when query machinery supports cached roles
             if isinstance (q._attr, MOM.Attr.A_Cached_Role) :
                 raise AttributeError \
                     ( _T ("Query for cached role attribute `%s` of %s not yet supported")
                     % (name, E_Type.type_name)
                     )
     qop     = getattr (q, op)
     fq      = qop (value)
     qate    = q.As_Template_Elem
     f       = dict \
         ( qate._kw
         , AQ     = q
         , attr   = q._attr
         , edit   = value
         , id     = fn
         , name   = fn
         , op     = soc._qop_desc (qop)
         , value  = value
         )
     return TFL.Record (** f), fq
예제 #3
0
파일: Field.py 프로젝트: JPilarr/tapyr
 def _gen (self, o, renderer) :
     o_set   = self._value_getter (o)
     as_html = self.__super.as_html
     for elem in o_set :
         oo  = TFL.Record ()
         setattr (oo, self.name, elem)
         vv  = self._as_html_value (oo, renderer)
         yield vv, as_html (oo, renderer)
예제 #4
0
 def Filter (cls, E_Type, key, value = None, default_op = "AC") :
     data  = { key : value }
     t_pat = cls._t_pat
     if t_pat.search (key) :
         name, typ, tail = t_pat.split (key, 1, 2)
         return cls._pepk_filter \
             (E_Type, key, name, typ, tail, value, default_op)
     else :
         request = TFL.Record (req_data = data, req_data_list = data)
         fs, fqs = cls.attr_filters \
             (E_Type, request, data, None, cls._a_pat_opt, default_op)
         if fs :
             return fs [0]
예제 #5
0
파일: Error.py 프로젝트: JPilarr/tapyr
 def __init__ (self, e_type, role, r_obj, epk, * links) :
     self.e_type       = e_type
     self.role         = role
     self.type_name    = e_type.ui_name
     self.l_ui_display = pyk.decoded (pyk.reprify (epk))
     self.r_ui_display = r_obj.ui_repr
     self.extra_links  = tuple \
         ( TFL.Record
             ( pid        = getattr (x, "pid", None)
             , ui_display = pyk.decoded (x.ui_repr)
             , type_name  = _T (x.ui_name)
             )
         for x in links
         )
예제 #6
0
    def name_split (cls, name) :
        """Return parts of `name`.

           The result is a Record with attributes `time`, `proc`, `deli`,
           `host`, and `info`.
        """
        t, _, r = split_hst (name, ".")
        p, _, h = split_hst (r,    ".")
        p, _, d = split_hst (p,    "_")
        h, _, i = split_hst (h,    ":")
        if i :
            if i.startswith ("2,") :
                i = i [2:]
            else :
                i = None
        return TFL.Record (time = t, proc = p, deli = d, host = h, info = i)
예제 #7
0
 def NEW (cls, app_type, scope = None, ** _kw) :
     kw      = dict (_kw)
     Version = app_type.Version
     result  = cls \
         ( creator       = kw.pop ("creator", None) or TFL.Record
             ( date          = pyk.decoded (datetime.datetime.utcnow ())
             , tool_version  = Version.id
             , user          =
                 getattr (scope, "user", None) or TFL.Environment.username
             )
         , dbid          = pyk.decoded (uuid.uuid4 ())
         , dbv_hash      = app_type.db_version_hash
         , guid          =
             kw.pop ("guid", None) or getattr (scope, "guid", None)
         , readonly      = kw.pop  ("readonly", False)
         , root_pid      =
             kw.pop ("root_pid", None) or getattr (scope, "_root_pid", None)
         , ** kw
         )
     return result
예제 #8
0
파일: Error.py 프로젝트: JPilarr/tapyr
 def __init__ (self, obj, inv) :
     self.__super.__init__ (obj)
     self.attributes   = sorted (inv.attributes + inv.attr_none)
     self.count        = len (inv.clashes)
     self.extra_links  = tuple \
         ( TFL.Record
             ( pid        = getattr (x, "pid", None)
             , ui_display = pyk.decoded (x.ui_repr)
             , type_name  = _T (x.ui_name)
             )
         for x in inv.extra_links
         )
     self.inv          = inv
     self.type_name    = _T (obj.ui_name)
     self.ui_display   = pyk.decoded (obj.ui_repr)
     self.args         = (self.type_name, self.ui_display)
     description       = _T (inv.description)
     try :
         self.inv_desc = description % TFL.Caller.Object_Scope (obj)
     except TypeError :
         self.inv_desc = description
예제 #9
0
 def _setup_order_by_1 (self, E_Type, s) :
     s     = s.strip ()
     sign  = "-" if s.startswith ("-") else ""
     name  = s [bool (sign): ]
     if name == "pid" : ### XXX move into MOM.Attr.Querier
         keys = (s, )
         f    = dict (attr = None, name = s, sign = sign, ui_name = s)
     else :
         q     = getattr (E_Type.AQ, name)
         ET    = getattr (q._attr, "E_Type", None)
         if ET and ET.sorted_by is not None :
             keys = tuple ("%s%s.%s" % (sign, name, k) for k in ET.sorted_by)
         else :
             keys = (s, )
         ate   = q.As_Template_Elem
         f     = dict \
             ( ate._kw
             , attr     = q._attr
             , name     = s
             , sign     = sign
             , ui_name  = "%s%s" % (sign, ate.ui_name)
             )
     return TFL.Record (** f), keys
예제 #10
0
class DB_Man(TFL.Meta.Object):
    """Manager for data bases of MOM."""

    uncommitted_changes = TFL.Record(pending_attr_changes={})
    ilk = "PC"
    src = None

    db_meta_data = property(TFL.Getter.ems.db_meta_data)
    entity_type = property(TFL.Getter.app_type.entity_type)
    max_cid = property(TFL.Getter.ems.max_cid)
    max_pid = property(TFL.Getter.ems.max_pid)
    max_surrs = property(TFL.Getter.ems.max_surrs)
    readonly = property(TFL.Getter.ems.db_meta_data.readonly)
    reserve_surrogates = False

    ### DB_Man creation methods
    @classmethod
    def connect(cls, app_type, db_url):
        db_url = app_type.Url(db_url)
        self = cls.__new__(cls, app_type, db_url)
        self.ems = app_type.EMS.connect(self, db_url)
        return self

    # end def connect

    @classmethod
    def create(cls,
               app_type,
               db_url,
               from_db_man,
               chunk_size=10000,
               legacy_lifter=None):
        db_url = app_type.Url(db_url)
        self = cls.__new__(cls, app_type, db_url)
        self.src = from_db_man
        self.ems = app_type.EMS.new(self, db_url)
        self.chunk_size = chunk_size
        self._migrate(chunk_size, legacy_lifter)
        return self

    # end def create

    def __init__(self):
        raise TypeError \
            ( "Use {name}.connect or {name}.create to create "
                "new database managers".format (name = self.__class__.__name__)
            )

    # end def __init__

    def __new__(cls, app_type, db_url):
        self = cls.__c_super.__new__(cls)
        self.db_url = db_url
        self.app_type = app_type
        return self

    # end def __new__

    ### DB_Man instance methods

    def change_readonly(self, state):
        """Change `readonly` state of database to `state`."""
        self.ems.change_readonly(state)

    # end def change_readonly

    def destroy(self):
        self.ems.close()
        self.__dict__.clear()

    # end def destroy

    def _migrate(self, chunk_size, legacy_lifter):
        src = self.src
        e_iter = src.ems.pcm.produce_entities()
        c_iter = src.ems.pcm.produce_changes()
        if legacy_lifter:
            ll = MOM.Legacy_Lifter_Wrapper(self, legacy_lifter)
            e_iter = ll.entity_iter(e_iter)
            c_iter = ll.change_iter(c_iter)
        self.ems.pcm.consume(e_iter, c_iter, chunk_size, src.db_meta_data)

    # end def _migrate

    def __str__(self):
        return "%s <%s>" % (self.__class__.__name__, self.db_url)
예제 #11
0
def _main (cmd) :
    cmd_path   = list (cmd.path or [])
    replacer   = Re_Replacer (r"\.py[co]", ".py")
    a          = cmd.argv [0]
    et         = ""
    one_arg_p  = len (cmd.argv) == 1 and not sos.path.isdir (a)
    if one_arg_p and not cmd.Extra_Interpreters :
        f              = Filename (a)
        m              = f.base
        py_version     = " [py %s]" % \
            ".".join (str (v) for v in sys.version_info [:3])
        sys.path [0:0] = cmd_path
        mod_path       = f.directory if f.directory else "./"
        if sos.path.exists \
               (Filename ("__init__.py", default_dir = mod_path).name) :
            sys.path [0:0] = [sos.path.join (mod_path, "..")]
        sys.path [0:0] = [mod_path]
        flags = doctest.NORMALIZE_WHITESPACE
        if not cmd.nodiff :
            flags |= doctest.REPORT_NDIFF
        try :
            logging.disable (logging.WARNING)
            start  = _timer ()
            module = __import__ (m)
            module.expect_except = TFL.CAO.expect_except
            cases  = len (getattr (module, "__test__", ())) or 1
            f, t   = doctest.testmod \
                ( module
                , verbose     = cmd.verbose
                , optionflags = flags
                )
            exec_time = _timer () - start
        except KeyboardInterrupt :
            raise
        except Exception as exc :
            exec_time = _timer () - start
            if cmd.timing :
                et = " in %7.5fs" % (exec_time, )
            msg = format_x % (replacer (a), py_version, exc, et)
            print (msg, file = sys.stderr)
            raise
        else :
            format = format_f if f else format_s
            if cmd.timing :
                et = " in %7.5fs" % (exec_time, )
            print (replacer (format % TFL.Caller.Scope ()), file = sys.stderr)
    else :
        py_executables = [sys.executable] + list (cmd.Extra_Interpreters)
        py_version     = ""
        head_pieces    = sos.python_options () + \
            [ __file__
            , "-path %r" % (",".join (cmd_path), ) if cmd_path else ""
            ]
        for opt in ("nodiff", "timing", "verbose") :
            if getattr (cmd, opt) :
                head_pieces.append ("-" + opt)
        head = " ".join (hp for hp in head_pieces if hp)
        if cmd.summary :
            run_cmd = run_command_with_summary
        else :
            run_cmd = run_command
        if cmd.RExclude :
            x_pat   = Regexp (cmd.RExclude)
            exclude = x_pat.search
        elif cmd.exclude :
            exclude = lambda a : fnmatch.fnmatch (a, cmd.exclude)
        else :
            exclude = lambda a : False
        def run_mod (a) :
            if exclude (a) :
                summary.excluded.append (a)
                print ("%s excluded" % (a, ))
            else :
                summary.modules += 1
                for pyx in py_executables :
                    run_cmd ("%s %s %s" % (pyx, head, a))
        def run_mods (d) :
            for f in sorted (sos.listdir_exts (d, ".py")) :
                if has_doctest (f) :
                    run_mod (f)
        if cmd.transitive :
            from _TFL.subdirs import subdirs
            def run_dir (d) :
                run_mods (d)
                for s in subdirs (d) :
                    run_dir (s)
        else :
            run_dir = run_mods
        start = _timer ()
        for a in cmd.argv :
            if sos.path.isdir (a) :
                run_dir (a)
            else :
                if has_doctest (a) :
                    run_mod (a)
        if cmd.summary :
            format = format_f if summary.failed else format_s
            if cmd.timing :
                et = " in %7.5fs" % (_timer () - start, )
            print ("=" * 79, file = sys.stderr)
            print \
                ( format % TFL.Caller.Scope
                    ( f      = summary.failed
                    , module = TFL.Record (__file__ = " ".join (cmd.argv))
                    , t      = summary.total
                    , cases  = summary.cases
                    , et     = et
                    )
                , "[%s/%s modules fail]" %
                    (len (summary.failures), summary.modules)
                , file = sys.stderr
                )
            print \
                ( "    %s"
                % ("\n    ".join ("%-68s : %s" % f for f in summary.failures))
                , file = sys.stderr
                )
            if summary.excluded :
                print \
                    ("    %s excluded" % (", ".join (summary.excluded), )
                    , file = sys.stderr
                    )
예제 #12
0
 def _as_template_elem(self, seen_etypes):
     result = dict(self._as_template_elem_inv, ui_name=self._ui_name_T)
     return TFL.Record(**result)
예제 #13
0
from Media_Parameters import Media_Parameters

Media_Parameters = Media_Parameters()

src_dir = sos.path.dirname(__file__)
web_root_dir = "//ffm.funkfeuer.at"
web_src_root = sos.path.abspath(src_dir)

base_template_dir = sos.path.dirname(_JNJ.__file__)
template_dirs = [src_dir, base_template_dir]

web_links = \
    [ TFL.Record
        ( href        = "http://guifi.net/en/"
        , title       = "Spanish open wireless network"
        , short_title = "Guifi.net"
        )
    , TFL.Record
        ( href        = "http://wlan-si.net/"
        , title       = "Slovenian open wireless network"
        , short_title = "wlan-si"
        )
    ]


def root_kw_args(cmd, **kw):
    return dict \
        ( console_context   = dict
            ( FFM           = FFM
            , GTW           = GTW
예제 #14
0
 def change_info(self):
     return TFL.Record(etag=self.top.App_Type.db_version_hash)
예제 #15
0
 def _matches (self, accept) :
     for r in self.renderers :
         for mt in r.mime_types :
             p = accept [mt]
             if p :
                 yield TFL.Record (render = r, mime_type = mt, priority = p)
예제 #16
0
 def __init__ (cls, name, bases, dict) :
     cls.__m_super.__init__ (name, bases, dict)
     if not hasattr (cls, "_") :
         cls._ = TFL.Record ()