例子
#-*- coding: utf-8 -*-
import tornado.httpserver
import tornado.ioloop
import tornado.web
import os
import tornado.autoreload
from tornado.options import define, options
from pycket.session import SessionMixin
import subprocess
import torndb
import MySQLdb
#1.2导入
import time
define('port', default=8000, help='Run on the given port', type=int)
define('debug', default=False, help='Set debug mode', type=bool)
#1 定义选项
define('mysql_host', default='127.0.0.1', help='mysql host IP')
define('mysql_user', default='root', help='db user name')
define('mysql_password', default='kylie', help='db password')
define('mysql_database', default='tornadoblog', help='db name')
class HomeHandler(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
#从数据库读取数据
zips = self.application.db.query(
'select title, content, updated, author_id from entries'
)
entries = []
for azip in zips:
entry = dict(azip)
entries.append(entry)
self.render('main.html', entries = entries)
#1.1增加一个基类
class BasicHandler(tornado.web.RequestHandler):
# 限制登陆的用户 必须覆盖下面这个函数
def get_current_user(self):
user = self.get_secure_cookie('user')
return user
#1 增加PostHandler
class PostHandler(BasicHandler):
def get(self, *args, **kwargs):
self.render('post.html')
#限制登陆的用户才可以访问
@tornado.web.authenticated
def post(self, *args, **kwargs):
user = self.get_secure_cookie('user', None)
user = user.decode('utf8')
if user is None or not self.application.db.get(
'select id from authors where name="%s"' % user
):
self.write('please login')
else:
title = self.get_argument('title')
content = self.get_argument('content')
if title and content:
self.application.db.execute(
'insert into entries (author_id, title, content, updated) values ("%s","%s","%s","%s")'%(user, title, content, time.asctime())
)
self.write('post successfully')
else:
self.write('field empty')
class RegisterHandler(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
self.render('register.html')
def post(self, *args, **kwargs):
user = self.get_argument('username')
password = self.get_argument('password')
email = self.get_argument('email')
password_c = self.get_argument('password_confirm')
print('select id from authors where name="%s"' % user)
if (not password) or (not password_c):
self.write('password is empty!')
elif not email:
self.write('email is empty')
elif not user:
self.write('name is empty')
elif password_c != password:
self.write('password is not same!')
elif self.application.db.get('select id from authors where name="%s"' % user):
self.write('user already exists')
else:
cmd = 'insert into authors (name, email, password) values("%s", "%s", "%s")' % (user, email, password)
self.application.db.execute(cmd)
self.write('Registered successfully!')
class LoginHandler(tornado.web.RequestHandler, SessionMixin):
def get(self, *args, **kwargs):
self.render('login.html')
def post(self, *args, **kwargs):
user = self.get_argument('user', None)
password = self.get_argument('password', None)
if user and password and self.application.db.get(
'select id from authors where name="%s" and password="%s"' % (user, password)):
self.set_secure_cookie('user', self.get_argument('user', None))
self.session.set('user', user)
txt = str(self.session.get('user'))
self.write('Successully set cookie!, user_session_test value: %s' % txt)
elif self.application.db.get('select id from authors where name="%s"' % user):
self.write('wrong password')
else:
self.write('please register')
class OtherHtmlHandler(tornado.web.RequestHandler):
def get_current_user(self):
user = self.get_secure_cookie('user')
print (user)
return user
@tornado.web.authenticated
def get(self, page):
pagename = page + '.html'
path = os.path.join(self.settings['static_path'], pagename)
self.render(pagename)
class CustomApp(tornado.web.Application):
def __init__(self, debug = False):
settings = {
'template_path':os.path.join(os.path.dirname(__file__), 'moban_clean/templates'),
'static_path':os.path.join(os.path.dirname(__file__), 'moban_clean'),
'blog_title': "tornado blog",
'login_url': '/login.html',
'cookie_secret':"2379874hsdhf0234990sdhsaiuofyasop977djdj",
'xsrf_cookies':True,
'debug':debug,
'pycket':{
'engine':'redis',
'storage':{
'host':'localhost',
'port': 6379,
'db_sessions':10,
'db_notifications':11,
'max_connections':2**31,
},
'cookies':{
'expires_days':2,
'expires':None, #秒
},
}
}
handles = [
(r'/(main.html)*', HomeHandler),
(r'/login.html', LoginHandler),
(r'/register', RegisterHandler),
#1增加post url
(r'/post', PostHandler),
(r'/(.+?)\.html', OtherHtmlHandler),
(r'/(.+?\..+)', tornado.web.StaticFileHandler, dict(path=settings['static_path'])),
]
super(CustomApp, self).__init__(handles, **settings)
self.db = torndb.Connection(host=options.mysql_host,
database=options.mysql_database,
user=options.mysql_user,
password=options.mysql_password,
)
self.create_tables()
def create_tables(self):
try:
self.db.get('select count(*) from entries')
except MySQLdb.ProgrammingError:
subprocess.check_call([
'mysql',
'--host=' + options.mysql_host,
'--database=' + options.mysql_database,
'--user=' + options.mysql_user,
'--password=' + options.mysql_password
], stdin=open(os.path.join(os.path.dirname(__file__), 'schema.sql')))
if __name__ == '__main__':
tornado.options.parse_command_line()
app = CustomApp(debug=options.debug)
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
#tornado.autoreload.start()
tornado.ioloop.IOLoop.instance().start()
main.html
{% extends "base.html" %}
{% block body %}
{% for entry in entries%}
<h2>{{escape(entry['title'])}}</h2>
<h3>{{escape(entry['content'])}}</h3>
<h3>{{escape(entry['author_id'])}},{{escape(entry['updated'])}}</h3>
<hr>
{% end %}
{% end %}