django进阶: 编写可复用程序
可重用的程序
The Python Package Index (PyPI) 有许大量的包,都可被用在你自己的 Python 项目中。同样可以在 Django Packages 中查找已发布的可重用应用,也可将其引入到你的项目中。Django 本身也是一个 Python 包,也就是说你可以将已有的 Python 包或 Django 应用并入你的项目。你只需要编写属于你的那部分即可。
打包工具
推荐使用setuptools打包工具,使用pip 来安装和卸载这个工具
打包步骤
-
新建一个文件夹, 如 django-做前缀,避免项目冲突
-
将项目目录一如新文件夹, 如polls拷贝到django-polls目录下
-
在文件夹下新建README.rst文件包含以下内容
===== 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.
-
新建LICENCSE 文件。选择一个授权协议,发布代码授权证书时必须的
-
创建
setup.cfg
和setup.py
文件用于说明构建和安装应用的细节# django-polls/setup.cfg [metadata] name = django-polls version = 0.1 description = A Django app to conduct Web-based polls. long_description = file: READNE.rst url = https://www.example.com author = Your Name autor_email = youname@example.com license = BSD-3-Clause # 实例的协议 classifiers = Environment :: Web Environment Framework :: Django Framework :: Django :: X.Y # "X.Y" 看情况替换 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.6 Programming Language :: Python :: 3.7 Programming Language :: Python :: 3.8 Topic :: Internet :: WWW/HTTP Topic :: Internet :: WWW/HTTP :: Dynamic Content [OPTIONS] include_package_data = true packages = find:
# django-polls/setup.py from setuptools import setup setup()
-
默认包中包含Pyton模块和包, 重建MANIFEST.in 文件包含说明包含的内容
# MANIFEST.in include LICENSE include README.rst recursive-include polls/static * recursive-include polls/templates * recrusive-include docs *
-
创建一个空目录docs 用于未来编写文档。额外添加一行至 MANIFEST.in文
-
构建自己的应用包,通过一些命令,生成django-polls-0.1.tar.gz
python setup.py sdist
将打包的库安装到项目中
python -m pip install django-polls/dist/django-polls-0.1.tar.gz