Răsfoiți Sursa

创建guest实现前后端分离

James Iter 8 ani în urmă
părinte
comite
e617bc7404
4 a modificat fișierele cu 90 adăugiri și 101 ștergeri
  1. 10 1
      models/utils.py
  2. 78 2
      templates/guest_create.html
  3. 2 96
      views/guest.py
  4. 0 2
      views_route_table.py

+ 10 - 1
models/utils.py

@@ -3,7 +3,7 @@
 
 
 from functools import wraps
-
+import socket
 import commands
 
 from flask import make_response, g, request
@@ -121,6 +121,15 @@ class Utils(object):
     def emit_instruction(message):
         db.r.publish(app.config['instruction_channel'], message=message)
 
+    @staticmethod
+    def port_is_opened(port):
+        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+        result = s.connect_ex(('0.0.0.0', port))
+        if result == 0:
+            return True
+        else:
+            return False
+
 
 class LazyView(object):
     """

+ 78 - 2
templates/guest_create.html

@@ -104,6 +104,8 @@
             if (data.fv.getInvalidFields().length > 0) {    // There is invalid field
                 data.fv.disableSubmitButtons(true);
             }
+        }).on('success.form.fv', function (e, data) {
+            create();
         });
 
         refresh_os_template_image_id_selectpicker($('#os_template_image_id'));
@@ -182,6 +184,72 @@
         });
     }
 
+    function create() {
+        var adjust_ability_value = $('#create_guest_form input:radio[name="ability"]:checked').val();
+
+        adjust_ability_value = adjust_ability_value.match(/^(\d+)c(\d+)g$/i);
+
+        if (adjust_ability_value === null) {
+            alter_danger('指定的配置取值有误!');
+            return
+        }
+
+        var cpu = adjust_ability_value[1];
+        var memory = adjust_ability_value[2];
+
+        var data = {
+            cpu: parseInt(cpu),
+            memory: parseInt(memory),
+            bandwidth: parseInt($('#bandwidth').val()),
+            bandwidth_unit: $('#bandwidth_unit').val(),
+            os_template_image_id: parseInt($('#os_template_image_id').val()),
+            quantity: parseInt($('#quantity').val()),
+            remark: $('#remark').val(),
+            password: $('#password').val(),
+            ssh_keys_id: $('#ssh_key_id').val(),
+            lease_term: 100
+        };
+
+        if (!$('#allocation_by_random').prop('checked')) {
+            data['node_id'] = $('#node_id').val()
+        }
+
+        var go_back_url = '/guests';
+
+        $.ajax({
+            url : '/api/guest',
+            type : 'POST',
+            contentType: "application/json; charset=utf-8",
+            async: false,
+            dataType: "json",
+            data : JSON.stringify(data),
+            error : function(data, textStatus, xhr) {
+                alter_warning('创建实例失败!');
+                alter_danger(data.responseText);
+            },
+            success : function(data, textStatus, xhr) {
+                alter_success('您所提交的资源正在创建中。根据所提交资源的大小,需要等待几到十几分钟。页面将在3秒钟后自动跳转到实例列表页面!');
+
+                $.ajax({
+                    url: '/api/guests',
+                    type : 'GET',
+                    dataType: "json",
+                    error : function(data, textStatus, xhr) {
+                    },
+                    success : function(data, textStatus, xhr) {
+                        var page_size = 10;
+                        var last_page = Math.ceil(data['paging']['total'] / page_size);
+                        go_back_url = "/guests?page_size=" + page_size + "&page=" + last_page;
+                    }
+                });
+            }
+        });
+
+        setTimeout(function() {
+            window.location.href=go_back_url;
+        }, 3000);
+    }
+
     $(function() { "use strict";
         $("#quantity").TouchSpin({
             max: 20,
@@ -202,6 +270,14 @@
         }
     }
 </script>
+<div id="page-content-wrapper">
+    <div id="alert-success-tip" class="alert alert-success alert-top">
+    </div>
+    <div id="alert-warning-tip" class="alert alert-warning alert-top">
+    </div>
+    <div id="alert-danger-tip" class="alert alert-danger alert-top">
+    </div>
+</div>
 <div class="container" style="padding-top: 100px;">
     <div class="panel">
         <div class="panel-body">
@@ -217,7 +293,7 @@
                 </span>
             </a>
             <div class="example-box-wrapper">
-                <form id="create_guest_form" class="form-horizontal bordered-row" action="/guests/create" method="post">
+                <form id="create_guest_form" class="form-horizontal bordered-row" action="javascript:;">
                     <div class="form-group">
                         <label class="col-sm-2 control-label"><span class="glyph-icon icon-elusive-gauge"></span>&nbsp;&nbsp;运算能力</label>
                         <div class="col-sm-10">
@@ -358,7 +434,7 @@
                     <div class="form-group">
                         <label class="col-sm-2 control-label"></label>
                         <div class="col-sm-3 pull-right">
-                            <button type="submit" class="btn btn-blue-alt" style="width: 180px; height: 40px; font-size: 16px;" disabled>创建</button>
+                            <button id="create_guest_form_button" type="submit" class="btn btn-blue-alt" style="width: 180px; height: 40px; font-size: 16px;" disabled>创建</button>
                         </div>
                     </div>
                 </form>

+ 2 - 96
views/guest.py

@@ -6,14 +6,10 @@ import json
 import random
 from flask import Blueprint, render_template, url_for, request
 import requests
-from math import ceil
-import re
-import socket
 import time
 
-from werkzeug.datastructures import ImmutableMultiDict
-
 from models import Database as db
+from models import Utils
 from models.initialize import config
 
 
@@ -58,89 +54,6 @@ def show():
                            pages=ret['data']['pages'], last_page=ret['data']['last_page'])
 
 
-def create():
-    host_url = request.host_url.rstrip('/')
-
-    if request.method == 'POST':
-        ability = request.form.get('ability')
-        bandwidth = request.form.get('bandwidth', 0)
-        bandwidth_unit = request.form.get('bandwidth_unit', 'm')
-        os_template_image_id = request.form.get('os_template_image_id')
-        quantity = request.form.get('quantity')
-        password = request.form.get('password')
-        remark = request.form.get('remark')
-        allocation_by_random = 'allocation_by_random' in request.form
-        node_id = request.form.get('node_id')
-        ssh_keys_id = request.form.getlist('ssh_keys_id')
-
-        if not isinstance(ability, basestring):
-            pass
-
-        m = re.search('^(\d+)c(\d+)g$', ability.lower())
-        if m is None:
-            pass
-
-        cpu = m.groups()[0]
-        memory = m.groups()[1]
-
-        payload = {
-            "cpu": int(cpu),
-            "memory": int(memory),
-            "bandwidth": int(bandwidth),
-            "bandwidth_unit": bandwidth_unit,
-            "os_template_image_id": int(os_template_image_id),
-            "quantity": int(quantity),
-            "remark": remark,
-            "password": password,
-            "ssh_keys_id": ssh_keys_id,
-            "lease_term": 100
-        }
-
-        if not allocation_by_random:
-            payload['node_id'] = node_id
-
-        url = host_url + '/api/guest'
-        headers = {'content-type': 'application/json'}
-        r = requests.post(url, data=json.dumps(payload), headers=headers, cookies=request.cookies)
-        j_r = json.loads(r.content)
-
-        if j_r['state']['code'] != '200':
-            return render_template('failure.html',
-                                   go_back_url='/guests',
-                                   timeout=10000, title='创建失败',
-                                   message_title='创建实例失败',
-                                   message=j_r['state']['sub']['zh-cn'])
-
-        guests_url = host_url + url_for('api_guests.r_get_by_filter')
-        guests_ret = requests.get(url=guests_url, cookies=request.cookies)
-        guests_ret = json.loads(guests_ret.content)
-        page_size = 10
-        last_page = int(ceil(guests_ret['paging']['total'] / float(page_size)))
-
-        return render_template('success.html',
-                               go_back_url='/guests?page={0}&page_size={1}'.format(last_page, page_size),
-                               timeout=10000, title='提交成功',
-                               message_title='创建实例的请求已被接受',
-                               message='您所提交的资源正在创建中。根据所提交资源的大小,需要等待几到十几分钟。页面将在10秒钟后自动跳转到实例列表页面!')
-
-    else:
-        hosts_url = host_url + url_for('api_hosts.r_get_by_filter', alive=True)
-
-        hosts_ret = requests.get(url=hosts_url, cookies=request.cookies)
-        hosts_ret = json.loads(hosts_ret.content)
-
-        return render_template('guest_create.html', hosts_ret=hosts_ret)
-
-
-def port_is_opened(port):
-    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-    result = s.connect_ex(('0.0.0.0', port))
-    if result == 0:
-        return True
-    else:
-        return False
-
-
 def vnc(uuid):
     host_url = request.host_url.rstrip('/')
 
@@ -159,7 +72,7 @@ def vnc(uuid):
 
     port = random.randrange(50000, 60000)
     while True:
-        if not port_is_opened(port=port):
+        if not Utils.port_is_opened(port=port):
             break
 
         port = random.randrange(50000, 60000)
@@ -215,10 +128,3 @@ def detail(uuid):
                            hosts_mapping_by_node_id=hosts_mapping_by_node_id,
                            disks_ret=disks_ret, config_ret=config_ret)
 
-
-def success():
-    return render_template('success.html', go_back_url='/guests', timeout=10000, title='提交成功',
-                           message_title='创建实例的请求已被接受',
-                           message='您所提交的资源正在创建中。根据所提交资源的大小,需要等待几到十几分钟。页面将在10秒钟后自动跳转到实例列表页面!')
-
-

+ 0 - 2
views_route_table.py

@@ -32,8 +32,6 @@ add_rule_views(misc.blueprint, 'reset_password/<token>', views_func='misc.reset_
 add_rule_views(dashboard.blueprint, '', views_func='dashboard.show', methods=['GET'])
 
 add_rule_views(guest.blueprints, '', views_func='guest.show', methods=['GET'])
-add_rule_views(guest.blueprints, '/create', views_func='guest.create', methods=['GET', 'POST'])
-add_rule_views(guest.blueprints, '/success', views_func='guest.success', methods=['GET'])
 add_rule_views(guest.blueprint, '/vnc/<uuid>', views_func='guest.vnc', methods=['GET'])
 add_rule_views(guest.blueprint, '/detail/<uuid>', views_func='guest.detail', methods=['GET'])