如何在Django中调用远程织物方法

2024-04-24 12:56:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要通过django调用远程机器上的fabric方法。我的意思是当用户发送一个给定的请求时,会得到一个远程机器的主机名。 像这样:

def get_hostname(request):  
  hostname = os.system('fab remote_server hostname')  
  return hostname  

Tags: django方法用户机器get远程remoteos
3条回答

如果您的服务器有所需的部分为fabric,您应该能够只导入您的fabfile调用函数直接。在

(这只是我想出的一些代码YMMW)

import fabfile as f #Your fabfile must be somewhere it can be imported


def get_hostname(request):  
  hostname = f.remote_server(hostname)
  return hostname

您也可以直接从django导入和使用织物

检查1.3版之后的fabric.tasks.execute()。在

为了获得更好的控制和灵活性,您应该使用fabric作为库。参见:http://docs.fabfile.org/en/1.3.3/usage/library.html

import fabric.api as fab
from fabric.network import disconnect_all
from contextlib import contextmanager

@context_manager
def ssh(settings):
    with settings:
         try:
            yield
         finally:
            disconnect_all()

def hostname(request, host='somehost', user='someuser', pw='secret'):  
    with ssh(fab.settings(host_string=host, user=user, password=pw)):
         return fab.run('hostname')

相关问题 更多 >