the5fire

关注Python、Django、Vim、Linux、Web开发、团队管理和互联网--Life is short, we need Python.


如何快速的部署我的博客(Django)代码

作者:the5fire | 标签:       | 发布:2013-04-25 6:57 a.m. | 阅读量: 13564, 13113

上篇文章介绍了我博客的一个架构,这里具体说下我是如何快速的通过git和fabric来持续部署我的博客的。

先来说一个场景,我前几天上线了一个 OSQA <http://qa.the5fire.com>_ 系统,为了方便以后来的网友在博客留言里提问时看到我有这样的一个系统,所以我决定在留言框上方加一句话,也就是现在在留言上方看到的那个文案:'技术问题还可以到the5fire技术问答上提问'。

那怎么做呢,从开发到上线,过程很简单:

  • 先打开代码,找到文章正文页模板,在留言上方加上这句话。保存代码。
  • git add -p ;git commit; git push;
  • fab re_deploy

然后本地的代码就运行到线上了,是不是很简单?

简单的背后一定是有复杂的支撑,不过我这小小的博客不用很复杂。下面开始阐述下背后的原理

搭建git服务器

不要被题目吓到,只是一个简单的git仓库,基于本地协议(文件系统)。在本地的话就是这样访问: git clone file:///tmp/project.git

在服务器上的话就是: git clone root@1.1.1.1:/tmp/project.git 这其实就是远程的文件系统访问。

那么怎么生成一个.git的文件呢,这其实叫做纯仓库副本,生成命令如下:

.. code::

# 在你项目所在目录
git clone --bare project project.git

之后再把你的project.git上传到服务器上,假设路径为 /tmp/project.git , 这时到你的项目目录中,添加remote origin: git remote add origin root@服务器ip:/tmp/project.git

到此你的git服务器就搭建好了,你本地可以直接push代码到服务器上。

用fabric快速部署

所谓部署,其实就是把你最新的代码放到运行的环境中去,然后重启服务。

上篇文章有提到,我用supervisor来管理我的Django进程,所以我需要做的就是在部署代码的地方pull一下最新的代码然后重启supervisor,不需要考虑virtuanlenv的事情。 过程就是这样,具体看代码就行了:

.. code:: python

#coding:utf-8

from fabric.api import run, roles, cd, parallel, task
from fabric.state import env

www_path = '/yourhome/virtuanlenv/project'
supervisord_bin_path = '/yourhome/virtualenv/bin'
supervisord_conf_file = '/yourhome/virtuanlenv/project/supervisord.conf'

env.roledefs = {
    'remote': ['root@yourserverip']
}

@task
@parallel(22)
@roles('remote')
def top():
    run("top -b | head -n 1")


def git_co(path, branch='master'):
    with(cd(path)):
        run('git reset --hard && git pull -f && git checkout %s' % branch)


def supervisord_restart(path, conf_path):
    with(cd(path)):
        run('./supervisorctl -c %s restart all' % (conf_path, ))


@task
@roles('remote')
def re_deploy(branch='master'):
    git_co(www_path, branch=branch)
    supervisord_restart(supervisord_bin_path, supervisord_conf_file)

综述

这就是一个完整的过程,在这个过程之上,从开发小功能点/修改BUG到上线,其实用不了几分钟。当然如果考虑到高可用还有很多事情要做。这只是一个开端。

2017-05-15更新:

我录了一套Django开发的视频,可以通过我的公众号查看。

- from the5fire.com
----EOF-----

微信公众号:Python程序员杂谈


其他分类: