Skip to content

Django开发和部署

新建项目

bash
django-admin startproject moviemash

运行服务器

shell
python manage.py runserver

创建投票app

bash
python manage.py startapp votes

设置路由

bash
# moviemash/url.py
urlpatterns = [
    path("admin/", admin.site.urls),
    path("",include("votes.urls"))
]

添加app

python
INSTALLED_APPS = [
    "votes.apps.VotesConfig",
    ...
    ]

创建模型

python
from django.db import models

# Create your models here.

class Movie(models.Model):
    title = models.CharField(max_length=100)
    image_url = models.URLField()
    def __str__(self) -> str:
        return self.title 
    def total_votes(self):
        return self.vote_set.count()  # 使用反向关联计算与该电影相关的投票数

    def vote(self):
        vote = Vote.objects.create(movie=self)
        vote.save()

class Vote(models.Model):
    movie = models.ForeignKey(Movie, on_delete=models.CASCADE)
    votes = models.IntegerField(default=1)  # 将默认值设置为1

    def __str__(self) -> str:
        return f"{self.movie}{self.votes}"

部署(aliyun)

参考教程:

uwsgi部署命令

bash
uwsgi --http 0.0.0.0:8001 --file moviemash/wsgi.py --static-map /static=/root/moviemash/static

使用systemd守护进程

创建 /etc/systemd/system/emperor.uwsgi.service

[Unit]
Description=uWSGI Emperor
After=syslog.target

[Service]
ExecStart= uwsgi --http 0.0.0.0:8001 --file moviemash/wsgi.py --static-map /static=/root/moviemash/static
# 或许之前要加上cd命令进入项目目录
RuntimeDirectory=uwsgi
Restart=always
KillSignal=SIGQUIT
Type=notify
StandardError=syslog
NotifyAccess=all

[Install]
WantedBy=multi-user.target

运行

systemctl start emperor.uwsgi.service

查看状态

systemctl status emperor.uwsgi.service

输出

emperor.uwsgi.service - uWSGI Emperor
 Loaded: loaded (/etc/systemd/system/emperor.uwsgi.service)
       Active: active (running) since Tue, 17 May 2011 08:51:31 +0200; 5s ago
Main PID: 30567 (uwsgi)
       Status: "The Emperor is governing 1 vassals"
       CGroup: name=systemd:/system/emperor.uwsgi.service
               ├ 30567 /root/uwsgi/uwsgi --ini /etc/uwsgi/emperor.ini
               ├ 30568 /root/uwsgi/uwsgi --ini werkzeug.ini
               └ 30569 /root/uwsgi/uwsgi --ini werkzeug.ini

结束

systemctl stop emperor.uwsgi.service