Tornado——異步操作(前端ajax和後端同步/異步操作)

異步編程:異步編程處理方式,主要用於數據業務的底層非同步操作,有兩種操作手段,Ajax和後端服務器的異步模塊。

1.Ajax

Ajax的異步操作:通過前端直接發送Ajax請求到目標服務器(以獲取天氣信息爲例,發送請求到氣象局),獲取數據並更新前端頁面,此操作不需要經過後端。獲取到數據後通過DOM操作渲染頁面。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax請求獲取天氣預報信息</title>
    <script src="static/jquery/jquery-2.2.4.js"></script>
</head>
<body>
<form>
    <input type="text" name="city" id="city"><br/>
    <div id="info"></div>
</form>
<script>
//失焦事件
    $('#city').blur(function(){

    $.ajax({
    'url':'http://wthrcdn.etouch.cn/weather_mini',
    type:'get',
    data:{city:$('#city').val()},
    success:function(data){
        var $_weather=JSON.parse(data);
        console.log($_weather);
        //城市
        $today1=$_weather.data.city;
        $1 = $('<p>').text('城市:'+$today1);
        $hr=$('<hr>')
        //今日日期
        $today2=$_weather.data.forecast[0].date;
        $2 = $('<p>').text('日期:'+$today2);

        //今日最高溫度;
        $today3=$_weather.data.forecast[0].high;
        $3 = $('<p>').text('最高溫度:'+$today3);
        //今日最低溫度
        $today4=$_weather.data.forecast[0].low;
        $4 = $('<p>').text('最低溫度:'+$today4);
        //今日風向
        $today5=$_weather.data.forecast[0].fengxiang;
        $5 = $('<p>').text('風向:'+$today5);
        //今日風力
        $today6=$_weather.data.forecast[0].fengli;
        $6 = $('<p>').text('風力:'+$today6);
        $('#info').append($1).append($hr).append($2).append($3).append($4).append($5).append($6)
    },


    })
    })
</script>
</body>
</html>

2.python後端程序中的數據交互方式,又分爲兩種(後端同步操作和後端異步操作)。

後端同步操作:
即同步交互,核心處理類是用了tornado內置的客戶端對象tornado.httpclient.HTTPClient
後端異步操作:
即異步交互,核心處理類是用了tornado內置的客戶端對象的異步操作對象tornado.httpclient.AsyncHTTPClient
後端同步操作和後端異步操作的特點:
同步操作表示每次只能向目標服務器發送一個請求,待其返回數據後才能進行下一次請求,若請求較多的情況下易發生阻塞。異步操作可同時發送多個請求到目標服務器,較早返回數據的將會被優先處理。
①後端同步操作
py文件
'''
後端同步操作,服務器通過內置的客戶端對象,抓取目標url地址的數據,返回給前端頁面,通過dom操作渲染頁面
'''
# 引入需要的模塊
from tornado.web import Application, RequestHandler
from tornado.ioloop import IOLoop
from tornado.httpserver import HTTPServer
from tornado.httpclient import HTTPClient


# 定義首頁視圖類
class IndexHandler(RequestHandler):
    def get(self):
        self.render('index.html')


# 定義獲取天氣的視圖類
class WeatherHandler(RequestHandler):
    def get(self):
        # 獲取內置的客戶端對象
        client = HTTPClient()
        # 獲取要查詢的城市
        city = self.get_argument('city')
        # 抓取氣象局天氣預報數據,得到響應對象
        response = client.fetch('http://wthrcdn.etouch.cn/weather_mini?city=' + city)
        # 數據被封裝在響應對象的body屬性中
        # 將數據寫入到頁面中
        self.write(response.body)


# 定義程序運行的入口
if __name__ == '__main__':
    import os

    BASE_DIR = os.path.dirname(__file__)
    app = Application([
        (r'/', IndexHandler),
        (r'/weather', WeatherHandler)
    ],
        template_path=os.path.join(BASE_DIR, 'templates'),
        static_path=os.path.join(BASE_DIR, 'static'),
        debug=True)
    server = HTTPServer(app)
    server.listen(8000)
    IOLoop.current().start()
index.html文件
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>後端同步/異步獲取數據</title>
    <script src="/static/jquery/jquery-2.2.4.js"></script>
</head>
<body>
<form>
    當前城市:<input type="text" name="city" id="city">
    <div id="info"></div>
</form>
<script>
    $('#city').blur(function(){
    //獲取到輸入的城市
    $city=$('#city').val()
    //發送ajax請求到後端
    $.ajax({
    url:'/weather',
    type:'get',
    data:{'city':$city},
    success:function(data){
    $data=JSON.parse(data)
    console.log($data)
    //當前城市名稱
    $cty=$('<p>').text('當前城市:'+$data.data.city)
    $hr=$('<hr>')
    //今天的日期
    $date=$('<p>').text('當前日期:'+$data.data.forecast[0].date)
    //最高氣溫
    $high=$('<p>').text('最高氣溫:'+$data.data.forecast[0].high)
    //最低氣溫
    $low=$('<p>').text('最低氣溫:'+$data.data.forecast[0].low)
    //風向
    $fx=$('<p>').text('風向:'+$data.data.forecast[0].fengixang)
    //風力
    $fl=$('<p>').text('風力:'+$data.data.forecast[0].fengli)
    //將天氣信息寫入到頁面中
    //empty()表示每次寫入前先清空以前的數據
    $('#info').empty().append($cty).append($hr).append($date).append($high).append($low).append($fx).append($fl)

    }

    })

    })
</script>
</body>
</html>
②後端異步操作,index.html文件與上面相同,下面是py文件

'''
後端異步操作通過異步操作對象,手動控制數據返回,實現異步獲取數據
'''
# 引入需要的模塊,asynchronous是一個裝飾器,用來告知函數不要自動返回數據
from tornado.web import Application, RequestHandler, asynchronous
from tornado.ioloop import IOLoop
from tornado.httpserver import HTTPServer
# 引入異步操作對象
from tornado.httpclient import AsyncHTTPClient


# 定義首頁視圖處理類
class IndexHandler(RequestHandler):
    def get(self):
        self.render('index.html')


# 定義後端異步獲取天氣信息的視圖處理類
class WeatherHandler(RequestHandler):
    @asynchronous
    def get(self):
        # 獲取前端輸入的城市信息
        city = self.get_argument('city')
        # 獲取異步操作對象
        client = AsyncHTTPClient()
        # 獲取天氣信息
        client.fetch('http://wthrcdn.etouch.cn/weather_mini?city=' + city, callback=self.deal_resonse)

    def deal_resonse(self, response):
        content = response.body
        # 將數據返回到頁面中
        self.write(content)
        # 手動控制數據返回,finish表示可以返回數據了
        self.finish()

# 定義程序運行入口
if __name__=='__main__':
    import os
    BASE_DIR=os.path.dirname(__file__)

    app = Application([
        (r'/',IndexHandler),
        (r'/weather',WeatherHandler)
    ],
    template_path=os.path.join(BASE_DIR,'templates'),
    static_path=os.path.join(BASE_DIR,'static'),
    debug=True)
    server = HTTPServer(app)
    server.listen(8000)

    IOLoop.current().start()

3.linux/unix系統中的壓力測試軟件siege



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章