def _tag(value): if isinstance(value, CheckerSessionObject): return {" ch": dict((k, _tag(v)) for k, v in iteritems(value))} elif isinstance(value, MeansTest): return {" mt": dict((k, _tag(v)) for k, v in iteritems(value))} elif isinstance(value, tuple): return {" t": [_tag(x) for x in value]} elif isinstance(value, uuid.UUID): return {" u": value.hex} elif isinstance(value, bytes): return {" b": b64encode(value).decode("ascii")} elif callable(getattr(value, "__html__", None)): return {" m": text_type(value.__html__())} elif isinstance(value, list): return [_tag(x) for x in value] elif isinstance(value, datetime): return {" d": http_date(value)} elif isinstance(value, dict): return dict((k, _tag(v)) for k, v in iteritems(value)) elif isinstance(value, str): try: return text_type(value) except UnicodeError: raise UnexpectedUnicodeError( u"A byte string with " u"non-ASCII data was passed to the session system " u"which can only store unicode strings. Consider " u"base64 encoding your string (String was %r)" % value) return value
def get(cls, typ,subtyp=None, add=False): if subtyp is None: if isinstance(typ,MIMEtype): return typ if isinstance(typ,Object): return typ.mime typ = text_type(typ) try: typ,subtyp = typ.split('/') except ValueError: try: return cls.q.get(or_(cls.name==typ, cls.ext==typ)) except NoData: try: return MIMEext.q.get_by(ext=typ).mime except NoData: raise KeyError("Could not find MIME type "+typ) else: subtyp = text_type(subtyp) try: return cls.q.get_by(typ=typ,subtyp=subtyp) except NoData: if not add: raise KeyError("Could not find MIME type "+typ+'/'+subtyp) return cls.new(typ=typ,subtyp=subtyp, add=add)
def _tag(value): if isinstance(value, CheckerSessionObject): return {" ch": dict((k, _tag(v)) for k, v in iteritems(value))} elif isinstance(value, MeansTest): return {" mt": dict((k, _tag(v)) for k, v in iteritems(value))} elif isinstance(value, tuple): return {" t": [_tag(x) for x in value]} elif isinstance(value, uuid.UUID): return {" u": value.hex} elif isinstance(value, bytes): return {" b": b64encode(value).decode("ascii")} elif callable(getattr(value, "__html__", None)): return {" m": text_type(value.__html__())} elif isinstance(value, list): return [_tag(x) for x in value] elif isinstance(value, datetime): return {" d": http_date(value)} elif isinstance(value, dict): return dict((k, _tag(v)) for k, v in iteritems(value)) elif isinstance(value, str): try: return text_type(value) except UnicodeError: raise UnexpectedUnicodeError( u"A byte string with " u"non-ASCII data was passed to the session system " u"which can only store unicode strings. Consider " u"base64 encoding your string (String was %r)" % value ) return value
def get(cls, typ, subtyp=None, add=False): if subtyp is None: if isinstance(typ, MIMEtype): return typ if isinstance(typ, Object): return typ.mime typ = text_type(typ) try: typ, subtyp = typ.split('/') except ValueError: try: return cls.q.get(or_(cls.name == typ, cls.ext == typ)) except NoData: try: return MIMEext.q.get_by(ext=typ).mime except NoData: raise KeyError("Could not find MIME type " + typ) else: subtyp = text_type(subtyp) try: return cls.q.get_by(typ=typ, subtyp=subtyp) except NoData: if not add: raise KeyError("Could not find MIME type " + typ + '/' + subtyp) return cls.new(typ=typ, subtyp=subtyp, add=add)
def drop_blueprint(blueprint,site=None): if site is None: site = current_site if isinstance(blueprint,string_types): blueprint = Blueprint.q.get_by(name=text_type(blueprint)) bp = SiteBlueprint.q.get_by(site=site, name=text_type(name)) Delete.new(bp)
def drop_site(site=None): if site is None: site = current_site elif isinstance(site, string_types): try: site = Site.q.get_by(name=text_type(site), parent=current_site) except NoData: site = Site.q.get_by(domain=text_type(site)) Delete.new(site)
def drop_blueprint(blueprint, site=None): if site is None: site = current_site if isinstance(blueprint, string_types): blueprint = Blueprint.q.get_by(name=text_type(blueprint)) bp = SiteBlueprint.q.get_by(site=site, name=text_type(name)) Delete.new(bp)
def drop_site(site=None): if site is None: site = current_site elif isinstance(site,string_types): try: site = Site.q.get_by(name=text_type(site),parent=current_site) except NoData: site = Site.q.get_by(domain=text_type(site)) Delete.new(site)
def gen_vars(): from pybble.core import default_settings as DS for k,v in DS.__dict__.items(): if k != k.upper(): continue if k in app.config: # add overrides v = app.config[k] yield text_type(k),v,getattr(DS,'d_'+k,None)
def default(self, obj: Any) -> Any: if isinstance(obj, set): return list(obj) elif isinstance(obj, LazyString): return text_type(obj) else: return json.JSONEncoder.default(self, obj)
def __getitem__(self, k): if isinstance(k, ConfigVar): var = k else: k = text_type(k) if k in pybble_config and pybble_config._is_fixed(k): return pybble_config[k] try: var = ConfigVar.q.cache_key("VAR", k).get_by(name=k) except RuntimeError: # system not yet configured if k in pybble_config: return pybble_config[k] raise except NoData: raise KeyError(k) self = refresh(self) def gen(): try: val = SiteConfigVar.q.get_by(parent=self, var=var).value except NoData: if self.super is None: return var.value val = self.super[k] return val return cache.cached(gen, "SVAR", self.id, var.id)
def parse(self, stream, media_type, **options): data = stream.read().decode('utf-8') try: return json.loads(data) except ValueError as exc: msg = 'JSON parse error - %s' % text_type(exc) raise exceptions.ParseError(msg)
def default(self, o): """Implement this method in a subclass such that it returns a serializable object for ``o``, or calls the base implementation (to raise a :exc:`TypeError`). For example, to support arbitrary iterators, you could implement default like this:: def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, o) """ if isinstance(o, datetime): return http_date(o.utctimetuple()) if isinstance(o, date): return http_date(o.timetuple()) if isinstance(o, uuid.UUID): return str(o) if hasattr(o, '__html__'): return text_type(o.__html__()) return _json.JSONEncoder.default(self, o)
def run(self, commands=None, default_command=None): """ Prepares manager to receive command line input. Usually run inside "if __name__ == "__main__" block in a Python script. :param commands: optional dict of commands. Appended to any commands added using add_command(). :param default_command: name of default command to run if no arguments passed. """ if commands: self._commands.update(commands) # Make sure all of this is Unicode argv = list(text_type(arg) for arg in sys.argv) if default_command is not None and len(argv) == 1: argv.append(default_command) if 'runserver' in argv and len(argv) == 3 and argv[2][0] in ('0:'): # `runserver 0:9000` --> `runserver -h 0.0.0.0 -p 9000` host, port = argv[2].split(':') if not host or host == '0': host = '0.0.0.0' argv[2] = '-h' for i in (host, '-p', port): argv.append(i) try: result = self.handle(argv[0], argv[1:]) except SystemExit as e: result = e.code sys.exit(result or 0)
def process_module(mod, force=False): targets = ( ('MODEL',add_objtypes), ('MIME',add_mimes), ('TRANSLATOR',add_translators), ('APP',lambda x,force: _load(App,x,force)), ('BLUEPRINT',lambda x,force: _load(Blueprint,x,force)), ('VAR',add_vars), ('VERIFIER',lambda x,force: _load(VerifierBase,x,force)), ('FILE',add_statics), ('TEMPLATE',add_templates), ('STATIC',add_statics), ) for k,proc in targets: try: try: data = getattr(mod,k) except AttributeError: data = mod.get(k) except (KeyError,AttributeError): pass else: if data is None: continue if isinstance(data,string_types): data = (text_type(data),) proc(data, force=force)
def run(self, commands=None, default_command=None): """ Prepares manager to receive command line input. Usually run inside "if __name__ == "__main__" block in a Python script. :param commands: optional dict of commands. Appended to any commands added using add_command(). :param default_command: name of default command to run if no arguments passed. """ if commands: self._commands.update(commands) # Make sure all of this is Unicode argv = list(text_type(arg) for arg in sys.argv) if default_command is not None and len(argv) == 1: argv.append(default_command) try: result = self.handle(argv[0], argv[1:]) except SystemExit as e: result = e.code sys.exit(result or 0)
def process_module(mod, force=False): targets = ( ('MODEL', add_objtypes), ('MIME', add_mimes), ('TRANSLATOR', add_translators), ('APP', lambda x, force: _load(App, x, force)), ('BLUEPRINT', lambda x, force: _load(Blueprint, x, force)), ('VAR', add_vars), ('VERIFIER', lambda x, force: _load(VerifierBase, x, force)), ('FILE', add_statics), ('TEMPLATE', add_templates), ('STATIC', add_statics), ) for k, proc in targets: try: try: data = getattr(mod, k) except AttributeError: data = mod.get(k) except (KeyError, AttributeError): pass else: if data is None: continue if isinstance(data, string_types): data = (text_type(data), ) proc(data, force=force)
def __setitem__(self, k, v): if isinstance(k, ConfigVar): var = k else: k = text_type(k) if k in pybble_config: pybble_config[k] = v if pybble_config._is_fixed(k): return try: var = ConfigVar.q.cache_key("VAR", k).get_by(name=k) except RuntimeError: if k in pybble_config: return raise self = refresh(self) try: ov = SiteConfigVar.q.get_by(parent=self, var=var) except NoData: SiteConfigVar.new(self, var, v) else: ov.value = v db.session.flush() cache.delete("SVAR", '*', var.id)
def code_exists(form, field): try: v = Verifier.q.get_by(code=text_type(field.data)) except NoData: raise ValidationError(u"Diesen Code kenne ich nicht.") else: if v.expired: raise ValidationError(u"Dieser Code ist zu alt.")
def code_exists(form, field): try: v = Verifier.q.get_by(code=text_type(field.data)) except NoData: raise ValidationError("Diesen Code kenne ich nicht.") else: if v.expired: raise ValidationError("Dieser Code ist zu alt.")
def add_translator(obj, name, doc=NotGiven, force=False): ## Templating and whatnot def get_types(types, add=False): if isinstance(types, string_types): types = (types, ) for s in types: mt = MIMEtype.get(s, add=add) if mt.subtyp == "*": yield mt, 10 for r in MIMEtype.q.filter_by(typ=mt.typ): if r.subtyp == '*' or r.subtyp.startswith('_'): continue yield mt, 50 else: yield mt, 0 name = text_type(name) mpath = obj.__module__ + '.' + obj.__name__ try: E = obj.SOURCE src = list(get_types(obj.SOURCE, add=True)) E = obj.DEST dst = list(get_types(obj.DEST, add=True)) E = obj.CONTENT mt = MIMEtype.get(obj.CONTENT, add=True) E = "??" w = obj.WEIGHT except NoData as e: logger.warn("{} is not usable ({}): {}\n{}".format( obj, E, str(e), format_exc())) return try: trans = MIMEtranslator.q.get_by(path=mpath) except NoData: trans = MIMEtranslator.new(path=mpath, mime=mt, weight=w, name=mpath) else: _upd(trans, (("mime", mt), ("weight", w)), force=force) for s, sw in src: for d, dw in dst: w = sw + dw try: obj = MIMEadapter.q.get_by(from_mime=s, to_mime=d, translator=trans) except NoData: obj = MIMEadapter.new(from_mime=s, to_mime=d, translator=trans, weight=w) else: _upd(obj, (("weight", w), ), force=force) db.session.flush()
def parse(self, stream, media_type, **options): import xmltodict data = stream.read().decode('utf-8') try: return xmltodict.parse(data) except ValueError as exc: msg = 'XML parse error - %s' % text_type(exc) raise exceptions.ParseError(msg)
def serialize_string(self, value): try: return text_type(value) except UnicodeError: raise UnexpectedUnicodeError( u"A byte string with " u"non-ASCII data was passed to the session system " u"which can only store unicode strings. Consider " u"base64 encoding your string (String was %r)" % value)
def get(cls, typ, obj=None): """\ Resolve 'something' to an object type, or (of the second parameter is an integer) to an object. """ if typ is None and obj is None: return None if typ is not None and obj is not None: if isinstance(obj, (int, long)): return cls.get(typ).get_obj(obj) typ = cls.get(typ) assert obj.type is typ, str((obj.type, typ)) return typ if hasattr(typ, '_get_current_object'): # Flask localproxy typ = typ._get_current_object() if isinstance(typ, ObjType): return typ if isinstance(typ, Object): typ = typ.__class__ if isinstance(typ, type) and issubclass(typ, Object): path = typ.__module__ + '.' + typ.__name__ res = _type_path.get(path) if res is not None: return refresh(res) try: return cls.q.get_by(path=path) except NoData: from .types import MIMEtype res = cls.new(path=path, name=path) _add_cache(res) MIMEtype.get("pybble", typ.__name__.lower(), add=res) return res if isinstance(typ, string_types): try: typ = int(typ) except ValueError: pass if isinstance(typ, cls): return typ if isinstance(typ, string_types): res = _type_name.get(typ, None) if res is not None: return refresh(res) res = cls.q.get_by(name=text_type(typ)) elif isinstance(typ, (int, long)): res = _type_id.get(typ, None) if res is not None: return refresh(res) res = cls.q.get_by(id=typ) else: raise RuntimeError("No known way to get an object type for " + str(typ)) _add_cache(res) return res
def default(self, o): # pylint: disable=method-hidden if isinstance(o, date): # TODO (testeddoughnut): proper timezone support o = o.replace(tzinfo=tzutc()) return o.isoformat() if isinstance(o, uuid.UUID): return str(o) if hasattr(o, '__html__'): return text_type(o.__html__()) return _json.JSONEncoder.default(self, o)
def test_serializer_with_markup(self): class TestMarkup: def __html__(self): return "<h1>Test</h1>" value = TestMarkup() outputJSON = self.serializer.dumps(value) expectedDict = {" m": text_type("<h1>Test</h1>")} expectedJSON = self.format_json(expectedDict) self.assert_json(outputJSON) self.assertEqual(outputJSON, expectedJSON)
def default(self, o): if hasattr(o, '__json__') and callable(o.__json__): return o.__json__() if isinstance(o, (date, datetime, time)): return o.isoformat()[:19].replace('T', ' ') elif isinstance(o, (int, long)): return int(o) elif isinstance(o, decimal.Decimal): return str(o) elif hasattr(o, '__html__'): return text_type(o.__html__()) return _JSONEncoder.default(self, o)
def get(cls, typ, obj=None): """\ Resolve 'something' to an object type, or (of the second parameter is an integer) to an object. """ if typ is None and obj is None: return None if typ is not None and obj is not None: if isinstance(obj,(int,long)): return cls.get(typ).get_obj(obj) typ = cls.get(typ) assert obj.type is typ, str((obj.type,typ)) return typ if hasattr(typ,'_get_current_object'): # Flask localproxy typ = typ._get_current_object() if isinstance(typ, ObjType): return typ if isinstance(typ, Object): typ = typ.__class__ if isinstance(typ,type) and issubclass(typ, Object): path = typ.__module__+'.'+typ.__name__ res = _type_path.get(path) if res is not None: return refresh(res) try: return cls.q.get_by(path=path) except NoData: from .types import MIMEtype res = cls.new(path=path,name=path) _add_cache(res) MIMEtype.get("pybble",typ.__name__.lower(),add=res) return res if isinstance(typ, string_types): try: typ = int(typ) except ValueError: pass if isinstance(typ, cls): return typ if isinstance(typ, string_types): res = _type_name.get(typ,None) if res is not None: return refresh(res) res = cls.q.get_by(name=text_type(typ)) elif isinstance(typ, (int,long)): res = _type_id.get(typ,None) if res is not None: return refresh(res) res = cls.q.get_by(id=typ) else: raise RuntimeError("No known way to get an object type for "+str(typ)) _add_cache(res) return res
def pr(v): if isinstance(v, time.struct_time): v = time.strftime("%Y-%m-%d %H:%M:%S", v) elif isinstance(v, dt.datetime): v = format_dt(v) elif isinstance(v, string_types): v = urepr(v) if v[0] == 'u': v = v[1:] else: v = text_type(v) return v
def pr(v): if isinstance(v,time.struct_time): v = time.strftime("%Y-%m-%d %H:%M:%S",v) elif isinstance(v,dt.datetime): v = format_dt(v) elif isinstance(v,string_types): v = urepr(v) if v[0] == 'u': v = v[1:] else: v = text_type(v) return v
def setup(self,domain, name=None, parent=None,app=None, superuser=None, inherit=True): if name is None: name=u"Here be "+domain self.domain=unicode(domain) if isinstance(app,string_types): app = App.q.get_by(name=text_type(app)) self.name=name self.parent=parent self.app=app self._superuser = superuser self.inherit_parent = inherit super(Site,self).setup()
def __delitem__(self, k): k = text_type(k) assert k not in pybble_config, k var = ConfigVar.q.cache_key("VAR", k).get_by(name=k) try: ov = SiteConfigVar.q.get_by(parent=self, var=var) except NoData: pass else: db.session.delete(ov) cache.delete("SVAR", '*', var.id) db.session.flush()
def add_translator(obj,name,doc=NotGiven, force=False): ## Templating and whatnot def get_types(types, add=False): if isinstance(types,string_types): types = (types,) for s in types: mt = MIMEtype.get(s, add=add) if mt.subtyp == "*": yield mt,10 for r in MIMEtype.q.filter_by(typ=mt.typ): if r.subtyp == '*' or r.subtyp.startswith('_'): continue yield mt,50 else: yield mt,0 name = text_type(name) mpath = obj.__module__+'.'+obj.__name__ try: E=obj.SOURCE src = list(get_types(obj.SOURCE, add=True)) E=obj.DEST dst = list(get_types(obj.DEST, add=True)) E=obj.CONTENT mt = MIMEtype.get(obj.CONTENT, add=True) E="??" w = obj.WEIGHT except NoData as e: logger.warn("{} is not usable ({}): {}\n{}".format(obj,E,str(e), format_exc())) return try: trans = MIMEtranslator.q.get_by(path=mpath) except NoData: trans = MIMEtranslator.new(path=mpath,mime=mt,weight=w,name=mpath) else: _upd(trans,(("mime",mt),("weight",w)),force=force) for s,sw in src: for d,dw in dst: w=sw+dw try: obj = MIMEadapter.q.get_by(from_mime=s,to_mime=d,translator=trans) except NoData: obj = MIMEadapter.new(from_mime=s,to_mime=d,translator=trans,weight=w) else: _upd(obj,(("weight",w),),force=force) db.session.flush()
def default(self, o): # default是会被循环调用的,如果一个对象的变量里还是一个对象,依旧会再次调用default方法 if hasattr(o,'keys') and hasattr(o,'__getitem__'): return dict(o) # 特殊处理某些特殊的对象转换 if isinstance(o, datetime): return http_date(o.utctimetuple()) if isinstance(o, date): return http_date(o.timetuple()) if isinstance(o, uuid.UUID): return str(o) if hasattr(o, '__html__'): return text_type(o.__html__()) raise ServerError()
def setup(self, site,blueprint, endpoint=None, name=None,path=None): if isinstance(blueprint,string_types): blueprint = Blueprint.q.get_by(name=text_type(blueprint)) if site is None: from ...globals import current_site self.site = current_site else: if isinstance(site,string_types): try: site = Site.q.get_by(name=text_type(site)) except NoData: site = Site.q.get_by(domain=text_type(site)) self.site = site if name is None: name = blueprint.name if endpoint is None: endpoint = name self.blueprint = blueprint self.name = name self.path = path self.endpoint = endpoint super(SiteBlueprint,self).setup()
def __init__(self, app): with app.app_context(): root = app.site if root is None: root = Site.q.get_by(parent=None) elif isinstance(root,string_types): root = Site.q.get_by(name=text_type(root)) self.app = app self.root = root self.lock = Lock() self.instances = {} all_apps.connect(self._reload) app_list.connect(self._reload) with app.app_context(): self._reload(sender=self)
def setup(self, site, blueprint, endpoint=None, name=None, path=None): if isinstance(blueprint, string_types): blueprint = Blueprint.q.get_by(name=text_type(blueprint)) if site is None: from ...globals import current_site self.site = current_site else: if isinstance(site, string_types): try: site = Site.q.get_by(name=text_type(site)) except NoData: site = Site.q.get_by(domain=text_type(site)) self.site = site if name is None: name = blueprint.name if endpoint is None: endpoint = name self.blueprint = blueprint self.name = name self.path = path self.endpoint = endpoint super(SiteBlueprint, self).setup()
def confirm(code=None): if code is None: code = request.values.get("code", None) if code is None: form = ConfirmForm(request.values, prefix="confirm") if request.method != "POST" or not form.validate(): return render_template("confirm.html", form=form, title_trace=["Bestätigung"]) code = form.code.data.lower() v = Verifier.q.get_by(code=text_type(code)) if v.expired: flash("Die Anfrage ist schon zu alt. Bitte schicke sie nochmal ab!") return v.retry() return v.entered()
def add_templates(data, parent=None, force=False): if parent is None: # default to the system root parent = root_site for d in data: if isinstance(d,(tuple,list)): filepath = d[0] webpath = d[1] inferred = d[2] if len(d) > 2 else "" else: assert isinstance(d,string_types) filepath = text_type(d) webpath = inferred = "" filepath = os.path.relpath(modpath(parent,filepath)) find_templates(parent, filepath,webpath, inferred=inferred, force=force)
def get_mod(cls, typ): "Optimization" if isinstance(typ, string_types): res = _typemod_name.get(typ,None) if res is not None: return res res = cls.q.get_by(name=text_type(typ)) elif isinstance(typ, (int,long)): res = _typemod_id.get(typ,None) if res is not None: return res res = cls.q.get_by(id=typ) else: raise RuntimeError("No known way to get an object type for "+str(typ)) _add_cache(res) return res.mod
def confirm(code=None): if code is None: code = request.values.get('code', None) if code is None: form = ConfirmForm(request.values, prefix='confirm') if request.method != 'POST' or not form.validate(): return render_template('confirm.html', form=form, title_trace=[u"Bestätigung"]) code = form.code.data.lower() v = Verifier.q.get_by(code=text_type(code)) if v.expired: flash(u"Die Anfrage ist schon zu alt. Bitte schicke sie nochmal ab!") return v.retry() return v.entered()
def parse(self, stream, media_type, **options): multipart_parser = WerkzeugMultiPartParser(default_stream_factory) boundary = media_type.params.get('boundary') if boundary is None: msg = 'Multipart message missing boundary in Content-Type header' raise exceptions.ParseError(msg) boundary = boundary.encode('ascii') content_length = options.get('content_length') assert content_length is not None, 'MultiPartParser.parse() requires `content_length` argument' try: return multipart_parser.parse(stream, boundary, content_length) except ValueError as exc: msg = 'Multipart parse error - %s' % text_type(exc) raise exceptions.ParseError(msg)
def get_mod(cls, typ): "Optimization" if isinstance(typ, string_types): res = _typemod_name.get(typ, None) if res is not None: return res res = cls.q.get_by(name=text_type(typ)) elif isinstance(typ, (int, long)): res = _typemod_id.get(typ, None) if res is not None: return res res = cls.q.get_by(id=typ) else: raise RuntimeError("No known way to get an object type for " + str(typ)) _add_cache(res) return res.mod
def get_source(self, environment, template): """\ Find a template. * attached to "self" * if this is a site: * if the template name contains a slash, * attached to the SiteBlueprint * attached to the Blueprint * attached to the app * recurse to my parent """ if isinstance(template, TemplateMatch): template = template.template if isinstance(template, DBTemplate): mtime = template.modified def t_is_current(): #db.refresh(refresh(t),('modified',)) return mtime == refresh(template).modified return template c = ContentData(site=refresh(self.site), name=text_type(template), from_mime=None, to_mime=None) if current_app.debug: trace = [] def tracer(*t): trace.append(t) t = get_template(c, tracer)[0] #g.context.setdefault('LOADER_TRACE',[]).append((c,trace)) else: t = get_template(c)[0] mtime = t.modified def t_is_current(): #db.refresh(refresh(t),('modified',)) return mtime == refresh(t).modified return t.content, t.oid, t_is_current
def explore_archive(fd, filename=None, uncompress=False): """ Given an uploaded file descriptor, return it or a list of archive content. Yield tuple(filepath, file-like object), where filepath is a list whose components are directories and last one is filename. """ if filename is None: filename = fd.filename if not isinstance(filename, text_type): filename = text_type(fd.filename, errors='ignore') if not uncompress: yield [], fd raise StopIteration if is_zipfile(fd): with ZipFile(fd, 'r') as archive: for zipinfo in archive.infolist(): filename = zipinfo.filename if isinstance(filename, bytes): # not unicode: try to convert from utf-8 (OSX case: unicode flag not # set), then legacy cp437 # http://stackoverflow.com/questions/13261347/correctly-decoding-zip-entry-file-names-cp437-utf-8-or try: filename = filename.decode('utf-8') except UnicodeDecodeError: filename = filename.decode('cp437') if any( pattern.match(filename) is not None for pattern in ARCHIVE_IGNORE_FILES): continue filepath = filename.split('/') filename = filepath.pop() zip_fd = archive.open(zipinfo, 'r') setattr(zip_fd, 'filename', filename) setattr(zip_fd, 'content_type', None) yield filepath, zip_fd else: yield [], fd
def create_blueprint(site, blueprint, path, name=None,endpoint=None): """\ Attach a blueprint to a site. :param site: The site to attach to. :param blueprint: The name of the blueprint in the `pybble.blueprint` directory. :param path: The web path to attach the blueprint to. :param name: A human-readable name for this attachment. """ if isinstance(blueprint,string_types): blueprint = Blueprint.q.get_by(name=text_type(blueprint)) if name is None: name = getattr(blueprint.mod,"_name",blueprint.name) bp = SiteBlueprint.new(site=site, path=path, blueprint=blueprint, name=name,endpoint=endpoint) db.session.flush() return bp
def setup(self, domain, name=None, parent=None, app=None, superuser=None, inherit=True): if name is None: name = u"Here be " + domain self.domain = unicode(domain) if isinstance(app, string_types): app = App.q.get_by(name=text_type(app)) self.name = name self.parent = parent self.app = app self._superuser = superuser self.inherit_parent = inherit super(Site, self).setup()
def render_template(template, _root=None, **context): """\ Renders a named template with the given context. :param template: the name of the template to be rendered, or an iterable with template names the first one existing will be rendered :param context: the variables that will be available in the context of the template. """ if isinstance(template,string_types): c = ContentData(name=text_type(template), anchor=_root) return c.render(_vars=context) for tn in template: try: return render_template(tn,**context) except TemplateNotFound: pass raise TemplateNotFound(template)
def run(self, help=False,name=None): if help: self.parser.print_help() sys.exit(not help) if name is None: print("Available apps:") for app in App.q.all(): print(app.name,app.path, sep="\t") return app = App.q.get_by(name=text_type(name)) if name is None: name = app.name if app.doc: print(app.doc) else: print("This app does not have individual configuration.") has_params = False for var in app.all_children("ConfigVar"): if not has_params: print("Name","Default","Usage", sep="\t") has_params = True print(var.name,var.value,var.doc, sep="\t") if not has_params: print("This app cannot be configured individually.")
def get_source(self, environment, template): """\ Find a template. * attached to "self" * if this is a site: * if the template name contains a slash, * attached to the SiteBlueprint * attached to the Blueprint * attached to the app * recurse to my parent """ if isinstance(template,TemplateMatch): template = template.template if isinstance(template,DBTemplate): mtime = template.modified def t_is_current(): #db.refresh(refresh(t),('modified',)) return mtime == refresh(template).modified return template c = ContentData(site=refresh(self.site), name=text_type(template), from_mime=None,to_mime=None) if current_app.debug: trace = [] def tracer(*t): trace.append(t) t = get_template(c, tracer)[0] #g.context.setdefault('LOADER_TRACE',[]).append((c,trace)) else: t = get_template(c)[0] mtime = t.modified def t_is_current(): #db.refresh(refresh(t),('modified',)) return mtime == refresh(t).modified return t.content, t.oid, t_is_current
def run(self, help=False,name=None): if help: self.parser.print_help() sys.exit(not help) if name is None: print("Available blueprints:") for bp in Blueprint.q.all(): print(bp.name,bp.path, sep="\t") return bp = Blueprint.q.get_by(name=text_type(name)) if name is None: name = bp.name if bp.doc: print(bp.doc) else: print("This blueprint is undocumented.") has_params = False for var in bp.all_children("ConfigVar"): if not has_params: print("Name","Default","Usage", sep="\t") has_params = True print(var.name,var.value,var.doc, sep="\t") if not has_params: print("This blueprint cannot be configured individually.")
def create_app(app=None, config=None, site=ROOT_SITE_NAME, testing=False): """\ Setup an app instance. Configuration is loaded from * local_settings * PYBBLE_SETTINGS * the database :param site: The site name. The default is '_root'; there may be more than one one root site :param config: A configuration file to load. Default: the PYBBLE environment variable. :param testing: Required to be identical to config.TESTING. """ if config: os.environ['PYBBLE'] = config make_cfg_app() if testing is not None: assert testing == cfg_app.config.get('TESTING',False), (testing,cfg_app.config.get('TESTING',False)) else: testing = cfg_app.config.get('TESTING',False) assert testing is not None with cfg_app.test_request_context('/'): if site is None: pass elif not isinstance(site,Site): if site == ROOT_SITE_NAME: try: site = Site.q.cached("SITE",ROOT_SITE_NAME,0).get(Site.parent==None) except NoData: raise RuntimeError("I cannot find your root site!") except ManyData: raise RuntimeError("You seem to have more than one root. Fix that (with mgr -S): "+"".join(x for x in Site.q.filter(Site.parent==None))) else: try: try: site = Site.q.get_by(domain=text_type(site)) except NoData: site = Site.q.get_by(name=text_type(site)) except NoData: raise RuntimeError("The site ‘%s’ does not exist."%(site,)) except ManyData: raise RuntimeError("The site name ‘%s’ is not unique: %s"%(site," ".join(x.domain for x in Site.q.filter_by(name=text_type(site))))) if site is not None: site = refresh(site) if site is None or site.app is None: app = cfg_app else: app = site.app.mod(site, testing=testing) if app is not cfg_app: init_db(app) @app.url_value_preprocessor def bp_url_value_preprocessor(endpoint, values): if values: request.bp = refresh(values.pop('bp',None)) with app.app_context(): logging.disable(logging.NOTSET if app.debug is not None else logging.DEBUG) if app.config.URLFOR_ERROR_FATAL is None: app.config.URLFOR_ERROR_FATAL = app.debug if not app.config.URLFOR_ERROR_FATAL: def build_err(error, endpoint, values): #return Markup('<a href="#" class="build_error" title="%s (%s)">Bad link</a>') % (endpoint,repr(values)) return Markup('bad_Link/')+endpoint+"?"+urlencode(values) app.url_build_error_handlers.append(build_err) return app
def test(): return text_type(flask.session.permanent)