【问题标题】:Accessing static files included in a Python module访问 Python 模块中包含的静态文件
【发布时间】:2019-04-13 11:48:45
【问题描述】:

我正在使用 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']

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

【问题讨论】:

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


【解决方案1】:

dir() 不会告诉你任何关于静态文件的信息。访问这些数据的正确方法(或至少其中一种方法)是使用 pkg_resources(setuptools 的一部分)中的 resource_* 函数,例如:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 2018-05-24
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多