django学习

本文详细介绍如何在Django项目中集成MySQL数据库,并通过gunicorn和supervisor进行部署。包括安装MySQL及其Python驱动、配置Django数据库连接、创建模型及迁移、处理POST请求等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

django学习


django支持mysql

  1. 安装mysql
  2. 安装MySQLdb

    sudo yum install MySQL-python
    
  3. 修改settings.py

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME' : 'blog',
            'USER' : 'root',
            'PASSWORD' : '******',
            'HOST' : '',
            'PORT' : '',
        }
    }
    
  4. 在数据库中手动建立database blog
  5. 设置数据库字段,例如

    from django.db import models
    class Question(models.Model):
        question_text = models.CharField(max_length=200)
    
  6. 输入命令,使得数据库变更生效

    python manage.py makemigrations uploadblog
    python manage.py migrate
    
  7. 在view中新建记录

    import models.Question
    ...
    test = Question(question_text = "helloworld")
    test.save()
    

django支持post

  1. 直接往django后台发post请求会出现403错误,解决方法为链接:

    导入模块
    from django.views.decorators.csrf import csrf_exempt
    在函数前面添加修饰器
    @csrf_exempt
    
  2. 区分post与get链接

    if request.method == 'GET':
        do_something()
    elif request.method == 'POST':
        do_something_else()
    

使用gunicorn部署django

由于开发机上安装uwsgi失败,选择用纯python开发的gunicorn来部署django。参考

  1. 使用pip安装gunicorn

    pip install gunicorn
    
  2. 在项目目录(即manage.py所在的目录)下运行下面命令

    gunicorn -w4 -b0.0.0.0:8800 website.wsgi #-w代表开几个线程, -b表示绑定的ip和端口
    
  3. 安装supervisor

    pip install supervisor
    
  4. 生成supervisor默认配置文件

    echo_supervisord_conf > ~/.jumbo/etc/supervisord.conf
    
  5. 修改配置文件,加入任务

    [program:website]
    command=gunicorn -w4 -b0.0.0.0:8800 website.wsgi
    directory=/home/users/liuchengyin02/workspace/website/website
    startsecs=0
    stopwaitsecs=0
    autostart=true
    autorestart=true
    
  6. supervisor相关命令

    supervisord -c ~/.jumbo/etc/supervisord.conf #启动supervisor
    supervisorctl -c ~/.jumbo/etc/supervisord.conf [start/stop/restart] [program-name|all] #启动,停止,或重启supervisor管理的某个程序或者所有程序
    
  7. supervisor的重启

    修改supervisord.conf后,使用restart命令重启,发现修改后的配置不生效。需要重启supervisord服务。但直接启动服务会报错,提示’another program is already listening on…’,需要先执行一行unlink命令。

    unlink /tmp/supervisord.sock
    supervisord -c ~/.jumbo/etc/supervisord.conf
    

使用apache部署django

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值