Skip to content

Commit

Permalink
recode blog
Browse files Browse the repository at this point in the history
  • Loading branch information
MartianZ committed Nov 28, 2013
1 parent acb04e7 commit e825f61
Show file tree
Hide file tree
Showing 7 changed files with 271 additions and 184 deletions.
224 changes: 40 additions & 184 deletions blog.py
@@ -1,187 +1,43 @@
#/usr/bin/env python
# -*- encoding: utf8 -*-
import tornado.ioloop
import tornado.web
import string, os, sys
import markdown
import codecs
import PyRSS2Gen
import datetime
from Crypto.Cipher import AES
import hashlib
import base64

site_config = {
"title" : "MartianZ!",
"url" : """http://blog.martianz.cn""",
"post_dir": os.getcwd() + os.sep + 'posts',
}

settings = {
"static_path": os.path.join(os.path.dirname(__file__), "static")
}

def SingleFileHandler(file_path):
f = codecs.open(file_path, mode='r', encoding='utf8')
lines = []
try:
lines = f.readlines()
except:
pass
f.close()

ret = {}
title = ''
date = ''
encrypt = 0
index = 1

for line in lines[1:]:
index += 1
if line.find('title: ') == 0:
title = line.replace('title: "','')[0:-2]
if line.find('date: ') == 0:
date = line.replace('date: ','')[0:-1]
if line.find('encrypt: 1') == 0:
encrypt = 1
if line.find('---') == 0:
break

content = u'';
for line in lines[index:]:
content += line

if title:
ret['title'] = title
ret['date'] = date
if encrypt:
ret['content'] = content
else:
ret['content'] = markdown.markdown(content)
ret['e'] = encrypt
ret['name'] = file_path.split(os.sep)[-1].split('.')[0]
return ret

class MainHandler(tornado.web.RequestHandler):
def get(self):
articles = []
post_dir = site_config["post_dir"]
file_list = []
files = os.listdir(post_dir)

p = int(self.get_argument('p','0'))

for f in files:
file_list.append(post_dir + os.sep + f)
file_list.sort(reverse=True)
for single_file in file_list[p:p+3]:
article = SingleFileHandler(single_file)
if article:
if article['e']: article['content'] = "文章已加密,请点击标题进入浏览 =v="
articles.append(article)

if p > 2:
prev = True
else:
prev = False

if p + 4 <= len(file_list):
pnext = True
else:
pnext = False

self.render("template/index.html", title=site_config['title'], url=site_config["url"], articles = articles, prev=prev, pnext=pnext, prevnum=p-3, nextnum=p+3)

class ArticleHandler(tornado.web.RequestHandler):
def auth(self):
self.set_status(401)
self.set_header('WWW-Authenticate', 'Basic realm=Please enter your username and password to decrypted this article')
self._transforms = []
self.finish()

def get(self, article_id):
post_path = site_config["post_dir"] + os.sep + article_id.replace('.','') + '.markdown'
article = SingleFileHandler(post_path)
if article['e']:
auth_header = self.request.headers.get('Authorization')
if auth_header is None or not auth_header.startswith('Basic '):
self.auth()
else:
try:
auth_decoded = base64.decodestring(auth_header[6:])
username, password = auth_decoded.split(':', 2)
if username == "201314":
key = hashlib.sha256(password).digest()
cipher = AES.new(key, AES.MODE_ECB)
article['content'] = markdown.markdown(unicode(cipher.decrypt(base64.decodestring(article['content'])),"utf8"))
self.render("template/article.html", title=site_config['title'], url=site_config["url"], article = article)
else:
self.auth()
except:
self.auth()
else:
self.render("template/article.html", title=site_config['title'], url=site_config["url"], article = article)


class NotFoundHandler(tornado.web.RequestHandler):
def prepare(self):
self.set_status(404)
self.render("template/404.html")

class RSSHandler(tornado.web.RequestHandler):
def get(self):
f = open("rss.xml", "r")
self.write(f.read())
f.close()

def RSSMaker():
articles = []
post_dir = site_config["post_dir"]
file_list = []
files = os.listdir(post_dir)

for f in files:
file_list.append(post_dir + os.sep + f)
file_list.sort(reverse=True)

for single_file in file_list:
article = SingleFileHandler(single_file)
if article:
if article['e'] == 0:
articles.append(article)

rss_items = []
for article in articles:
link = site_config["url"]+"/article/"+article["name"]
rss_item = PyRSS2Gen.RSSItem(
title = article["title"],
link = link,
description = article["content"],
guid = PyRSS2Gen.Guid(link),
pubDate = datetime.datetime( int(article["date"][0:4]),
int(article["date"][5:7]),
int(article["date"][8:10]),
int(article["date"][11:13]),
int(article["date"][14:16])))
rss_items.append(rss_item)

rss = PyRSS2Gen.RSS2(
title = site_config["title"],
link = site_config["url"],
description = "",
lastBuildDate = datetime.datetime.utcnow(),
items = rss_items)

rss.write_xml(open("rss.xml", "w"))

application = tornado.web.Application([
(r"/", MainHandler),
(r"/article/(.*)", ArticleHandler),
(r"/.*\.xml",RSSHandler),
(r"/.*", NotFoundHandler),
], **settings)
# author: MartianZ <fzyadmin@gmail.com>
import os
import tornado
import logging
from time import time
from tornado import web
from tornado.ioloop import IOLoop, PeriodicCallback
from tornado.options import define, options
from tornado.httpserver import HTTPServer

define("debug", default=True, help="debug mode")
define("bind_ip", default="0.0.0.0", help="the bind ip")
define("port", default=8888, help="the port tornado listen to")
define("site_name", default="MartianZ!", help="blog site name")
define("site_url", default="http://blog.martianz.cn", help="blog site url")
define("posts_dir", default=os.getcwd() + os.sep + "posts", help="posts_dir")

class Application(web.Application):
def __init__(self):
from handlers import handlers
settings = dict(
debug=options.debug,

template_path=os.path.join(os.path.dirname(__file__), "template"),
static_path=os.path.join(os.path.dirname(__file__), "static"),

)
super(Application, self).__init__(handlers, **settings)

logging.info("load finished! listening on %s:%s" % (options.bind_ip, options.port))

def main():
tornado.options.parse_command_line()
http_server = HTTPServer(Application(), xheaders=True)
http_server.bind(options.port, options.bind_ip)
http_server.start()

IOLoop.instance().start()

if __name__ == "__main__":
application.listen(8888)
RSSMaker()
print "MartianZ Burogu Sutato!"
tornado.ioloop.IOLoop.instance().start()
main()
10 changes: 10 additions & 0 deletions handlers/__init__.py
@@ -0,0 +1,10 @@
# -*- encoding: utf8 -*-
# author: MartianZ <fzyadmin@gmail.com>

handlers = []

modules = ["index", "article", "rss", "error"]

for module in modules:
module = __import__("handlers."+module, fromlist=["handlers"])
handlers.extend(module.handlers)
44 changes: 44 additions & 0 deletions handlers/article.py
@@ -0,0 +1,44 @@
#/usr/bin/env python
# -*- encoding: utf8 -*-
# author: MartianZ <fzyadmin@gmail.com>

from .base import BaseHandler
import os
import base64
import hashlib
from Crypto.Cipher import AES
from markdown import markdown

class ArticleHandler(BaseHandler):
def auth(self):
self.set_status(401)
self.set_header('WWW-Authenticate', 'Basic realm=Please enter your username and password to decrypt this article')
self._transforms = []
self.finish()

def get(self, article_id):
post_path = self.posts_dir + os.sep + article_id.replace('.','') + '.markdown'
article = self.markdown_parser(post_path)
if article['e']:
auth_header = self.request.headers.get('Authorization')
if auth_header is None or not auth_header.startswith('Basic '):
self.auth()
else:
try:
auth_decoded = base64.decodestring(auth_header[6:])
username, password = auth_decoded.split(':', 2)
if username == "201314":
key = hashlib.sha256(password).digest()
cipher = AES.new(key, AES.MODE_ECB)
article['content'] = markdown(unicode(cipher.decrypt(base64.decodestring(article['content'])),"utf8"))
self.render("article.html", title=self.site_name, url=self.site_url, article = article)
else:
self.auth()
except:
self.auth()
else:
self.render("article.html", title=self.site_name, url=self.site_url, article = article)

handlers = [
(r"/article/(.*)", ArticleHandler),
]
60 changes: 60 additions & 0 deletions handlers/base.py
@@ -0,0 +1,60 @@
# -*- encoding: utf8 -*-
# author: MartianZ <fzyadmin@gmail.com>

from tornado.web import RequestHandler
from tornado.options import options
import codecs
from markdown import markdown
import os

class BaseHandler(RequestHandler):
@property
def site_name(self):
return options.site_name;
@property
def site_url(self):
return options.site_url;
@property
def posts_dir(self):
return options.posts_dir;

def markdown_parser(self, file_path):
f = codecs.open(file_path, mode='r', encoding='utf8')
lines = []
try:
lines = f.readlines()
except:
pass
f.close()

ret = {}
title = ''
date = ''
encrypt = 0
index = 1

for line in lines[1:]:
index += 1
if line.find('title: ') == 0:
title = line.replace('title: "','')[0:-2]
if line.find('date: ') == 0:
date = line.replace('date: ','')[0:-1]
if line.find('encrypt: 1') == 0:
encrypt = 1
if line.find('---') == 0:
break

content = u'';
for line in lines[index:]:
content += line

if title:
ret['title'] = title
ret['date'] = date
if encrypt:
ret['content'] = content
else:
ret['content'] = markdown(content)
ret['e'] = encrypt
ret['name'] = file_path.split(os.sep)[-1].split('.')[0]
return ret
14 changes: 14 additions & 0 deletions handlers/error.py
@@ -0,0 +1,14 @@
#/usr/bin/env python
# -*- encoding: utf8 -*-
# author: MartianZ <fzyadmin@gmail.com>

from .base import BaseHandler

class NotFoundHandler(BaseHandler):
def prepare(self):
self.set_status(404)
self.render("404.html")

handlers = [
(r"/.*", NotFoundHandler),
]

0 comments on commit e825f61

Please sign in to comment.