Django 项目搭建
Python版本: 3.9
Django版本:4.2
环境准备
创建一个项目文件夹,或者拉取一个现有仓库的项目
$ mkdir amslide && cd amslide
# git clone git@github.com:amuluze/amslide.git为项目生成 Poetry 配置
# 安装 Poetry
$ pip install poetry
# 初始化 poetry
$ mkdir slide && cd slide
$ poetry init
This command will guide you through creating your pyproject.toml config.
Package name [slide]:
Version [0.1.0]:
Description []:
Author [Amu <wangjialong89@yeah.net>, n to skip]:
License []: MIT
Compatible Python versions [^3.9]:
Would you like to define your main dependencies interactively? (yes/no) [yes]
You can specify a package in the following forms:
- A single name (requests): this will search for matches on PyPI
- A name and a constraint (requests@^2.23.0)
- A git url (git+https://github.com/python-poetry/poetry.git)
- A git url with a revision (git+https://github.com/python-poetry/poetry.git#develop)
- A file path (../my-package/my-package.whl)
- A directory (../my-package/)
- A url (https://example.com/packages/my-package-0.1.0.tar.gz)
Package to add or search for (leave blank to skip):
Would you like to define your development dependencies interactively? (yes/no) [yes]
Package to add or search for (leave blank to skip):
Generated file
[tool.poetry]
name = "slide"
version = "0.1.0"
description = ""
authors = ["Amu <wangjialong89@yeah.net>"]
license = "MIT"
readme = "README.md"
[tool.poetry.dependencies]
python = "^3.9"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
Do you confirm generation? (yes/no) [yes]执行
peotry init后,会有很多提示输入,不确定的内容就先按下Enter使用默认值,后续可以再修改pyproject.toml文件。
初始化完成后,会再 slide 目录下生成 pyproject.toml 文件,文件内容如下:
[tool.poetry]
name = "amslide"
version = "0.1.0"
description = ""
authors = ["Amu <wangjialong89@yeah.net>"]
readme = "README.md"
[tool.poetry.dependencies]
python = "^3.9"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"配置 Poetry 安装源, 在 pyproject.toml 里添加以下内容
[[tool.poetry.source]]
name = 'aliyun.mirrors'
url = "http://mirrors.aliyun.com/pypi/simple/"虚拟环境
创建虚拟环境
查看 Poetry 配置
$ poetry config --list
cache-dir = "/Users/amu/Library/Caches/pypoetry"
experimental.system-git-client = false
installer.max-workers = null
installer.modern-installation = true
installer.no-binary = null
installer.parallel = true
keyring.enabled = true
repositories.aliyun.mirrors = {"url": "http://mirrors.aliyun.com/pypi/simple/"}
solver.lazy-wheel = true
virtualenvs.create = true
virtualenvs.in-project = null
virtualenvs.options.always-copy = false
virtualenvs.options.no-pip = false
virtualenvs.options.no-setuptools = false
virtualenvs.options.system-site-packages = false
virtualenvs.path = "{cache-dir}/virtualenvs" # /Users/amu/Library/Caches/pypoetry/virtualenvs
virtualenvs.prefer-active-python = false
virtualenvs.prompt = "{project_name}-py{python_version}"
warnings.export = true当参数 virtualenvs.create=true 时,执行 poetry install 或 poetry add 时会检测当前项目是否有虚拟环境,没有就自动创建。
激活虚拟环境
执行 Poetry 的命令并不需要激活虚拟环境,因为 Poetry 会自动检测当前虚拟环境,如果想在当前目录对应的虚拟环境中执行命令,可以使用以下命令:
$ peotry run python test.py如果想显示的激活虚拟环境,使用如下命令:
$ peotry shell
Spawning shell within /Users/amu/Library/Caches/pypoetry/virtualenvs/amslide-CfKYd4Ay-py3.9
# 退出虚拟环境
$ exit创建项目
$ poetry add django==4.2使用 add 命令进行安装,它将自动找到合适的版本约束并安装包和子依赖项。
初始化 Django 项目
$ poetry run django-admin startproject slide .创建完成后,项目目录结构如下:
.
├── manage.py
├── poetry.lock
├── pyproject.toml
└── slide
├── __init__.py
├── asgi.py
├── settings.py
├── urls.py
└── wsgi.py在 slide/slide 目录下新建 view.py 文件,并输入如下代码:
from django.http import HttpResponse
# 视图函数
def hello(request):
return HttpResponse("Hello World!")接着绑定 URL 与视图函数。打开 slide/slide/urls.py 文件,进行如下修改:
from django.urls import path
from . import view
urlpatterns = [
# path('admin/', admin.site.urls),
path("hello", view.hello)
]运行项目
# 激活虚拟环境
$ poetry shell
# 安装依赖
$ poetry install
# 运行服务
$ python manage.py runserver 0.0.0.0:8000
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
April 30, 2024 - 16:41:09
Django version 4.2, using settings 'slide.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.然后在浏览器中输入 http://localhost:8000/hello 可以看到返回了 Hello World!
部署项目
gunicorn 介绍
这里选用
gunicorn来运行Django项目
gunicorn 启动一般有两种方式,可以在项目目录下建立 gunicorn.conf.py 配置文件,也可以在启动 gunicorn 时直接加上相关命令
方式一:
- 需要在项目的
settings.py中的 INSTALLED_APPS 添加gunicorn:
INSTALLED_APPS = [
...
...
'gunicorn', # 部署用
]- 在项目根目录下创建
gunicorn.conf.py文件
bind = "0.0.0.0:8000"
loglevel = "info"
workders = 2
threads = 4
proc_name = "amslide"启动
$ gunicorn amslide.wsgi:application -c /xx/xx/gunicorn.conf.py方式二:
直接使用 gunicron 启动
$ gunicorn amslide.wsgi:application -b 0.0.0.0:8000gunicorn 使用
我们这里使用方式一进行部署。
在根目录下新建文件 setup.sh、Dockerfile,内容如下:
FROM python:3.9-buster
WORKDIR /app
COPY . /app
# 安装peotry
RUN pip install -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com poetry && \
poetry config virtualenvs.create false && poetry install --no-interaction --no-ansi && \
chmod +x /app/setup.sh
EXPOSE 8000
# 这里有点坑,不加 -n 服务启动不了
CMD ["/bin/sh", "-c", "/app/setup.sh"]# setup.sh
#!/bin/sh
python manage.py migrate
gunicorn -c /app/gunicorn.conf.py slide.wsgi:application打包镜像
$ docker build -t amuluze/amslide:v1.0.0 .运行测试
$ docker run --name slidev --rm -it -p 8000:8000 amuluze/amslide:v1.0.0
$ curl http://localhost:8000/hello
Hello World!