Django中的一個app應用,實際上就是相當于一個包
最好將一個應用的相關文件(包括模板、靜態文件)放在一起,以便用于其它的項目
Django中將app以包(package)的形式重復利用
-
打包app
- 創建新的目錄(如django-polls)以存放app(注意該目錄名不應該同其它package名相同)
- 將polls文件拷入django-polls文件中
- 在django-polls文件夾下創建README.rst文件
===== Polls ===== Polls is a simple 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:: url(r'^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文件(許可文件)
- 創建安裝文件setup.py(setuptools文檔)
import os from setuptools import find_packages, setup with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-polls', version='0.1', packages=find_packages(), include_package_data=True, license='BSD License', # example license description='A simple Django app to conduct Web-based polls.', long_description=README, url='https://www.example.com/', author='Your Name', author_email='yourname@example.com', classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Framework :: Django :: X.Y', # replace "X.Y" as appropriate 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', # example license 'Operating System :: OS Independent', 'Programming Language :: Python', # Replace these appropriately if you are stuck on Python 2. 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], )
- 創建MANIFEST.in文件
默認情況下,將創建的包中只會包含與python相關的模塊和包,為了將一些其它文件(如templates/、README.rst、LICENSE)也包含進新創建的包中,需要在MANIFEST.in文件中進行指定
include LICENSE include README.rst recursive-include polls/static * recursive-include polls/templates *
- (可選)在新創建的app中包含細節描述文件
創建docs文件夾,并在MANIFEST.in文件中添加一句
recursive-inclued docs *
- 創建包
在命令提示符中輸入
> python setup.py sdist
創建的包位于新建的dist文件夾中,名稱為django-polls-0.1.tar.gz
-
使用應用包
- 安裝該app包(最好在虛擬環境下)
pip install --user django-polls/dist/django-polls-0.1.tar.gz # 注意是自己的相對路徑
- 現在就可以使用該app了(可以刪去原項目中的polls文件了)
- 卸載包
pip uninstall django-polls