django学习
django支持mysql
- 安装mysql
安装MySQLdb
sudo yum install MySQL-python
修改settings.py
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME' : 'blog', 'USER' : 'root', 'PASSWORD' : '******', 'HOST' : '', 'PORT' : '', } }
- 在数据库中手动建立database blog
设置数据库字段,例如
from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200)
输入命令,使得数据库变更生效
python manage.py makemigrations uploadblog python manage.py migrate
在view中新建记录
import models.Question ... test = Question(question_text = "helloworld") test.save()
django支持post
直接往django后台发post请求会出现403错误,解决方法为链接:
导入模块 from django.views.decorators.csrf import csrf_exempt 在函数前面添加修饰器 @csrf_exempt
区分post与get链接
if request.method == 'GET': do_something() elif request.method == 'POST': do_something_else()
使用gunicorn部署django
由于开发机上安装uwsgi失败,选择用纯python开发的gunicorn来部署django。参考
使用pip安装gunicorn
pip install gunicorn
在项目目录(即manage.py所在的目录)下运行下面命令
gunicorn -w4 -b0.0.0.0:8800 website.wsgi #-w代表开几个线程, -b表示绑定的ip和端口
安装supervisor
pip install supervisor
生成supervisor默认配置文件
echo_supervisord_conf > ~/.jumbo/etc/supervisord.conf
修改配置文件,加入任务
[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
supervisor相关命令
supervisord -c ~/.jumbo/etc/supervisord.conf #启动supervisor supervisorctl -c ~/.jumbo/etc/supervisord.conf [start/stop/restart] [program-name|all] #启动,停止,或重启supervisor管理的某个程序或者所有程序
supervisor的重启
修改supervisord.conf后,使用restart命令重启,发现修改后的配置不生效。需要重启supervisord服务。但直接启动服务会报错,提示’another program is already listening on…’,需要先执行一行unlink命令。
unlink /tmp/supervisord.sock supervisord -c ~/.jumbo/etc/supervisord.conf