Flask作api+angularjs調用實現獲取數據及刪除的完整實例

在oschina開源中國學習到很多東西,今天回饋下. 現用python框架flask作api很方便,angular用久了有依賴了,爲方便後面的同窗,給出個完整實例. ##FLASK部分,用到了flask-json,和一個轉json的方法 ###固然你也能夠用flask的api專用插件,但我在現實場景用的時間,有些地方不是很方便,你們若是是作app應用,能夠用flask的api插件,畢竟是有速率限制restful特性,我如今的是混合用法html

pip install flask-json

###先作數據 models.pypython

class Qiu(db.Model):
    __tablename__ = 'qius'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64))
    active = db.Column('is_active',
                       db.Boolean(),
                       nullable=False,
                       default=False)  # 是否激活
    phone = db.Column(db.String(20), server_default='')  # 企業電話

    def to_json(self):
        """
        轉json,由於angular讀的是json,這裏要注意,很經常使用的方法
        """
        return {
            'id': self.id,
            'name': self.name,
            'active': self.active,
            'phone':  self.phone,
        }

###flaskapi,這裏作了獲取數據和刪除接口angularjs

from app.models import  Qiu
from flask import jsonify
from flask_json import JsonError, json_response
@main.route('/api/v1.0/qius', methods=['GET'])
def get_qius():
    """
    獲取單個成員信息
    :param user_id:
    """
    qius = Qiu.query.all()
    ##轉json
    return json_response(qius=(qiu.to_json() for qiu in qius))

@main.route('/api/v1.0/qius', methods=['delete']) 
#這裏的methods是delete,能夠用post,angular中也要改成post
def delete_qius():
    """
    刪除成員信息
    :param user_id:
    :return: TRUE FALSE
    """
    # if not request.json or not 'id' in request.json:
    #從angularjs調用的json中取數據
    user_id=request.json['deluid']
    qiu = Qiu.query.get(user_id)
    db.session.remove(qiu)
    db.session.commit()
    res = "ok"
    return jsonify({'res': res})

###再作視圖 views.py 視圖的功能當前只是頁面渲染,數據是用angularjs讀的json

from app.models import  Qiu
from flask import render_template, redirect, request, url_for, flash, abort

@main.route('/qiuadmin', methods=['GET', 'POST'])
def qiuadmin():    
    #qius=Qiu.query.all()
    #return render_template('main/qiu.html',qius=qius)
    return render_template('main/qiu.html')

###qiu.htmlflask

<script>	
//這個是csrftoken,angularjs會用cookie模塊調用	
var csrftoken = "{{ csrf_token() }}"		
</script>
<div ng-controller="MainCtrl">
<tr ng-repeat="qiu in qius">

                                            <td class="center">
                                                [{[qiu.name||'']}](#)
                                            </td>
                                            <td class="center">{[qiu.phone]}</td>
                                            <td class="center">
                                             {[qiu.active]}
                                            </td>            
</tr>
</div>

###最後就是angularjs調用api,獲取和刪除數據api

var yunApp = angular.module('yunApp', ['ngCookies']);
yunApp.run(function ($http, $cookies) {
//這裏取的是csrftoken 否則angularjs post或delete時會報csrf失敗錯誤
    $http.defaults.headers.post['X-CSRFToken'] = csrftoken;
});
//解決flask和angular在模板中的標籤同樣會衝突,把angularjs的標籤換成{[xxx]}
yunApp.config(
    [
        '$interpolateProvider',
        function ($interpolateProvider) {
            $interpolateProvider.startSymbol('{[');
            $interpolateProvider.endSymbol(']}');
        }
    ]
);

//主控制器
yunApp.controller(
    'MainCtrl', [
        "$scope", "$http",  "$log", "$document", "$window",
        function ($scope, $http, $log, $document,$window,) {
$rootScope.qius=null;
           $http.get('/api/v1.0/qius')
                .success(function (response) {
                    $rootScope.qius = response.qius;
                    $scope.qius = $rootScope.qius;

                }).error(function () {
                    alert('獲取數據失敗' );
                });
            //刪除用戶及轉移數據方法
            $scope.removeit = function (userid) {
                // var param = { uid: userid };
                if ($window.confirm('你肯定要刪除用戶嗎?')) {
                    //alert("肯定");
                    // return true;
                    if (userid) {
                        data = {deluid: userid};
                        $http({
                            method: 'DELETE',
                            url: '/api/v1.0/qius',
                            data: data,
                            headers: {'Content-Type': 'application/json'}
                        }).success(function (data) {
                            if (data.res == "ok") {
                                alert('成功');
                                $http.get('/api/v1.0/qius')
                                    .success(function (response) {
                                        $rootScope.qius = response.qius;                                        v
                                        $scope.qius = $rootScope.qius;
                                    }).error(function () {
                                    alert('失敗');
                                });
                            }
                            else if (data.status == 200 && data.res == "no")                         alert('失敗');
                        }).error(function () {
                            alert('刪除用戶失敗');
                        });
                    }
                    else {
                        alert('參數錯誤');
                        $timeout(function () {
                            setInterval(function () {
                                $window.location.reload();
                            }, 800)
                        })
                    }
                } else {
                    //alert("取消");
                    return false;
                }
            };

        }
    ]);

angular cookie須要加載:angular-cookies.min.js,如不須要刪除更新刪除操做,可刪除['ngCookies']和下面獲取csrftoken部分.restful

完畢,有問題留言cookie

相關文章
相關標籤/搜索