访问Python模块中包含的静态文件

时间:2018-11-09 21:50:10

标签: python python-3.x pip python-module

我正在使用pip安装模块。以下是setup.py:

from setuptools import setup, find_packages

with open('requirements.txt') as f:
    required = f.read().splitlines()

print(required)
setup(
    name='glm_plotter',
    packages=find_packages(),
    include_package_data=True,
    install_requires=required
)

和MANIFEST.in:

recursive-include glm_plotter/templates *
recursive-include glm_plotter/static *

安装时,目录和文件似乎已安装:

  ...
  creating build/lib/glm_plotter/templates
  copying glm_plotter/templates/index.html -> build/lib/glm_plotter/templates
...
  creating build/bdist.linux-x86_64/wheel/glm_plotter/templates
  copying build/lib/glm_plotter/templates/index.html -> build/bdist.linux-x86_64/wheel/glm_plotter/templates
 ...

当我导入该模块时:

>>> import g_plotter
>>> dir(g_plotter)
['CORS', 'Flask', 'GLMparser', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'app', 'controllers', 'views']

我没有看到静态文件。我不确定这是否是访问静态文件的正确方法。

1 个答案:

答案 0 :(得分:1)

dir()不会告诉您有关静态文件的任何信息。获取此数据的正确方法(或至少其中一种)是使用pkg_resources(setuptools的一部分)中的README函数,例如:

import pkg_resources

pkg_resource.resource_listdir('glm_plotter', 'templates')
# Returns a list of files in glm_plotter/templates

pkg_resource.resource_string('glm_plotter', 'templates/index.html')
# Returns the contents of glm_plotter/templates/index.html as a byte string
相关问题