tornado的用户指南的使用总结和一个 tornado程序示例

 

 tornado程序示例


# coding:utf-8
import tornado.web
import tornado.ioloop
import tornado.httpserver
import tornado.options
from tornado.options import options, define
from tornado.web import url, RequestHandler
import os


database_config=dict(    engine=None,
    # engine_url='postgresql+psycopg2://mhq:1qaz2wsx@localhost:5432/blog',
    # 如果是使用mysql+mysqldb,在确认所有的库表列都是uft8编码后,依然有字符编码报错,
    # 可以尝试在该url末尾加上queryString charset=utf8
    engine_url='sqlite:root/ceph-manager.db',
    engine_setting=dict(
        echo=True,
        echo_pool=False,
        pool_recycle=25200,
        connect_args={'check_same_thread': False},

    ))
redis_session_config=dict(
    db_no=0,
    host="127.0.0.1",
    port=6379,
    password=None,
    max_connections=10,
    session_key_name='session_key_name',
    session_expires_days=7,
)
# 站点相关配置以及tornado的相关参数
config = dict(
    debug=False,
    database=database_config,
    redis_session=redis_session_config,
    application=None,  # 项目启动后会在这里注册整个server,以便在需要的地方调用,勿修改
)
settings = dict(
    template_path=os.path.join(os.path.dirname(__file__), "template"),
    static_path=os.path.join(os.path.dirname(__file__), "static"),
    compress_response=config['compress_response'],
    xsrf_cookies=config['xsrf_cookies'],
    cookie_secret=config['cookie_secret'],
    login_url=config['login_url'],
    debug=config['debug'],
)

from sqlalchemy.orm import contains_eager, deferred
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, DateTime, Integer, String, Boolean, Text, ForeignKey, BigInteger, DATE
from sqlalchemy.orm import relationship, backref
DbBase = declarative_base()
class Plugin(DbBase):
    __tablename__ = 'plugins'
    id = Column(Integer, primary_key=True)
    title = Column(String(64), unique=True)
    note = Column(Text, default='')
    content = Column(Text, default='')
    order = Column(Integer, index=True, default=0)
    disabled = Column(Boolean, default=False)

    def __repr__(self):
        return '<Plugin %r>' % self.title
# sqlalchemy连接池配置以及生成链接池工厂实例
def db_poll_init():
    from sqlalchemy import create_engine
    from sqlalchemy.orm import sessionmaker
    engine_config = config['database']['engine_url']
    engine = create_engine(engine_config, **config['database']["engine_setting"])
    config['database']['engine'] = engine
    db_poll = sessionmaker(bind=engine)
    return db_poll

define("port", default=8000, type=int, help="run server on the given port.")

class IndexHandler(RequestHandler):
    def get(self):
        python_url = self.reverse_url("python_url")
        self.write('<a href="%s">itcast</a>' % python_url)

'''
调用顺序
set_default_headers()
initialize()
prepare()
HTTP方法
set_default_headers()
write_error()
on_finish()
'''
class ItcastHandler(RequestHandler):
    def initialize(self, subject):
        self.subject = subject

    def get(self, name):
        self.write(self.subject)

    def post(self):
        self.get_argument("author_name", default="liudehua", strip=True)
        obj = Plugin(3,"classname")
        session.add(obj)
        session.commit()
        plugins = session.query(Plugin).order_by(Plugin.order.asc()).all()
        self.render("class.html", base_url=self.reverse_url('index'),pager="A4")

    def sort_up(db_session, plugin_id):
        plugin = db_session.query(Plugin).get(plugin_id)
        if plugin:
            plugin_up = db_session.query(Plugin).\
                filter(Plugin.order < plugin.order).order_by(Plugin.order.desc()).first()
            if plugin_up:
                order_tmp = plugin.order
                plugin.order = plugin_up.order
                plugin_up.order = order_tmp
                db_session.commit()
                return True
        return False

if __name__ == "__main__":
    tornado.options.parse_command_line()
    db = db_poll_init()
    session = db()
    app = tornado.web.Application([
            (r"/", IndexHandler),
            (r"/(cpp|c++)", ItcastHandler, {"subject":"c++"}),
            url(r"/python", ItcastHandler, {"subject":"python"}, name="python_url")
        ],**settings)
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.current().start()
from tornado.web import url, RequestHandler
RequestHandler.set_secure_cookie(self.session_manager.session_key_name, self.session_id,
                                       expires_days=self.session_manager.session_expires_days)设置cookie
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值