首页 > 解决方案 > Pyinstaller 不包含 django rest 框架模板

问题描述

我有一个使用 rest_framework 的 django 应用程序,一切正常,我正在使用 pyinstaller 为这个应用程序获取一个 exe,可执行应用程序工作正常,但是当我尝试访问一个可浏览的 api 以获取其他框架,例如 http:// localhost:8000/api/flags/ 以查看可浏览的 api,我收到此错误

TemplateDoesNotExist at /api/flags/
rest_framework/horizontal/form.html
Request Method: GET
Request URL:    http://localhost:8000/api/flags/
Django Version: 3.0.7
Exception Type: TemplateDoesNotExist
Exception Value:    
rest_framework/horizontal/form.html
Exception Location: site-packages\django\template\loader.py in get_template, line 19
Python Executable:  C:\Workset\proj_test\app.exe
Python Version: 3.8.3
Python Path:    
['C:\\Workset\\proj_test\\dist\\app\\base_library.zip',
 'C:\\Workset\\proj_test\\dist\\app']
Server time:    Thu, 9 Jul 2020 09:52:53 +0000
Template-loader postmortem
Django tried loading these templates, in this order:

Using engine django:

django.template.loaders.filesystem.Loader: C:\Workset\proj_test\dist\app\src\templates\rest_framework\horizontal\form.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Workset\proj_test\dist\app\django\contrib\admin\templates\rest_framework\horizontal\form.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Workset\proj_test\dist\app\django\contrib\auth\templates\rest_framework\horizontal\form.html (Source does not exist)

这意味着 Pyinstaller 不包含 rest_framework 默认 ui 模板,我如何将这些模板包含在 Pyinstaller 生成的输出 dist 文件夹中

注意:rest api 本身工作正常,即调用 rest api 工作正常

标签: djangodjango-rest-frameworkpyinstaller

解决方案


我知道这是一篇较旧的帖子,但我想我会分享我的决心。

我在这里找到了 django 特定的钩子文件(linux 机器):/home/<< user >>/.local/lib/python3.6/site-packages/PyInstaller/hooks/hook-django.py

发现它只提取了 django site-packages 文件夹中的任何内容。Django rest_framework 不包含在 django 站点包中,它位于同一级别的自己的文件夹中。因此,我通过添加以下代码编辑了这个钩子文件以包含 rest_framework 文件夹:

    datas, binaries, hiddenimports = collect_all('django')
    datas_rest, binaries_rest, hiddenimports_rest = collect_all('rest_framework')
    datas += datas_rest
    binaries += binaries_rest
    hiddenimports += hiddenimports_rest

然后重新运行pyinstaller。确保它包含 dist 文件夹中的 rest_framework 文件夹。


推荐阅读