Angular js 结合Python tornado 实例
Angular js 与 python tornado的结合使用,解决后端的支持。
本文主要是通过使用Angular JS的$http()方法来实现与python tornado后端的结合,实例如下template文件:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 5 <title>angular+tornado</title> 6 </head> 7 <script src="http://apps.bdimg.com/libs/angular.js/1.3.9/angular.min.js"></script> 8 <body> 9 10 <div ng-app="myApp" ng-controller="customersCtrl"> 11 <h2>实现angularjs+tornado例子</h2> 12 <ul id="ul"> 13 <li ng-repeat="x in names"> 14 // x.name + ', ' + x.country // 15 </li> 16 </ul> 17 18 </div> 19 20 <script> 21 var names1 = document.getElementById("ul").innerHTML; 22 var app = angular.module('myApp', []); 23 app.config(function($interpolateProvider) { 24 $interpolateProvider.startSymbol('//'); 25 $interpolateProvider.endSymbol('//'); 26 }); 27 app.controller('customersCtrl', function($scope, $http) { 28 $http.get("/test_http_action?user="+names1) 29 .success(function (response) {$scope.names = response.records;}); 30 }); 31 </script> 32 33 </body> 34 </html> 35
python tornado后端的main文件:
1 import os.path 2 import uuid 3 import json 4 import tornado.ioloop 5 import tornado.web 6 from tornado.options import define, options 7 8 9 10 define("port", default=9003, help="run on the given port", type=int) 11 12 13 class Application(tornado.web.Application): 14 15 def __init__(self): 16 handlers = [ 17 (r"/http", Httprpl), 18 (r"/test_http_action", Testhttprpl), 19 20 21 ] # 在此列表中追加新的路由cal 22 23 settings = dict( 24 cookie_secret=str(uuid.uuid4()), 25 template_path=os.path.join(os.path.dirname(__file__), "templates"), 26 static_path=os.path.join(os.path.dirname(__file__), "static"), 27 xsrf_cookies=True, 28 login_url="/", 29 debug=True 30 ) 31 tornado.web.Application.__init__(self, handlers, **settings) 32 33 class Httprpl(tornado.web.RequestHandler): 34 35 def get(self): 36 37 self.render( 38 "http_py.html",) 39 40 class Testhttprpl(tornado.web.RequestHandler): 41 42 def get(self): 43 user = self.get_argument("user") 44 print(user) 45 obj = {"records":[{"name": "张三", "country": "中国"}, 46 {"name": "Jay", "country": "美国"}, 47 {"name": "李四", "country": "中国"} 48 ]} 49 a = json.dumps(obj) 50 self.write(a) 51 52 if __name__ == "__main__": 53 app = Application() 54 app.listen(options.port) 55 tornado.ioloop.IOLoop.current().start()
终端输出结果:
>> python3 pagetestmain.py >> <li ng-repeat="x in names">// x.name ', ' x.country //</li>
网页效果:
最后完成了两者的结合,前端获取后端传来的值的同时有传值给后端,后端取得前端传来的值以后去进行一些数据的操作之后再回显给前端的过程。
努力吧,为了媳妇儿,为了家。。。