Accessing static files included in a Python module

此生再无相见时 提交于 2021-02-08 11:51:22

问题


I'm installing my module with pip. The following is the 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
)

and MANIFEST.in:

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

When installing, the directories and files seem to get installed:

  ...
  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
 ...

When I go to import this module:

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

I'm not seeing the static files. I'm not sure if this is the correct way to go about getting access to the static files.


回答1:


dir() won't tell you anything about static files. The correct way (or one of them, at least) to get access to this data is with the resource_* functions in pkg_resources (part of setuptools), e.g.:

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


来源:https://stackoverflow.com/questions/53233670/accessing-static-files-included-in-a-python-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!