参考django官方文档(https://docs.djangoproject.com/zh-hans/5.0/intro/reusable-apps/)
打包应用
在项目中创建一个应用,并完成功能和业务逻辑,完成测试。
- 创建项目
django-admin startproject xxx_admin - 进入项目
cd xxx_admin - 创建应用
django-admin startapp common - 完成common应用的功能和业务逻辑
- 完成common的测试
在项目外其他位置来配置包
在其他目录下创建一个文件夹来存放要打包的文件, 文件夹名称使用
django-前缀作为标记1
cd ~/Training/django-common
将
xxx_admin项目中的common应用复制到django-common目录下在
django-common目录下创建如下文件1
2
3
4
5
6
7
8django-common/
- common/
- README.rst
- LICENSE
- pyproject.toml
- setup.cfg
- setup.py
- MANIFEST.inREADME.rst内容为应用简介1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29=====
Polls
=====
Polls is a Django app to conduct web-based polls. For each question,
visitors can choose between a fixed number of answers.
Detailed documentation is in the "docs" directory.
Quick start
-----------
1. Add "polls" to your INSTALLED_APPS setting like this::
INSTALLED_APPS = [
...
'polls',
]
2. Include the polls URLconf in your project urls.py like this::
path('polls/', include('polls.urls')),
3. Run ``python manage.py migrate`` to create the polls models.
4. Start the development server and visit http://127.0.0.1:8000/admin/
to create a poll (you'll need the Admin app enabled).
5. Visit http://127.0.0.1:8000/polls/ to participate in the poll.LICENSE可以为一个空文件,其目的是写一个授权协议pyproject.toml使打包的依赖1
2
3[build-system]
requires = ['setuptools>=40.8.0', 'wheel']
build-backend = 'setuptools.build_meta:__legacy__'setup.cfg是打包的配置参数1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30[metadata]
name = django-polls
version = 0.1
description = A Django app to conduct web-based polls.
long_description = file: README.rst
url = https://www.example.com/
author = Your Name
author_email = yourname@example.com
license = BSD-3-Clause # Example license
classifiers =
Environment :: Web Environment
Framework :: Django
Framework :: Django :: X.Y # Replace "X.Y" as appropriate
Intended Audience :: Developers
License :: OSI Approved :: BSD License
Operating System :: OS Independent
Programming Language :: Python
Programming Language :: Python :: 3
Programming Language :: Python :: 3 :: Only
Programming Language :: Python :: 3.8
Programming Language :: Python :: 3.9
Topic :: Internet :: WWW/HTTP
Topic :: Internet :: WWW/HTTP :: Dynamic Content
[options]
include_package_data = true
packages = find:
python_requires = >=3.8
install_requires =
Django >= X.Y # Replace "X.Y" as appropriatesetup.py使打包的运行文件1
2
3from setuptools import setup
setup()MANIFEST.in是在打包中明确要包含的其他模块和包1
2
3
4include LICENSE
include README.rst
recursive-include polls/static *
recursive-include polls/templates *在’django-common/‘目录下打包,命令如下:
1
ptyhon3 setup.py sdist
该命令会在目录下生成一个dist的目录,里面包含了完成的应用包, 后缀为tar.gz
使用应用包
在创建虚拟环境中使用命令安装包
1
pip install --user ../django-common/dist/django-common-0.1.tar.gz
在项目settings.py的
INSTALLED_APPS中增加应用, 这样就可以使用common的全部功能了1
2
3...
'common',
...卸载应用包
1
pop uninstall django-common