使用圖靈機器人api開發我的智能機器人

圖靈智能機器人地址 http://www.tuling123.com/openapi/cloud/proexp.jsphtml

一次偶然在某論壇發現這個玩意兒,挺好玩的,還竟然有開放API,就跟微信公共帳號似的,所以本身就想着搗鼓一個本身的智能及其人來玩玩。。前端

開始構想。想用python來開發,由於調用外部API比較耗時。爲了縮短請求處理的響應時間,想把API調用的請求作成服務器的異步請求處理模式,python

恰好python有Tornado這個很是強大的web框架,而且支持服務器端的異步請求處理,就決定使用它了。。。。web

 

代碼很簡單,除了開發一個tornado項目必備固定的那幾個部分外,請求處理類只須要一個。其他的則是js部分。。。json

 

python請求處理類代碼:api

handlers.py服務器

import tornado.web
import os
import tornado.httpclient
import json
config = {}
execfile(os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.py"), config)

class AnwserHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self):
        self.info = self.get_argument("info","")
        url = config['URL']+"?key="+config['KEY']+"&info="+self.info
        asyncclient = tornado.httpclient.AsyncHTTPClient()
        asyncclient.fetch(url,callback=self.on_response)
    def on_response(self,response):
        reback = json.loads(response.body)
        if not self.info:
            self.render("index.html",section = reback['text'])
        else:
            print response.body
            self.write(response.body)
            self.finish()微信

程序主模塊:app

main.py框架

import tornado.httpserver
import tornado.ioloop
import tornado.web
import os
import urls
from tornado.options import define,options

define("port",default=8000,help="run on the given port",type=int)
class Application(tornado.web.Application):
    def __init__(self):
        handlers = urls.handler
        settings = dict(template_path = os.path.join(os.path.dirname(__file__),"templates"),
                   static_path = os.path.join(os.path.dirname(__file__),"static"))
        tornado.web.Application.__init__(self, handlers, **settings)
        
if __name__ == "__main__":
    tornado.options.parse_command_line()
    application  = Application()
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

項目效果圖:

不是專門寫前端的,界面湊合着看吧

相關文章
相關標籤/搜索