背景
之前用 Django 写了一个 WEB 项目,最近有人想拿它测试下,看能不能满足需求。一看部署文档就打算放弃。主要是一个正儿八经的 Django 网站要想拉起来依赖项还是比较多的,比如 WEB 服务器 nginx 、应用服务器 wsgi 、数据库服务器 MySQL (可选) ...
于是想对这类项目做些改进,把 Django 网站项目做成一个软件包,安装之后就直接能用。等觉得好用,再给它配上对应的服务器软件也不迟。想了想,我还真有能力做到,说干就干。
效果展示
我觉得这次是真的效果不错,安装后就能直接运行。
代码语言:javascript复制pip install dbm-center
dbm-center runserver 0.0.0.0:8080
ps -ef | grep dbm
nginx 732824 732292 4 19:53 pts/2 00:00:00 /usr/local/python-3.10.4/bin/python3.10 /usr/local/python/bin//dbm-center runserver 0.0.0.0:8080
nginx 732825 732824 9 19:53 pts/2 00:00:00 /usr/local/python-3.10.4/bin/python3.10 /usr/local/python/bin//dbm-center runserver 0.0.0.0:8080
可以说这个改进非常成功,其对功能验证来说算是极度友好了,两条命令就能搞完。
目前这台云主机还没有欠费,直接这样就能访问到。http://1.13.13.169:8080
原理
Django 其实它自包含了一个测试用的 WEB 服务器,只要我复用的这个就不再需要其它依赖。剩下的就是给项目导出一个可执行文件,而这个可执行文件,直接复用 manage.py 就行;没有想到最终的解决方案,会如此简单。
整个项目的结构如下
代码语言:javascript复制tree .
├── bin
│ └── dbm-center
├── dbmcenter
│ ├── __init__.py
│ ├── asgi.py
│ ├── dbm-center
│ │ ├── css
│ │ │ └── app.940106bb.css
│ │ ├── favicon.ico
│ │ ├── index.html
│ │ └── js
│ │ ├── app.4bb2602a.js
│ │ ├── app.4bb2602a.js.map
│ │ ├── chunk-vendors.ae02e612.js
│ │ └── chunk-vendors.ae02e612.js.map
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── manage.py
└── setup.py
9 directories, 29 files
setup.py 的内容如下(setup.py 用于导出可执行文件 bin/dbm-center):
代码语言:javascript复制import os
import re
from setuptools import setup
setup(name='dbm-center',
version='0.2.1',
description='dbm-center 数据库管理中心服务端程序',
author="Neeky",
author_email="neeky@live.com",
maintainer='Neeky',
maintainer_email='neeky@live.com',
scripts=['bin/dbm-center'],
packages=['dbmcenter'],
package_data={'dbmcenter': ['dbm-center/*', 'dbm-center/css/*', 'dbm-center/js/*']},
install_requires=['Django==4.1.2'],
url='https://github.com/Neeky/dbm-center',
python_requires='>=3.6.*',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Operating System :: POSIX',
'Operating System :: MacOS :: MacOS X',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8']
)
bin/dbm-center 可执行文件的内容如下
代码语言:javascript复制#!/usr/bin/env python3
# -*- coding: utf8 -*-
# 这里可以直接复用 manage.py
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dbmcenter.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
github
项目地址:https://github.com/Neeky/dbm-center