当前位置: 首页>>代码示例>>Python>>正文


Python BuiltinTemplateLoader.init方法代码示例

本文整理汇总了Python中sphinx.jinja2glue.BuiltinTemplateLoader.init方法的典型用法代码示例。如果您正苦于以下问题:Python BuiltinTemplateLoader.init方法的具体用法?Python BuiltinTemplateLoader.init怎么用?Python BuiltinTemplateLoader.init使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在sphinx.jinja2glue.BuiltinTemplateLoader的用法示例。


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

示例1: get_template_env

# 需要导入模块: from sphinx.jinja2glue import BuiltinTemplateLoader [as 别名]
# 或者: from sphinx.jinja2glue.BuiltinTemplateLoader import init [as 别名]
 def get_template_env(self):
     '''Create jinja template environment'''
     env = self.state.document.settings.env
     current_dir = os.path.dirname(__file__)
     template_dirs = [os.path.join(current_dir, 'flaskSphinx_templates'), current_dir]
     template_loader = BuiltinTemplateLoader()
     template_loader.init(env.app.builder, dirs=template_dirs)
     return SandboxedEnvironment(loader=template_loader)
开发者ID:delfick,项目名称:flaskSphinx,代码行数:10,代码来源:routes.py

示例2: MakoBridge

# 需要导入模块: from sphinx.jinja2glue import BuiltinTemplateLoader [as 别名]
# 或者: from sphinx.jinja2glue.BuiltinTemplateLoader import init [as 别名]
class MakoBridge(TemplateBridge):
    def init(self, builder, *args, **kw):
        self.jinja2_fallback = BuiltinTemplateLoader()
        self.jinja2_fallback.init(builder, *args, **kw)

        builder.config.html_context['site_base'] = builder.config['site_base']

        self.lookup = TemplateLookup(
            directories=builder.config.templates_path,
            imports=[
                "from builder import util"
            ],
            #format_exceptions=True,
        )

    def render(self, template, context):
        template = template.replace(".html", ".mako")
        context['prevtopic'] = context.pop('prev', None)
        context['nexttopic'] = context.pop('next', None)

        # RTD layout
        if rtd:
            # add variables if not present, such
            # as if local test of READTHEDOCS variable
            if 'MEDIA_URL' not in context:
                context['MEDIA_URL'] = "http://media.readthedocs.org/"
            if 'slug' not in context:
                context['slug'] = "mako-test-slug"
            if 'url' not in context:
                context['url'] = "/some/test/url"
            if 'current_version' not in context:
                context['current_version'] = "some_version"
            if 'versions' not in context:
                context['versions'] = [('default', '/default/')]

            context['docs_base'] = "http://readthedocs.org"
            context['toolbar'] = True
            context['layout'] = "rtd_layout.mako"
            context['pdf_url'] = "%spdf/%s/%s/%s.pdf" % (
                    context['MEDIA_URL'],
                    context['slug'],
                    context['current_version'],
                    context['slug']
            )
        # local docs layout
        else:
            context['toolbar'] = False
            context['docs_base'] = "/"
            context['layout'] = "layout.mako"

        context.setdefault('_', lambda x:x)
        return self.lookup.get_template(template).render_unicode(**context)

    def render_string(self, template, context):
        # this is used for  .js, .css etc. and we don't have
        # local copies of that stuff here so use the jinja render.
        return self.jinja2_fallback.render_string(template, context)
开发者ID:Distrotech,项目名称:mako,代码行数:59,代码来源:builders.py

示例3: __init__

# 需要导入模块: from sphinx.jinja2glue import BuiltinTemplateLoader [as 别名]
# 或者: from sphinx.jinja2glue.BuiltinTemplateLoader import init [as 别名]
 def __init__(self, app):
     template_loader = BuiltinTemplateLoader()
     template_loader.init(app.builder)
     template_env = SandboxedEnvironment(loader=template_loader)
     template_env.filters['escape'] = escape_filter
     template_env.filters['underline'] = underline_filter
     template_env.filters['as_extlink'] = as_extlink_filter
     self.env = template_env
     self.templates = {}
开发者ID:gogetdata,项目名称:ggd-recipes,代码行数:11,代码来源:generate_docs.py

示例4: __init__

# 需要导入模块: from sphinx.jinja2glue import BuiltinTemplateLoader [as 别名]
# 或者: from sphinx.jinja2glue.BuiltinTemplateLoader import init [as 别名]
 def __init__(self, app, extra_context):
     template_loader = BuiltinTemplateLoader()
     template_loader.init(app.builder)
     template_env = SandboxedEnvironment(loader=template_loader)
     template_env.filters['rst_escape'] = rst_escape_filter
     template_env.filters['underline'] = underline_filter
     template_env.filters['as_extlink'] = as_extlink_filter
     template_env.filters['prefixes'] = prefixes_filter
     template_env.filters['rst_link'] = rst_link_filter
     self.env = template_env
     self.templates: Dict[str, Any] = {}
     self.extra_context = extra_context
开发者ID:bioconda,项目名称:bioconda-utils,代码行数:14,代码来源:sphinxext.py

示例5: MakoBridge

# 需要导入模块: from sphinx.jinja2glue import BuiltinTemplateLoader [as 别名]
# 或者: from sphinx.jinja2glue.BuiltinTemplateLoader import init [as 别名]
class MakoBridge(TemplateBridge):
    def init(self, builder, *args, **kw):
        self.jinja2_fallback = BuiltinTemplateLoader()
        self.jinja2_fallback.init(builder, *args, **kw)

        builder.config.html_context['release_date'] = builder.config['release_date']
        builder.config.html_context['site_base'] = builder.config['site_base']

        self.lookup = TemplateLookup(directories=builder.config.templates_path,
            #format_exceptions=True,
            imports=[
                "from builder import util"
            ]
        )

        if rtd:
            # RTD layout, imported from sqlalchemy.org
            import urllib2
            template = urllib2.urlopen(builder.config['site_base'] + "/docs_adapter.mako").read()
            self.lookup.put_string("docs_adapter.mako", template)

            setup_ctx = urllib2.urlopen(builder.config['site_base'] + "/docs_adapter.py").read()
            lcls = {}
            exec(setup_ctx, lcls)
            self.setup_ctx = lcls['setup_context']

    def setup_ctx(self, context):
        pass

    def render(self, template, context):
        template = template.replace(".html", ".mako")
        context['prevtopic'] = context.pop('prev', None)
        context['nexttopic'] = context.pop('next', None)

        # local docs layout
        context['rtd'] = False
        context['toolbar'] = False
        context['base'] = "static_base.mako"

        # override context attributes
        self.setup_ctx(context)

        context.setdefault('_', lambda x: x)
        return self.lookup.get_template(template).render_unicode(**context)

    def render_string(self, template, context):
        # this is used for  .js, .css etc. and we don't have
        # local copies of that stuff here so use the jinja render.
        return self.jinja2_fallback.render_string(template, context)
开发者ID:23andMe,项目名称:sqlalchemy,代码行数:51,代码来源:mako.py

示例6: get_template_env

# 需要导入模块: from sphinx.jinja2glue import BuiltinTemplateLoader [as 别名]
# 或者: from sphinx.jinja2glue.BuiltinTemplateLoader import init [as 别名]
def get_template_env(app):
    """
    Get the template environment.

    .. note::

       Template should be loaded as a package_data using
       :py:function:`pkgutil.get_data`, but because we want the user to
       override the default template we need to hook it to the Sphinx loader,
       and thus a file system approach is required as it is implemented like
       that.
    """
    template_dir = [join(dirname(abspath(__file__)), 'templates')]
    template_loader = BuiltinTemplateLoader()
    template_loader.init(app.builder, dirs=template_dir)
    template_env = SandboxedEnvironment(loader=template_loader)
    template_env.filters['summary'] = filter_summary
    return template_env
开发者ID:VLSI-EDA,项目名称:PoC,代码行数:20,代码来源:sphinx.py

示例7: generate_autosummary_docs

# 需要导入模块: from sphinx.jinja2glue import BuiltinTemplateLoader [as 别名]
# 或者: from sphinx.jinja2glue.BuiltinTemplateLoader import init [as 别名]
def generate_autosummary_docs(sources, output_dir=None, suffix='.rst',
                              base_path=None, builder=None, template_dir=None):

    showed_sources = list(sorted(sources))
    if len(showed_sources) > 20:
        showed_sources = showed_sources[:10] + ['...'] + showed_sources[-10:]
    print('[autosummary] generating autosummary for: %s' %
          ', '.join(showed_sources))

    if output_dir:
        print('[autosummary] writing to %s' % output_dir)

    if base_path is not None:
        sources = [os.path.join(base_path, filename) for filename in sources]

    # create our own templating environment
    template_dirs = [os.path.join(os.path.dirname(__file__), 'templates')]

    if builder is not None:
        # allow the user to override the templates
        template_loader = BuiltinTemplateLoader()
        template_loader.init(builder, dirs=template_dirs)
    else:
        if template_dir:
            template_dirs.insert(0, template_dir)
        template_loader = FileSystemLoader(template_dirs)
    template_env = SandboxedEnvironment(loader=template_loader)

    # read
    items = find_autosummary_in_files(sources)

    # keep track of new files
    new_files = []

    for name, path, template_name in sorted(set(items), key=str):
        if path is None:
            # The corresponding autosummary:: directive did not have
            # a :toctree: option
            continue

        path = output_dir or os.path.abspath(path)
        ensuredir(path)

        try:
            name, obj, parent, mod_name = import_by_name(name)
        except ImportError as e:
            print('WARNING [autosummary] failed to import %r: %s' % (name, e), file=sys.stderr)
            continue

        fn = os.path.join(path, name + suffix).replace('::', '.')

        # skip it if it exists
        if os.path.isfile(fn):
            continue

        new_files.append(fn)

        if template_name is None:
            if obj.tag == 'compounddef' and obj.get('kind') == 'class':
                template_name = 'doxyclass.rst'
            else:
                raise NotImplementedError('No template for %s' % obj)

        with open(fn, 'w') as f:
            template = template_env.get_template(template_name)
            ns = {}
            if obj.tag == 'compounddef' and obj.get('kind') == 'class':
                ns['methods'] = [e.text for e in obj.findall('.//sectiondef[@kind="public-func"]/memberdef[@kind="function"]/name')]
                ns['enums'] = [e.text for e in obj.findall('.//sectiondef[@kind="public-type"]/memberdef[@kind="enum"]/name')]
                ns['objtype'] = 'class'
            else:
                raise NotImplementedError(obj)

            parts = name.split('::')
            mod_name, obj_name = '::'.join(parts[:-1]), parts[-1]

            ns['fullname'] = name
            ns['module'] = mod_name
            ns['objname'] = obj_name
            ns['name'] = parts[-1]
            ns['underline'] = len(name) * '='

            rendered = template.render(**ns)
            f.write(rendered)

    # descend recursively to new files
    if new_files:
        generate_autosummary_docs(new_files, output_dir=output_dir,
                                  suffix=suffix, base_path=base_path, builder=builder,
                                  template_dir=template_dir)
开发者ID:rmcgibbo,项目名称:sphinxcontrib-autodoc_doxygen,代码行数:92,代码来源:generate.py

示例8: generate_autosummary_docs

# 需要导入模块: from sphinx.jinja2glue import BuiltinTemplateLoader [as 别名]
# 或者: from sphinx.jinja2glue.BuiltinTemplateLoader import init [as 别名]
def generate_autosummary_docs(sources, output_dir=None, suffix='.rst',
                              warn=_simple_warn, info=_simple_info,
                              base_path=None, builder=None, template_dir=None):

    showed_sources = list(sorted(sources))
    if len(showed_sources) > 20:
        showed_sources = showed_sources[:10] + ['...'] + showed_sources[-10:]
    info('[autosummary] generating autosummary for: %s' %
         ', '.join(showed_sources))

    if output_dir:
        info('[autosummary] writing to %s' % output_dir)

    if base_path is not None:
        sources = [os.path.join(base_path, filename) for filename in sources]

    # create our own templating environment
    template_dirs = [os.path.join(package_dir, 'ext',
                                  'autosummary', 'templates')]
    if builder is not None:
        # allow the user to override the templates
        template_loader = BuiltinTemplateLoader()
        template_loader.init(builder, dirs=template_dirs)
    else:
        if template_dir:
            template_dirs.insert(0, template_dir)
        template_loader = FileSystemLoader(template_dirs)
    template_env = SandboxedEnvironment(loader=template_loader)

    # read
    items = find_autosummary_in_files(sources)

    # remove possible duplicates
    items = dict([(item, True) for item in items]).keys()

    # keep track of new files
    new_files = []

    # write
    for name, path, template_name in sorted(items):
        if path is None:
            # The corresponding autosummary:: directive did not have
            # a :toctree: option
            continue

        path = output_dir or os.path.abspath(path)
        ensuredir(path)

        try:
    	    name, obj, parent = import_by_name(name)
        except ImportError, e:
            warn('[autosummary] failed to import %r: %s' % (name, e))
            continue

        # skip base modules
        if name.endswith(".base"):
            continue
            
        fn = os.path.join(path, name + suffix)

        # skip it if it exists
        if os.path.isfile(fn):
            continue

        new_files.append(fn)

        f = open(fn, 'w')

        try:
            doc = get_documenter(obj, parent)

            if template_name is not None:
                template = template_env.get_template(template_name)
            else:
                try:
                    template = template_env.get_template('autosummary/%s.rst'
                                                         % doc.objtype)
                except TemplateNotFound:
                    template = template_env.get_template('autosummary/base.rst')


            def exclude_member(obj, name):
                if sys.skip_member(name, obj): 
                    return True
                
                live = getattr(obj, name)

                if inspect.isbuiltin(live): 
                    return True

                real_module = inspect.getmodule(live)
                if real_module is not None:
                    if real_module.__name__ in ["ctypes", 
                                                "unittest"]: 
                        return True
                    
                c = getattr(obj, name)
                if inspect.isclass(c) or inspect.isfunction(c):
                    if (c.__module__!=obj.__name__+".base" and
                        c.__module__!=obj.__name__):
#.........这里部分代码省略.........
开发者ID:Benrflanders,项目名称:Pytris,代码行数:103,代码来源:generate.py

示例9: add_content

# 需要导入模块: from sphinx.jinja2glue import BuiltinTemplateLoader [as 别名]
# 或者: from sphinx.jinja2glue.BuiltinTemplateLoader import init [as 别名]
    def add_content(self, more_content, no_docstring=False):
        if self.doc_as_attr:
            super(GWpyClassDocumenter, self).add_content(
                more_content, no_docstring=no_docstring)
        else:
            name = safe_getattr(self.object, '__name__', None)
            if name:
                # create our own templating environment
                builder = self.env.app.builder or None
                template_dirs = [os.path.join(package_dir, 'ext',
                                              'autosummary', 'templates')]
                if builder is not None:
                    if builder.config.templates_path:
                        template_dirs = (builder.config.templates_path +
                                         template_dirs)
                    # allow the user to override the templates
                    template_loader = BuiltinTemplateLoader()
                    template_loader.init(builder, dirs=template_dirs)
                else:
                    template_loader = FileSystemLoader(template_dirs)
                template_env = SandboxedEnvironment(loader=template_loader)
                template = template_env.get_template('autoclass/class.rst')

                def get_members(obj, typ, include_public=[]):
                    items = []
                    want_all = self.options.inherited_members or \
                               self.options.members is ALL
                    members = zip(*self.get_object_members(want_all)[1])[0]
                    if self.options.exclude_members:
                        members = [m for m in members if
                                   m not in self.options.exclude_members]
                    for name in members:
                        try:
                            documenter = get_documenter(safe_getattr(obj, name),
                                                        obj)
                        except AttributeError:
                            continue
                        if documenter.objtype == typ:
                            items.append(name)
                    public = [x for x in items
                              if x in include_public or not x.startswith('_')]
                    return public, items

                ns = {}
                config = self.env.app.config
                npconfig = dict(
                    use_plots=config.numpydoc_use_plots,
                    show_class_members=config.numpydoc_show_class_members)
                ns['docstring'] = SphinxClassDoc(self.object, config=npconfig)

                ns['members'] = vars(self.object)
                ns['methods'], ns['all_methods'] = get_members(self.object,
                                                               'method',
                                                               ['__init__'])
                ns['attributes'], ns['all_attributes'] = get_members(
                    self.object, 'attribute')

                parts = self.fullname.split('.')
                mod_name, obj_name = '.'.join(parts[:-1]), parts[-1]

                ns['fullname'] = name
                ns['module'] = mod_name
                ns['objname'] = obj_name
                ns['name'] = parts[-1]

                for line in template.render(**ns).split('\n'):
                    if line not in [None, 'None']:
                        self.add_line(line, '<autodoc>')
                self.doc_as_attr = True
开发者ID:gitter-badger,项目名称:gwpy,代码行数:71,代码来源:autoclassapi.py

示例10: generate_autosummary_docs

# 需要导入模块: from sphinx.jinja2glue import BuiltinTemplateLoader [as 别名]
# 或者: from sphinx.jinja2glue.BuiltinTemplateLoader import init [as 别名]
def generate_autosummary_docs(
        sources, output_dir=None, suffix='.rst', warn=_simple_warn,
        info=_simple_info, base_path=None, builder=None, template_dir=None,
        app=None):
    showed_sources = list(sorted(sources))
    if len(showed_sources) > 20:
        showed_sources = showed_sources[:10] + ['...'] + showed_sources[-10:]
    info('[autosummary] generating autosummary for: %s' %
         ', '.join(showed_sources))

    if output_dir:
        info('[autosummary] writing to %s' % output_dir)

    if base_path is not None:
        sources = [osp.join(base_path, filename) for filename in sources]

    # create our own templating environment
    template_dirs = [osp.join(package_dir, 'ext', 'autosummary', 'templates')]
    if builder is not None:
        # allow the user to override the templates
        template_loader = BuiltinTemplateLoader()
        template_loader.init(builder, dirs=template_dirs)
    else:
        if template_dir:
            template_dirs.insert(0, template_dir)
        template_loader = FileSystemLoader(template_dirs)
    template_env = SandboxedEnvironment(loader=template_loader)

    # read
    items = find_autosummary_in_files(sources)

    # remove possible duplicates
    items = list(dict([(item, True) for item in items]).keys())

    # keep track of new files
    new_files = []

    # write
    # noinspection PyTypeChecker
    for name, path, template_name in sorted(items, key=str):
        if path is None:
            # The corresponding autosummary:: directive did not have
            # a :toctree: option
            continue

        path = output_dir or osp.abspath(path)
        ensuredir(path)

        try:
            name, obj, parent, mod_name = import_by_name(name)
        except ImportError as e:
            warn('[autosummary] failed to import %r: %s' % (name, e))
            continue

        fn = osp.join(path, name + suffix)

        # skip it if it exists
        if osp.isfile(fn):
            continue

        new_files.append(fn)

        f = open(fn, 'w')

        try:
            try:
                doc = get_documenter(app, obj, parent)
            except TypeError:
                doc = get_documenter(obj, parent)

            if template_name is not None:
                template = template_env.get_template(template_name)
            else:
                try:
                    template = template_env.get_template('autosummary/%s.rst'
                                                         % doc.objtype)
                except TemplateNotFound:
                    template = template_env.get_template('autosummary/base.rst')

            ns = {}

            if doc.objtype == 'module':
                ns['members'] = dir(obj)
                ns['functions'], ns['all_functions'] = \
                    get_members(app, obj, 'function')
                ns['classes'], ns['all_classes'] = \
                    get_members(app, obj, 'class')
                ns['exceptions'], ns['all_exceptions'] = \
                    get_members(app, obj, 'exception')
                ns['data'], ns['all_data'] = \
                    get_members(app, obj, 'data', imported=True)

                ns['data'] = ', '.join(ns['data'])
                ns['all_data'] = ', '.join(ns['all_data'])

                ns['dispatchers'], ns['all_dispatchers'] = \
                    get_members(app, obj, 'dispatcher', imported=True)
            elif doc.objtype == 'class':
                ns['members'] = dir(obj)
                ns['methods'], ns['all_methods'] = \
#.........这里部分代码省略.........
开发者ID:vinci1it2000,项目名称:dispatcher,代码行数:103,代码来源:autosummary.py

示例11: generate_autosummary_docs

# 需要导入模块: from sphinx.jinja2glue import BuiltinTemplateLoader [as 别名]
# 或者: from sphinx.jinja2glue.BuiltinTemplateLoader import init [as 别名]
def generate_autosummary_docs(
    sources,
    output_dir=None,
    suffix=".rst",
    warn=_simple_warn,
    info=_simple_info,
    base_path=None,
    builder=None,
    template_dir=None,
):

    showed_sources = list(sorted(sources))
    if len(showed_sources) > 20:
        showed_sources = showed_sources[:10] + ["..."] + showed_sources[-10:]
    info("[autosummary] generating autosummary for: %s" % ", ".join(showed_sources))

    if output_dir:
        info("[autosummary] writing to %s" % output_dir)

    if base_path is not None:
        sources = [os.path.join(base_path, filename) for filename in sources]

    # create our own templating environment
    template_dirs = [os.path.join(os.path.dirname(__file__), "templates")]
    if builder is not None:
        # allow the user to override the templates
        template_loader = BuiltinTemplateLoader()
        template_loader.init(builder, dirs=template_dirs)
    else:
        if template_dir:
            template_dirs.insert(0, template_dir)
        template_loader = FileSystemLoader(template_dirs)
    template_env = SandboxedEnvironment(loader=template_loader, extensions=["jinja2.ext.do"])

    # read
    items = find_autosummary_in_files(sources)

    # remove possible duplicates
    items = dict([(item, True) for item in items]).keys()

    # keep track of new files
    new_files = []

    # write
    for name, path, template_name in sorted(items):
        if path is None:
            # The corresponding autosummary:: directive did not have
            # a :toctree: option
            continue

        path = output_dir or os.path.abspath(path)
        ensuredir(path)

        try:
            name, obj, parent = import_by_name(name)
        except ImportError, e:
            warn("[autosummary] failed to import %r: %s" % (name, e))
            continue

        fn = os.path.join(path, name + suffix)

        # skip it if it exists
        if os.path.isfile(fn):
            continue

        new_files.append(fn)

        f = open(fn, "w")

        try:
            doc = get_documenter(obj, parent)

            if template_name is not None:
                template = template_env.get_template(template_name)
            else:
                try:
                    template = template_env.get_template("autosummary/%s.rst" % doc.objtype)
                except TemplateNotFound:
                    template = template_env.get_template("autosummary/base.rst")

            def get_members(obj, typ, include_public=[]):
                # XXX: whole function is a patch!
                if typ in ("function", "class", "exception"):
                    # modules seem to work
                    items = [name for name in dir(obj) if get_documenter(getattr(obj, name), obj).objtype == typ]
                    items = [name for name in items if getattr(obj, name).__module__ == obj.__name__]
                elif typ == "method":
                    # filter methods (__call__) which are defined within this
                    # class (im_class)
                    items = [
                        name
                        for name in dir(obj)
                        if hasattr(getattr(obj, name), "__call__") and hasattr(getattr(obj, name), "im_class")
                    ]
                elif typ == "attribute":
                    # attribute
                    items = [name for name in dir(obj) if not hasattr(getattr(obj, name), "__call__")]
                public = [x for x in items if not x.startswith("_") or x.endswith("__")]
                return public, items

#.........这里部分代码省略.........
开发者ID:jshridha,项目名称:obspy,代码行数:103,代码来源:generate.py

示例12: generate_automodsumm_docs

# 需要导入模块: from sphinx.jinja2glue import BuiltinTemplateLoader [as 别名]
# 或者: from sphinx.jinja2glue.BuiltinTemplateLoader import init [as 别名]
def generate_automodsumm_docs(lines, srcfn, suffix='.rst', warn=None,
                              info=None, base_path=None, builder=None,
                              template_dir=None):
    """
    This function is adapted from
    `sphinx.ext.autosummary.generate.generate_autosummmary_docs` to
    generate source for the automodsumm directives that should be
    autosummarized. Unlike generate_autosummary_docs, this function is
    called one file at a time.
    """

    from sphinx.jinja2glue import BuiltinTemplateLoader
    from sphinx.ext.autosummary import import_by_name, get_documenter
    from sphinx.ext.autosummary.generate import (find_autosummary_in_lines,
                                                 _simple_info, _simple_warn)
    from sphinx.util.osutil import ensuredir
    from sphinx.util.inspect import safe_getattr
    from jinja2 import FileSystemLoader, TemplateNotFound
    from jinja2.sandbox import SandboxedEnvironment

    if info is None:
        info = _simple_info
    if warn is None:
        warn = _simple_warn

    #info('[automodsumm] generating automodsumm for: ' + srcfn)

    # Create our own templating environment - here we use Astropy's
    # templates rather than the default autosummary templates, in order to
    # allow docstrings to be shown for methods.
    template_dirs = [os.path.join(os.path.dirname(__file__), 'templates'),
                     os.path.join(base_path, '_templates')]
    if builder is not None:
        # allow the user to override the templates
        template_loader = BuiltinTemplateLoader()
        template_loader.init(builder, dirs=template_dirs)
    else:
        if template_dir:
            template_dirs.insert(0, template_dir)
        template_loader = FileSystemLoader(template_dirs)
    template_env = SandboxedEnvironment(loader=template_loader)

    # read
    #items = find_autosummary_in_files(sources)
    items = find_autosummary_in_lines(lines, filename=srcfn)
    if len(items) > 0:
        msg = '[automodsumm] {1}: found {0} automodsumm entries to generate'
        info(msg.format(len(items), srcfn))

#    gennms = [item[0] for item in items]
#    if len(gennms) > 20:
#        gennms = gennms[:10] + ['...'] + gennms[-10:]
#    info('[automodsumm] generating autosummary for: ' + ', '.join(gennms))

    # remove possible duplicates
    items = dict([(item, True) for item in items]).keys()

    # keep track of new files
    new_files = []

    # write
    for name, path, template_name in sorted(items):
        if path is None:
            # The corresponding autosummary:: directive did not have
            # a :toctree: option
            continue

        path = os.path.abspath(path)
        ensuredir(path)

        try:
            import_by_name_values = import_by_name(name)
        except ImportError as e:
            warn('[automodsumm] failed to import %r: %s' % (name, e))
            continue

        # if block to accommodate Sphinx's v1.2.2 and v1.2.3 respectively
        if len(import_by_name_values) == 3:
            name, obj, parent = import_by_name_values
        elif len(import_by_name_values) == 4:
            name, obj, parent, module_name = import_by_name_values

        fn = os.path.join(path, name + suffix)

        # skip it if it exists
        if os.path.isfile(fn):
            continue

        new_files.append(fn)

        f = open(fn, 'w')

        try:
            doc = get_documenter(obj, parent)

            if template_name is not None:
                template = template_env.get_template(template_name)
            else:
                tmplstr = 'autosummary/%s.rst'
                try:
#.........这里部分代码省略.........
开发者ID:bnaul,项目名称:gatspy,代码行数:103,代码来源:automodsumm.py

示例13: generate_autosummary_docs

# 需要导入模块: from sphinx.jinja2glue import BuiltinTemplateLoader [as 别名]
# 或者: from sphinx.jinja2glue.BuiltinTemplateLoader import init [as 别名]
def generate_autosummary_docs(
    sources,
    output_dir=None,
    suffix=".rst",
    warn=_simple_warn,
    info=_simple_info,
    base_path=None,
    builder=None,
    template_dir=None,
):

    showed_sources = list(sorted(sources))
    if len(showed_sources) > 20:
        showed_sources = showed_sources[:10] + ["..."] + showed_sources[-10:]
    info("[autosummary] generating autosummary for: %s" % ", ".join(showed_sources))

    if output_dir:
        info("[autosummary] writing to %s" % output_dir)

    if base_path is not None:
        sources = [os.path.join(base_path, filename) for filename in sources]

    # create our own templating environment
    template_dirs = [os.path.join(package_dir, "ext", "autosummary", "templates")]
    if builder is not None:
        # allow the user to override the templates
        template_loader = BuiltinTemplateLoader()
        template_loader.init(builder, dirs=template_dirs)
    else:
        if template_dir:
            template_dirs.insert(0, template_dir)
        template_loader = FileSystemLoader(template_dirs)
    template_env = SandboxedEnvironment(loader=template_loader)

    # read
    items = find_autosummary_in_files(sources)

    # keep track of new files
    new_files = []

    # write
    for name, path, template_name in sorted(set(items), key=str):
        if path is None:
            # The corresponding autosummary:: directive did not have
            # a :toctree: option
            continue

        path = output_dir or os.path.abspath(path)
        ensuredir(path)

        try:
            name, obj, parent, mod_name = import_by_name(name)
        except ImportError as e:
            warn("[autosummary] failed to import %r: %s" % (name, e))
            continue

        fn = os.path.join(path, name + suffix)

        # skip it if it exists
        if os.path.isfile(fn):
            continue

        new_files.append(fn)

        with open(fn, "w") as f:
            doc = get_documenter(obj, parent)

            if template_name is not None:
                template = template_env.get_template(template_name)
            else:
                try:
                    template = template_env.get_template("autosummary/%s.rst" % doc.objtype)
                except TemplateNotFound:
                    template = template_env.get_template("autosummary/base.rst")

            def get_members(obj, typ, include_public=[]):
                items = []
                for name in dir(obj):
                    try:
                        documenter = get_documenter(safe_getattr(obj, name), obj)
                    except AttributeError:
                        continue
                    if documenter.objtype == typ:
                        items.append(name)
                public = [x for x in items if x in include_public or not x.startswith("_")]
                return public, items

            ns = {}

            if doc.objtype == "module":
                ns["members"] = dir(obj)
                ns["functions"], ns["all_functions"] = get_members(obj, "function")
                ns["classes"], ns["all_classes"] = get_members(obj, "class")
                ns["exceptions"], ns["all_exceptions"] = get_members(obj, "exception")
            elif doc.objtype == "class":
                ns["members"] = dir(obj)
                ns["methods"], ns["all_methods"] = get_members(obj, "method", ["__init__"])
                ns["attributes"], ns["all_attributes"] = get_members(obj, "attribute")

            parts = name.split(".")
#.........这里部分代码省略.........
开发者ID:QuLogic,项目名称:sphinx,代码行数:103,代码来源:generate.py

示例14: MakoBridge

# 需要导入模块: from sphinx.jinja2glue import BuiltinTemplateLoader [as 别名]
# 或者: from sphinx.jinja2glue.BuiltinTemplateLoader import init [as 别名]
class MakoBridge(TemplateBridge):
    def init(self, builder, *args, **kw):
        self.jinja2_fallback = BuiltinTemplateLoader()
        self.jinja2_fallback.init(builder, *args, **kw)

        builder.config.html_context['release_date'] = builder.config['release_date']
        builder.config.html_context['site_base'] = builder.config['site_base']

        self.lookup = TemplateLookup(directories=builder.config.templates_path,
            #format_exceptions=True,
            imports=[
                "from builder import util"
            ]
        )

        if rtd:
            import urllib2
            template_url = builder.config['site_base'] + "/docs_base.mako"
            template = urllib2.urlopen(template_url).read()
            self.lookup.put_string("/rtd_base.mako", template)

    def render(self, template, context):
        template = template.replace(".html", ".mako")
        context['prevtopic'] = context.pop('prev', None)
        context['nexttopic'] = context.pop('next', None)

        # RTD layout
        if rtd:
            # add variables if not present, such
            # as if local test of READTHEDOCS variable
            if 'MEDIA_URL' not in context:
                context['MEDIA_URL'] = "http://media.readthedocs.org/"
            if 'slug' not in context:
                context['slug'] = context['project'].lower()
            if 'url' not in context:
                context['url'] = "/some/test/url"
            if 'current_version' not in context:
                context['current_version'] = "latest"

            if 'name' not in context:
                context['name'] = context['project'].lower()

            context['rtd'] = True
            context['toolbar'] = True
            context['layout'] = "rtd_layout.mako"
            context['base'] = "rtd_base.mako"

            # pdf gen is just broken on RTD
            #context['pdf_url'] = "%spdf/%s/%s/%s.pdf" % (
            #        context['MEDIA_URL'],
            #        context['slug'],
            #        context['current_version'],
            #        context['slug']
            #)
        # local docs layout
        else:
            context['rtd'] = False
            context['toolbar'] = False
            context['layout'] = "layout.mako"
            context['base'] = "static_base.mako"

        context.setdefault('_', lambda x: x)
        return self.lookup.get_template(template).render_unicode(**context)

    def render_string(self, template, context):
        # this is used for  .js, .css etc. and we don't have
        # local copies of that stuff here so use the jinja render.
        return self.jinja2_fallback.render_string(template, context)
开发者ID:NoNo1234,项目名称:the_walking_project,代码行数:70,代码来源:mako.py

示例15: generate_autosummary_docs

# 需要导入模块: from sphinx.jinja2glue import BuiltinTemplateLoader [as 别名]
# 或者: from sphinx.jinja2glue.BuiltinTemplateLoader import init [as 别名]
def generate_autosummary_docs(
    sources,
    output_dir=None,
    suffix=".rst",
    warn=_simple_warn,
    info=_simple_info,
    base_path=None,
    builder=None,
    template_dir=None,
):

    showed_sources = list(sorted(sources))
    if len(showed_sources) > 20:
        showed_sources = showed_sources[:10] + ["..."] + showed_sources[-10:]
    info("[autosummary] generating autosummary for: %s" % ", ".join(showed_sources))

    if output_dir:
        info("[autosummary] writing to %s" % output_dir)

    if base_path is not None:
        sources = [os.path.join(base_path, filename) for filename in sources]

    # create our own templating environment
    template_dirs = [os.path.join(package_dir, "ext", "autosummary", "templates")]
    if builder is not None:
        # allow the user to override the templates
        template_loader = BuiltinTemplateLoader()
        template_loader.init(builder, dirs=template_dirs)
    else:
        if template_dir:
            template_dirs.insert(0, template_dir)
        template_loader = FileSystemLoader(template_dirs)
    template_env = SandboxedEnvironment(loader=template_loader)

    # read
    items = find_autosummary_in_files(sources)

    # remove possible duplicates
    items = dict([(item, True) for item in items]).keys()

    # keep track of new files
    new_files = []

    # write
    for name, path, template_name in sorted(items):
        if path is None:
            # The corresponding autosummary:: directive did not have
            # a :toctree: option
            continue

        path = output_dir or os.path.abspath(path)
        ensuredir(path)

        try:
            name, obj, parent = import_by_name(name)
        except ImportError, e:
            warn("[autosummary] failed to import %r: %s" % (name, e))
            continue

        fn = os.path.join(path, name + suffix)

        # skip it if it exists
        if os.path.isfile(fn):
            continue

        new_files.append(fn)

        f = open(fn, "w")

        try:
            doc = get_documenter(obj, parent)

            if template_name is not None:
                template = template_env.get_template(template_name)
            else:
                try:
                    template = template_env.get_template("autosummary/%s.rst" % doc.objtype)
                except TemplateNotFound:
                    template = template_env.get_template("autosummary/base.rst")

            def get_members(obj, typ, include_public=[]):
                items = []
                for name in dir(obj):

                    if sys.skip_member(name, obj):
                        continue
                    if typ in ["class", "function"]:
                        c = getattr(obj, name)
                        if inspect.isclass(c) or inspect.isfunction(c):
                            if c.__module__ != obj.__name__ + ".base" and c.__module__ != obj.__name__:
                                continue
                    try:
                        documenter = get_documenter(safe_getattr(obj, name), obj)
                    except AttributeError:
                        continue
                    if documenter.objtype == typ:
                        items.append(name)
                public = [x for x in items if x in include_public or not x.startswith("_")]
                return public, items

#.........这里部分代码省略.........
开发者ID:niklaskorz,项目名称:pyglet,代码行数:103,代码来源:generate.py


注:本文中的sphinx.jinja2glue.BuiltinTemplateLoader.init方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。