1. 程式人生 > >軟體測試之後端開發——django

軟體測試之後端開發——django

django與前端資料互動

1、通過ajax進行通訊

頁面載入完成後,在頁面上操作,在頁面上通過 ajax 方法得到新的資料(再向伺服器傳送一次請求)並顯示在網頁上,這種情況適用於頁面不重新整理的情況下,動態載入一些內容。比如使用者輸入一個值或者點選某個地方,動態地把相應內容顯示在網頁上。
舉一個實際的例子,一個測試用例,點選執行按鈕要將結果顯示到介面上,程式碼如下
index.html

<div class="admin-biaogelist">
        <div class="listbiaoti am-cf">
            <ul class="am-icon-flag on"> 編輯用例</ul>
            <dl class="am-icon-home" style="float: right;"> 當前位置: 用例管理 > <a href="#">用例編輯</a></dl>
        </div>

        <div class="fbneirong">
            <div class="contact-row">
                <div class="col-md-5">
                    <p><b>測試用例:</b></p>
                    <form id="create_testcase">
                        <textarea name="code" id="code" style="width:90%;height: 570px">{{jcehtml}}</textarea>
                        <p><button type="button" class="am-btn am-btn-success am-radius" id="run" onclick="run_ajax('#create_testcase', '/api/create_testcase/')">Run</button></p>
                     </form>
                </div>
                <div class="col-md-5">
                      <ul id="myTab" class="nav nav-tabs">
                          <li class="active">
                              <a href="#home" data-toggle="tab">執行結果</a>
                          </li>
                      </ul>
                      <div id="myTabContent" class="tab-content">
                             <div class="tab-pane fade in active" id="home">
                                   <textarea name="consonle" id="consonle" style="width:90%;height: 570px"></textarea>
                             </div>
                      </div>
                      <script>
                                var console = CodeMirror.fromTextArea(document.getElementById("consonle"), {
                                        mode: "text",
                                        readOnly:true,
                                        lineNumbers: true,
                                        indentUnit: 4,
                                        theme: "monokai",	//設定主題
                                        styleActiveLine: true, // 當前行背景高亮
                                        lineWrapping: false,//程式碼摺疊
                                        foldGutter: true,
                                        gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
                                        matchBrackets: true,	//括號匹配
                                });
                                console.setSize(null,570)
                                console.setOption("extraKeys", {
                                // Tab鍵換成4個空格
                                    Tab: function(cm) {
                                        var spaces = Array(cm.getOption("indentUnit") + 1).join(" ");
                                        cm.replaceSelection(spaces);
                                    },
                                    // F11鍵切換全屏
                                    "F11": function(cm) {
                                        cm.setOption("fullScreen", !cm.getOption("fullScreen"));
                                    },
                                    // Esc鍵退出全屏
                                    "Esc": function(cm) {
                                        if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
                                    }
                                });

                                var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
                                    mode: {name: "python",
                                    version: 2.7,
                                    singleLineStringErrors: false},
                                    lineNumbers: true,
                                    indentUnit: 4,
                                    theme: "monokai",	//設定主題
                                    styleActiveLine: true, // 當前行背景高亮
                                    lineWrapping: true,	//程式碼摺疊
                                    foldGutter: true,
                                    gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
                                    matchBrackets: true,	//括號匹配
                                });
                                editor.setSize(null,570)
                                editor.setOption("extraKeys", {
                                // Tab鍵換成4個空格
                                    Tab: function(cm) {
                                        var spaces = Array(cm.getOption("indentUnit") + 1).join(" ");
                                        cm.replaceSelection(spaces);
                                    },
                                    // F11鍵切換全屏
                                    "F11": function(cm) {
                                        cm.setOption("fullScreen", !cm.getOption("fullScreen"));
                                    },
                                    // Esc鍵退出全屏
                                    "Esc": function(cm) {
                                        if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
                                    }
                                });

                                $(function () {
                                    $('#myTab li:eq(1) a').tab('show');
                                });
                  </script>
                 </div>   
         </div>        
</div>

效果如下圖所示:
圖1 編輯測試用例

為了樣式,引入了codemirror進行線上編輯

 var console = CodeMirror.fromTextArea(document.getElementById("consonle"), {
                                        mode: "text",
                                        readOnly:true,
                                        lineNumbers: true,
                                        indentUnit: 4,
                                        theme: "monokai",	//設定主題
                                        styleActiveLine: true, // 當前行背景高亮
                                        lineWrapping: false,//程式碼摺疊
                                        foldGutter: true,
                                        gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
                                        matchBrackets: true,	//括號匹配
                                });
                                console.setSize(null,570)
                                console.setOption("extraKeys", {
                                // Tab鍵換成4個空格
                                    Tab: function(cm) {
                                        var spaces = Array(cm.getOption("indentUnit") + 1).join(" ");
                                        cm.replaceSelection(spaces);
                                    },
                                    // F11鍵切換全屏
                                    "F11": function(cm) {
                                        cm.setOption("fullScreen", !cm.getOption("fullScreen"));
                                    },
                                    // Esc鍵退出全屏
                                    "Esc": function(cm) {
                                        if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
                                    }
                                });

這樣的話,ajax只能引用該變數,而不是使用$(’#consonle’)來引用元素

function run_ajax(id, url){
     var data = $(id).serializeJSON();
     $.ajax({
        type: 'post'    ,
        url: url,
        data: JSON.stringify(data),
        contentType: "application/json",
        success: function (data) {
           // $('#consonle').append(data)
            console.setValue(data)
        }
        ,
        error: function () {
            myAlert('Sorry,伺服器可能開小差啦, 請重試!');
        }
    });
}

2、直接將資料返回給前端html

直接在檢視函式(views.py中的函式)中將 JSON物件 和網頁其它內容一起傳遞到Django模板(一次性地渲染,還是同一次請求)
views.py程式碼如下:

@login_check
def create_testcase(request,id=None):
    """
    編輯用例
    :param request:
    :param id:
    :return:
    """
    account = request.session["now_account"]

    if request.is_ajax():
        kwargs = json.loads(request.body.decode('utf-8'))
        msg = run_testcase(**kwargs)
        result = json.loads(msg)
        value = result.values()[0]
        # print value.encode('utf8')
        return HttpResponse(get_ajax_msg(value.encode('utf8'),'/api/create_testcase/1/'))

    else:
        cmd = "ApiUpdateUgcVideo"
        jcehtml = ""
        request = ""
        if id != None:
            test_info = TestCaseInfo.objects.get_case_by_id(id)
            jcehtml = jceCMDHandle(cmd,test_info[0].filename)
            request = test_info[0].request
        request = request.encode('utf8')
        manage_info = {
            'account': account,
            'jcehtml':jcehtml,
            'request':request,
            'env': EnvInfo.objects.all().order_by('-create_time'),
            'project': ProjectInfo.objects.all().order_by('-update_time'),
        }

        return render_to_response('create_testcase.html',manage_info)

create_testcase.html程式碼如下:

<form id="create_testcase">
       <textarea name="code" id="code" style="width:90%;height: 570px">{{jcehtml}}</textarea>
       <p><button type="button" class="am-btn am-btn-success am-radius" id="run" onclick="run_ajax('#create_testcase', '/api/create_testcase/')">Run</button></p>
 </form>

3、將資料返回給js來顯示資料

通過js可以直接操作html進行資料的顯示,通過後臺返回的資料也可以操作html進行資料的顯示,那麼是否可以將後臺的資料返回給js,然後通過js來操作html嗎呢?答案是可以的。
views.py程式碼如下

@login_check
def create_testcase(request,id=None):
    """
    編輯用例
    :param request:
    :param id:
    :return:
    """
    account = request.session["now_account"]

    if request.is_ajax():
        kwargs = json.loads(request.body.decode('utf-8'))
        msg = run_testcase(**kwargs)
        result = json.loads(msg)
        value = result.values()[0]
        # print value.encode('utf8')
        return HttpResponse(get_ajax_msg(value.encode('utf8'),'/api/create_testcase/1/'))

    else:
        cmd = "ApiUpdateUgcVideo"
        jcehtml = ""
        request = ""
        if id != None:
            test_info = TestCaseInfo.objects.get_case_by_id(id)
            jcehtml = jceCMDHandle(cmd,test_info[0].filename)
            request = test_info[0].request
        request = request.encode('utf8')
        manage_info = {
            'account': account,
            'jcehtml':jcehtml,
            'request':request,
            'env': EnvInfo.objects.all().order_by('-create_time'),
            'project': ProjectInfo.objects.all().order_by('-update_time'),
        }

        return render_to_response('create_testcase.html',manage_info)

create_testcase.html程式碼如下:

 <script>
	var request = {{request | safe}},
</script>

4、參考文章

1、https://code.ziqiangxuetang.com/django/django-json-templates.html