#
# Basic Asynchronous Call
#
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.httpclient
import os.path
import urllib
import json
import datetime
import time
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 = [
(r"/", IndexHandler),
]
settings =
dict(
template_path=os.path.join(os.path.dirname(__file__),
"templates"),
#static_path=os.path.join(os.path.dirname(__file__),
"static"),
debug=True,
)
tornado.web.Application.__init__(self, handlers,
**settings)
class IndexHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
city =
self.get_argument('city', '400040')
print("city=[{}]".format(city))
print("len(city)={}".format(len(city)))
url =
"http://weather.livedoor.com/forecast/webservice/json/v1"
if (len(city)
!= 0): url = url + "?city=" + city
print("url={}".format(url))
client = tornado.httpclient.AsyncHTTPClient()
client.fetch(url, callback=self.on_response)
def on_response(self, response):
print("response={}".format(response))
data =
json.loads(response.body)
print("data={}".format(data))
print(json.dumps(data, indent=2))
print()
print()
print(data['location'])
print(data['location']['city'])
city=data['location']['city']
print(data['location']['prefecture'])
prefecture=data['location']['prefecture']
print(data['location']['area'])
area=data['location']['area']
print(data['publicTime'])
publicTime=data['publicTime']
dateTime=publicTime.split('T')
print("dateTime={}".format(dateTime))
date=dateTime[0]
time=dateTime[1]
time=time.split('+')
print("time={}".format(time))
print(data['description']['text'])
text=data['description']['text']
self.render(
"index.html",
area = area,
prefecture = prefecture,
city = city,
date = date,
time = time[0],
text = text,
)
if __name__ == "__main__":
tornado.options.parse_command_line()
app = Application()
http_server =
tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
tornado.ioloop.IOLoop.current().start() |