浏览代码

分离完ssh-key。

James Iter 8 年之前
父节点
当前提交
eae84b146b
共有 4 个文件被更改,包括 127 次插入90 次删除
  1. 77 2
      api/ssh_key.py
  2. 1 0
      api_route_table.py
  3. 36 5
      templates/ssh_keys_show.html
  4. 13 83
      views/ssh_key.py

+ 77 - 2
api/ssh_key.py

@@ -1,8 +1,9 @@
 #!/usr/bin/env python
 # -*- coding: utf-8 -*-
+from math import ceil
 
-
-from flask import Blueprint
+import requests
+from flask import Blueprint, url_for
 from flask import request
 from werkzeug.datastructures import ImmutableMultiDict
 import json
@@ -357,3 +358,77 @@ def r_unbind(ssh_key_id, uuids):
     except ji.PreviewingError, e:
         return json.loads(e.message)
 
+
+@Utils.dumps2response
+def r_show():
+    args = list()
+    page = int(request.args.get('page', 1))
+    page_size = int(request.args.get('page_size', 10))
+    keyword = request.args.get('keyword', None)
+    order_by = request.args.get('order_by', None)
+    order = request.args.get('order', None)
+
+    if page is not None:
+        args.append('page=' + page.__str__())
+
+    if page_size is not None:
+        args.append('page_size=' + page_size.__str__())
+
+    if keyword is not None:
+        args.append('keyword=' + keyword.__str__())
+
+    if order_by is not None:
+        args.append('order_by=' + order_by)
+
+    if order is not None:
+        args.append('order=' + order)
+
+    ssh_keys_url = url_for('api_ssh_keys.r_get_by_filter', _external=True)
+    if keyword is not None:
+        ssh_keys_url = url_for('api_ssh_keys.r_content_search', _external=True)
+
+    if args.__len__() > 0:
+        ssh_keys_url = ssh_keys_url + '?' + '&'.join(args)
+
+    ssh_keys_ret = requests.get(url=ssh_keys_url, cookies=request.cookies)
+    ssh_keys_ret = json.loads(ssh_keys_ret.content)
+
+    last_page = int(ceil(ssh_keys_ret['paging']['total'] / float(page_size)))
+    page_length = 5
+    pages = list()
+    if page < int(ceil(page_length / 2.0)):
+        for i in range(1, page_length + 1):
+            pages.append(i)
+            if i == last_page or last_page == 0:
+                break
+
+    elif last_page - page < page_length / 2:
+        for i in range(last_page - page_length + 1, last_page + 1):
+            if i < 1:
+                continue
+            pages.append(i)
+
+    else:
+        for i in range(page - page_length / 2, page + int(ceil(page_length / 2.0))):
+            pages.append(i)
+            if i == last_page or last_page == 0:
+                break
+
+    ret = dict()
+    ret['state'] = ji.Common.exchange_state(20000)
+
+    ret['data'] = {
+        'ssh_keys': ssh_keys_ret['data'],
+        'paging': ssh_keys_ret['paging'],
+        'page': page,
+        'page_size': page_size,
+        'keyword': keyword,
+        'pages': pages,
+        'last_page': last_page,
+        'order_by': order_by,
+        'order': order
+    }
+
+    return ret
+
+

+ 1 - 0
api_route_table.py

@@ -162,6 +162,7 @@ add_rule_api(ssh_key.blueprint, '/_bound/<ssh_key_id>', api_func='ssh_key.r_boun
 add_rule_api(ssh_key.blueprint, '/_unbound/<ssh_key_id>', api_func='ssh_key.r_unbound', methods=['GET'])
 add_rule_api(ssh_key.blueprint, '/_bind/<ssh_key_id>/<uuids>', api_func='ssh_key.r_bind', methods=['PUT'])
 add_rule_api(ssh_key.blueprint, '/_unbind/<ssh_key_id>/<uuids>', api_func='ssh_key.r_unbind', methods=['PUT'])
+add_rule_api(ssh_key.blueprints, '/_show', api_func='ssh_key.r_show', methods=['GET'])
 
 # 快照操作
 add_rule_api(snapshot.blueprint, '', api_func='snapshot.r_create', methods=['POST'])

+ 36 - 5
templates/ssh_keys_show.html

@@ -180,8 +180,8 @@
                     validators: {
                         notEmpty: {},
                         stringLength: {
-                            min: 380,
-                            max: 420
+                            min: 200,
+                            max: 1000
                         }
                     }
                 }
@@ -191,6 +191,8 @@
             if (data.fv.getInvalidFields().length > 0) {    // There is invalid field
                 data.fv.disableSubmitButtons(true);
             }
+        }).on('success.form.fv', function (e, data) {
+            create();
         });
 
         init_multi_selector($('#bind_multi_selector'));
@@ -459,6 +461,35 @@
             }
         });
     }
+
+    function create() {
+        var data = {
+            label: $('#label').val(),
+            public_key: $('#public_key').val()
+        };
+
+        var go_back_url = '/ssh_keys';
+
+        $.ajax({
+            url : '/api/ssh_key',
+            type : 'POST',
+            contentType: "application/json; charset=utf-8",
+            async: false,
+            dataType: "json",
+            data : JSON.stringify(data),
+            error : function(data, textStatus, xhr) {
+                alter_warning('添加 SSH Key 失败!');
+                alter_danger(data.responseText);
+            },
+            success : function(data, textStatus, xhr) {
+                alter_success('您所提交的 SSH Key 已创建。页面将在3秒钟后自动跳转到模板列表页面!');
+            }
+        });
+
+        setTimeout(function() {
+            window.location.href=go_back_url;
+        }, 3000);
+    }
 </script>
 <div class="panel">
     <div class="panel-body">
@@ -491,7 +522,7 @@
                 </tr>
                 </thead>
                 <tbody>
-                {% for item in ssh_keys_ret.data %}
+                {% for item in ssh_keys %}
                 <tr role="row" class="odd" onmouseover="row_onmouseover(this);" onmouseout="row_onmouseout(this);">
                     <td style="display: none;">{{ item.id }}</td>
                     <td><input title="选中" type="checkbox"></td>
@@ -543,7 +574,7 @@
                                 <div class="col-sm-6">
                                 </div>
                                 <div class="col-sm-3" style="font-size: 12px; padding-top: 5px; text-align: right;">
-                                    共有{{ ssh_keys_ret.paging.total }}条,每页显示:
+                                    共有{{ paging.total }}条,每页显示:
                                     <select id="page_size" name="datatable-row-highlight_length" title="page_size" class="form-control" style="height: 22px; vertical-align: baseline;">
                                         <option value="10" {% if page_size == 10 %} selected {% endif %}>10</option>
                                         <option value="20" {% if page_size == 20 %} selected {% endif %}>20</option>
@@ -639,7 +670,7 @@
             </div>
             <div class="modal-body" style="padding-top: 0; padding-bottom: 0;">
                 <div class="example-box-wrapper">
-                    <form id="add_ssh_key_form" class="form-horizontal bordered-row" action="/ssh_key" method="post">
+                    <form id="add_ssh_key_form" class="form-horizontal bordered-row" action="javascript:;">
                         <div class="form-group">
                             <div class="col-sm-2"></div>
                             <label class="col-sm-2 control-label"><span class="glyph-icon icon-elusive-compass-circled"></span>&nbsp;&nbsp;名称</label>

+ 13 - 83
views/ssh_key.py

@@ -5,7 +5,6 @@
 import json
 from flask import Blueprint, render_template, url_for, request, redirect
 import requests
-from math import ceil
 
 
 __author__ = 'James Iter'
@@ -28,93 +27,24 @@ blueprints = Blueprint(
 
 
 def show():
-    args = list()
-    page = int(request.args.get('page', 1))
-    page_size = int(request.args.get('page_size', 10))
-    keyword = request.args.get('keyword', None)
-    order_by = request.args.get('order_by', None)
-    order = request.args.get('order', None)
+    url = url_for('api_ssh_keys.r_show', _external=True)
+    if request.args.__len__() >= 1:
+        args = list()
 
-    if page is not None:
-        args.append('page=' + page.__str__())
+        for k, v in request.args.items():
+            args.append('='.join([k, v]))
 
-    if page_size is not None:
-        args.append('page_size=' + page_size.__str__())
+        url += '?' + '&'.join(args)
 
-    if keyword is not None:
-        args.append('keyword=' + keyword.__str__())
+    ret = requests.get(url=url, cookies=request.cookies)
+    ret = json.loads(ret.content)
 
-    if order_by is not None:
-        args.append('order_by=' + order_by)
-
-    if order is not None:
-        args.append('order=' + order)
-
-    host_url = request.host_url.rstrip('/')
-
-    ssh_keys_url = host_url + url_for('api_ssh_keys.r_get_by_filter')
-    if keyword is not None:
-        ssh_keys_url = host_url + url_for('api_ssh_keys.r_content_search')
-
-    if args.__len__() > 0:
-        ssh_keys_url = ssh_keys_url + '?' + '&'.join(args)
-
-    ssh_keys_ret = requests.get(url=ssh_keys_url, cookies=request.cookies)
-    ssh_keys_ret = json.loads(ssh_keys_ret.content)
-
-    last_page = int(ceil(ssh_keys_ret['paging']['total'] / float(page_size)))
-    page_length = 5
-    pages = list()
-    if page < int(ceil(page_length / 2.0)):
-        for i in range(1, page_length + 1):
-            pages.append(i)
-            if i == last_page or last_page == 0:
-                break
-
-    elif last_page - page < page_length / 2:
-        for i in range(last_page - page_length + 1, last_page + 1):
-            if i < 1:
-                continue
-            pages.append(i)
-
-    else:
-        for i in range(page - page_length / 2, page + int(ceil(page_length / 2.0))):
-            pages.append(i)
-            if i == last_page or last_page == 0:
-                break
-
-    return render_template('ssh_keys_show.html', ssh_keys_ret=ssh_keys_ret,
-                           page=page, page_size=page_size, keyword=keyword, pages=pages, order_by=order_by, order=order,
-                           last_page=last_page)
+    return render_template('ssh_keys_show.html', ssh_keys=ret['data']['ssh_keys'], paging=ret['data']['paging'],
+                           page=ret['data']['page'], page_size=ret['data']['page_size'], keyword=ret['data']['keyword'],
+                           pages=ret['data']['pages'], order_by=ret['data']['order_by'], order=ret['data']['order'],
+                           last_page=ret['data']['last_page'])
 
 
 def create():
-    host_url = request.host_url.rstrip('/')
-
-    if request.method == 'POST':
-        label = request.form.get('label')
-        public_key = request.form.get('public_key', '')
-
-        payload = {
-            "label": label,
-            "public_key": public_key
-        }
-
-        url = host_url + '/api/ssh_key'
-        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='/ssh_keys',
-                                   timeout=10000, title='添加失败',
-                                   message_title='添加 SSH Key 失败',
-                                   message=j_r['state']['sub']['zh-cn'])
-
-        return render_template('success.html', go_back_url='/ssh_keys', timeout=10000, title='提交成功',
-                               message_title='添加 SSH Key 的请求已被接受',
-                               message='您所提交的 SSH Key 已创建。页面将在10秒钟后自动跳转到模板列表页面!')
-
-    else:
-        return redirect(url_for('v_ssh_keys.show'))
+    return redirect(url_for('v_ssh_keys.show'))