在 Django中操作KVM上的虛擬機

Django是在Python中非常著名的Web Framework,如果我們想要透過Web介面來操作在主機上的VM,方法也非常簡單。主要的程式要寫在views.py中。假設我們要讓瀏覽器一進主網頁的時候就馬上可以看到目前執行中和非執行中的VM,則views.py中要這樣寫:

[code]
from django.http import HttpResponse
from django.template.loader import get_template
import libvirt, sys

# Create your views here.
def index(request):
conn = libvirt.openReadOnly("qemu:///system")
running = []
for id in conn.listDomainsID():
vm = conn.lookupByID(id)
running.append(vm.name())
inactive = []
for domname in conn.listDefinedDomains():
inactive.append(domname)
conn.close()
template = get_template(‘index.html’)
html = template.render({‘running’: running, ‘inactive’: inactive})
return HttpResponse(html)
[/code]

因為使用到template,所以我們也準備了一個index.html,放在templates目錄之下。index.html的內容如下所示:

[code]
<!DOCTYPE html>
<html>
<head>
<meta charset=’utf-8′>
<title> VM Management </title>
</head>
<body>
<h2>Welcome to Master Monitor Management System</h2>
<h3>Running VMs</h3>
<ul>
{% for dm in running %}
<li> {{ dm }} </li>
{% empty %}
<p>沒有正在執行中的VM</p>
{% endfor %}
</ul>
<h3>Inactive VMs</h3>
<ul>
{% for dm in inactive %}
<li> {{ dm }} </li>
{% empty %}
<p>沒有處於inactive狀態的VM</p>
{% endfor %}
</ul>
</body>
</html>
[/code]

要讓網頁主網址可以執行index()這個函數去render index.html,urls.py裡面也要改一下,如下所示:

[code]
from django.conf.urls import url
from django.contrib import admin
from mm.views import index

urlpatterns = [
url(r’^admin/’, admin.site.urls),
url(r’^$’, index),
]
[/code]

再加上其它的一些必要的Django基本設定,就大功告成了。以下是執行的結果畫面:

2016-02-26_15-47-01

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *