1. 程式人生 > >tornado學習(一)專案搭建

tornado學習(一)專案搭建

安裝:pip install tornado

結果:D:\tornado程式碼\project>pip install tornado

Requirement already satisfied: tornado in c:\python36\lib\site-packages (5.0.2)

新版本可以pip安裝

專案結構搭建:

config.py:

import os

BASE_DIRS = os.path.dirname(__file__)


#引數
options = {
    'port':8888,
}

#配置
setting = {
    'static_path':os.path.join(BASE_DIRS,'static'),
    'template_path':os.path.join(BASE_DIRS,'templates'),
    'debug':True,
    # 'autoreload':True
}


application.py:

import tornado.web
import views
import config


class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r"/", views.IndexHandler),
            (r"/home", views.HomeHandler),
            (r"/pzl", views.PzlHandler,{'word1':'good','word2':'nice'}),

            (r"/json1", views.JsonHandler),
            (r"/json2", views.Json2Handler),


            (r"/iserror", views.ErrorHandler),
            tornado.web.url(r'/p',views.PHandler,{'word3':'good','word4':'nice'},name='p'),
            #uri
            (r'/liuyifei/(?P<p1>\w+)/(?P<p3>\w+)/(?P<p2>\w+)/',views.LiuyifeiHandler),
            #get
            (r'/zhangmanyu',views.ZhangmanyuHandler),
            #post
            (r'/postfile', views.PostFileHandler),
            #request物件
            (r'/zhuyin', views.ZhuyinHandler),
            #上傳檔案
            (r'/upfile', views.UpFileHandler),


        ]
        super(Application,self).__init__(handlers,**config.setting)

server.py:

import tornado.ioloop
import tornado.httpserver
import config

from application import Application




if __name__ == "__main__":
    print('啟動...')
    app = Application()
    httpServer = tornado.httpserver.HTTPServer(app)
    # httpServer.listen(8888)
    #繫結埠
    httpServer.bind(config.options['port'])
    #開啟5個子程序(預設1,若為None或者小於0,開啟對應硬體的CPU核心數個子程序)
    httpServer.start(1)
    tornado.ioloop.IOLoop.current().start()




views/__init__.py

from .index import IndexHandler,PzlHandler,JsonHandler,Json2Handler,ErrorHandler,PHandler
from .home import HomeHandler,LiuyifeiHandler,ZhangmanyuHandler,PostFileHandler,ZhuyinHandler,UpFileHandler

views下寫檢視類

例如:

from tornado.web import RequestHandler


class IndexHandler(RequestHandler):
    def get(self, *args, **kwargs):
        url=self.reverse_url('p')
        print(url)
        self.write("<a href='%s'>GO another page</a>"%(url))

upfile檔案下放上傳的檔案,templates下放模板,static下放靜態檔案/css,/js,/img

這就是一個tornado的一個專案的結構