Django 项目打包成 exe

一、下载(pyinstaller)

pip install pyinstaller

二、生成spec文件

pyi-makespec -D manage.py

三、swagger依赖

1、配置静态文件

# settings.py
 
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

2、收集静态文件

python manage.py collectstatic

3、配置url

# urls.py
 
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.urls import path, include
from rest_framework.documentation import include_docs_urls
from drf_yasg import openapi
from drf_yasg.views import get_schema_view
from django.conf import settings
from django.conf.urls.static import static
 
schema_view = get_schema_view(
   openapi.Info(
      title="Your API",
      default_version='v1',
      description="API documentation",
   ),
   public=True,
)
 
urlpatterns = [
    path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
    path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
    path('admin/', admin.site.urls),
    path('api/', include('your_api.urls')),  # 你的 API URL 配置
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + staticfiles_urlpatterns()  # 添加静态文件服务配置

4、把drf-yasg中的templates\drf-yasg 复制到 项目的 templates文件夹下

四、配置spec文件

# -*- mode: python ; coding: utf-8 -*-


a = Analysis(
    ['manage.py'],
    pathex=[],
    binaries=[('./log', 'log'),('./templates', 'templates'), ('./static', 'static'),('./staticfiles', 'staticfiles')],
    datas=[],
    hiddenimports=['app1', 'app2'],
    hookspath=[],
    hooksconfig={},
    runtime_hooks=[],
    excludes=[],
    noarchive=False,
    optimize=0,
)
pyz = PYZ(a.pure)

exe = EXE(
    pyz,
    a.scripts,
    [],
    exclude_binaries=True,
    name='manage',
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    console=True,
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
)
coll = COLLECT(
    exe,
    a.binaries,
    a.datas,
    strip=False,
    upx=True,
    upx_exclude=[],
    name='manage',
)

hiddenimports 根据提示添加

五、打包

pyinstaller manage.spec

六、运行

在dist\manage文件夹下

manage.exe runserver 0.0.0.0:port --noreload

 

posted @ 2025-03-04 17:03  市丸银  阅读(294)  评论(0)    收藏  举报