将Mercurial整合到Flask项目中

来源:互联网 发布:天狼星期货软件 编辑:程序博客网 时间:2024/04/30 08:47
将Mercurial整合到Flask项目中的目的是以Mercurial作为后端代码仓库,Flask作为web框架,来构建一个拥有WEB界面的代码仓库系统。
但是将Mercurial的各种组件拿到取出来是需要对Mercurial的源码相当熟悉才能实现的,所以这里选择的方法是利用请求的差异,判断返回的是Mercurial的app还是Flask的app


判断是不是Mercurial客户端的请求的方法如下(来自kallithea项目的lib/middleware/simplehg.py):
def is_mercurial(environ):    """    Returns True if request's target is mercurial server - header    ``HTTP_ACCEPT`` of such request would start with ``application/mercurial``.    """    http_accept = environ.get('HTTP_ACCEPT')    path_info = environ['PATH_INFO']    if http_accept and http_accept.startswith('application/mercurial'):        ishg_path = True    else:        ishg_path = False    log.debug('pathinfo: %s detected as Mercurial %s',        path_info, ishg_path    )    return ishg_path

而执行判断的地方,在FLask类的__call__方法中,重写其__call__方法:

from flask import Flask as _Flaskclass Flask(_Flask)    def __call__(self, environ, start_response):        if is_mercurial(environ):            return self.hg_app(environ, start_response)        return self.wsgi_app(environ, start_response)    def hg_app(self, environ, start_response):        config = "/home/ubuntu/kallithea/hg.cfg"        from mercurial import demandimport; demandimport.enable()        from mercurial.hgweb import hgweb        application = hgweb(config)        return application(environ, start_response)

这里的hg_app方法中,具体处理了如何调用Mercurial的app,其实这就是配置Mercurial的wsgi应用的代码,只是最后加了一个return application(environ, start_response),因为我们需要返回响应。

而这里面的配置文件/home/ubuntu/kallithea/hg.cfg需要实际配置该项目的细节,例如:
[web]allow_push = *   #允许所有人pushpush_ssl = false  #关闭push的ssl要求style = monobluebaseurl =   #需要保留,否则出错[paths]/ = /home/ubuntu/kallithea/repositories/*   #定义了通过url访问实际指向的文件路径,这里的/repo 转到/home/ubuntu/kallithea/repositories/repo下[collections]


测试:
ubuntu@ubuntu-Lenovo:~/test/kallithea$ hg clone http://localhost:5000/test1目标目录: test1正在请求全部修改正在增加修改集正在增加清单正在增加文件改变已增加 3 个修改集,包含 3 个改变,修改了 2 个文件updating to branch default2 files updated, 0 files merged, 0 files removed, 0 files unresolved$ lslocal  myrepo  remote  test  test1$ cd test1/$ lsnew  README$ hg rm new$ lsREADME$ hg statusR new$ hg ci -m'rm newfile' -uhuil1$ hg push http://localhost:5000/test1正在推到 http://localhost:5000/test1正在搜索修改remote: 正在增加修改集remote: 正在增加清单remote: 正在增加文件改变remote: 已增加 1 个修改集,包含 0 个改变,修改了 0 个文件


这只是简单的实现,如果想要添加权限,用户等控制,则需要实现更多的细节了。
                                             
0 0
原创粉丝点击