四個都是 Tornado 的模塊,在本例中都是必須的。它們四個在一般的網(wǎng)站開發(fā)中,都要用到,基本作用分別是:
tornado.httpserver:這個模塊就是用來解決 web 服務器的 http 協(xié)議問題,它提供了不少屬性方法,實現(xiàn)客戶端和服務器端的互通。Tornado 的非阻塞、單線程的特點在這個模塊中體現(xiàn)。
tornado.ioloop:這個也非常重要,能夠實現(xiàn)非阻塞 socket 循環(huán),不能互通一次就結束。
tornado.options:這是命令行解析模塊,也常用到。
tornado.web:這是必不可少的模塊,它提供了一個簡單的 Web 框架與異步功能,從而使其擴展到大量打開的連接,使其成為理想的長輪詢。
設置靜態(tài)路徑
app?=?tornado.web.Application(
handlers=[(r'/',?IndexHandler),?(r'/poem',?MungedPageHandler)],
template_path=os.path.join(os.path.dirname(__file__),"templates"),
static_path=os.path.join(os.path.dirname(__file__),"static"),
debug=True
)
連接mongo
frompymongoimportMongoClient
#?建立于MongoClient?的連接
client?=?MongoClient("localhost",27017)
#?得到數(shù)據(jù)庫,只有插入數(shù)據(jù)時才會創(chuàng)建:
db?=?client.cache
#?或者
#?db?=?client['cache']
print(db)
#?得到一個數(shù)據(jù)集合,只有插入數(shù)據(jù)時才會創(chuàng)建:
collection?=?db.test_collection
#?或者? ? collection?=?db['test-collection']
#?MongoDB中的數(shù)據(jù)使用的是類似Json風格的文檔:
importdatetime
post={
"author":"Mike",
"test":"My?first?blog?post",
"tags":["mongodb","python","pymongo"],
"date":datetime.datetime.utcnow()
}
#?插入一個文檔
posts?=?db.posts
post_id?=?posts.insert_one(post).inserted_id
print(post_id)
代碼
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)
client = MongoClient('127.0.0.1', 27017)
db = client.homework
coll = db.homework1
class IndexHandler(tornado.web.RequestHandler):
? ? def get(self):
? ? ? ? greeting = self.get_argument('greeting', 'Hello')
? ? ? ? self.write(greeting + ', friendly user!')
#主方法
if __name__ == "__main__":
? ? #解析命令行參數(shù)
? ? tornado.options.parse_command_line()
? ? #創(chuàng)建應用程序
? ? app = tornado.web.Application(
? ? ? ? handlers=[(r"/", IndexHandler)],
? ? ? ? template_path=os.path.join(os.path.dirname(__file__),? ? ? ? ? ? ? ? ? ? "templates/basic"),
? ? ? ? static_path=os.path.join(os.path.dirname(__file__),"static"),
? ? )
? ? #創(chuàng)建Http服務器
? ? http_server = tornado.httpserver.HTTPServer(app)
? ? #設置監(jiān)聽端口
? ? http_server.listen(options.port)
? ? #啟動服務器循環(huán)
? ? tornado.ioloop.IOLoop.instance().start()
包裝Application
class Application(tornado.web.Application):
? ? def __init__(self):
? ? ? ? handlers = [
? ? ? ? ? ? (r"/", MainHandler),
? ? ? ? ]
? ? ? ? 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)
if __name__ == "__main__":
? ? tornado.options.parse_command_line()
? ? http_server = tornado.httpserver.HTTPServer(Application())
? ? http_server.listen(options.port)
? ? tornado.ioloop.IOLoop.instance().start()