Skip to content

Commit

Permalink
Merge pull request #9 from the5fire/support-markdown
Browse files Browse the repository at this point in the history
主要增加对markdown的支持,修复英文标题非必填导致的bug(Issues #8)
  • Loading branch information
the5fire authored Jul 2, 2016
2 parents 3c2e852 + fba816d commit 16fb9f4
Show file tree
Hide file tree
Showing 16 changed files with 176 additions and 129 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ atlassian-ide-plugin.xml
.env
*.log
*.sqlite3
.ropeproject/
7 changes: 7 additions & 0 deletions readme.rst
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ the5fire的技术博客源码
-------------------------------
后台修改为xadmin(0.5v)

2016-07-02
-------------------------------
* Post增加is_md字段,增加对markdown格式的支持
* 拆分settings.py文件为develop.py,product.py让配置更清晰
* 通过DJANGOSELFBLOG_PROFILE来加载对应的配置develop/product
* 修复创建Post时不填英文标题导致的文章无法访问的bug


哪些技术
------------------------------
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ python-memcached==1.53
django-debug-toolbar==0.10.2
django-xadmin==0.5.0
django-ipware
markdown
8 changes: 6 additions & 2 deletions selfblog/blog/adminx.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#coding:utf-8
# coding:utf-8
import markdown
import xadmin
from django.core import urlresolvers

Expand Down Expand Up @@ -35,7 +36,10 @@ def save_models(self):
obj.author = self.request.user
if not obj.summary:
obj.summary = obj.content
if not obj.is_old:

if obj.is_md:
obj.content_html = markdown.markdown(obj.content, extensions=['codehilite'])
elif not obj.is_old:
obj.content_html = restructuredtext(obj.content)
else:
obj.content_html = obj.content.replace('\r\n', '<br/>')
Expand Down
17 changes: 14 additions & 3 deletions selfblog/blog/models.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
# coding:utf-8
from datetime import datetime

from django.db import models
from django.contrib.auth.models import User
from django.db import models
from django.db.models import signals
from django.dispatch import receiver
from django.utils.functional import cached_property

from selfblog import settings
from django.conf import settings
from utils.cache import cache_decorator

STATUS = {
Expand Down Expand Up @@ -55,14 +57,15 @@ class Post(models.Model):
is_top = models.BooleanField(default=False, verbose_name=u'置顶')

summary = models.TextField(verbose_name=u'摘要')
content = models.TextField(verbose_name=u'文章正文rst格式')
content = models.TextField(verbose_name=u'文章正文rst/md格式')

content_html = models.TextField(verbose_name=u'文章正文html')
view_times = models.IntegerField(default=1)

tags = models.CharField(max_length=100, null=True, blank=True, verbose_name=u'标签', help_text=u'用英文逗号分割')
status = models.IntegerField(default=0, choices=STATUS.items(), verbose_name=u'状态')

is_md = models.BooleanField(default=False, verbose_name=u'是否为Markdown格式')
is_old = models.BooleanField(default=False, verbose_name=u'是否为旧数据')
pub_time = models.DateTimeField(default=datetime.now, verbose_name=u'发布时间')

Expand Down Expand Up @@ -122,6 +125,14 @@ class Meta:
verbose_name_plural = verbose_name = u"文章"


@receiver(signals.post_save, sender=Post)
def check_or_update_post_alias(sender, instance=None, **kwargs):
# 如果alias未设置则使用id
if not instance.alias:
instance.alias = instance.id
instance.save()


class Page(models.Model):
author = models.ForeignKey(User, verbose_name=u'作者')
title = models.CharField(max_length=100, verbose_name=u'标题')
Expand Down
1 change: 1 addition & 0 deletions selfblog/blog/templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -100,5 +100,6 @@ <h1><a href="/">the5fire的技术博客</a></h1>


{% include "includes/footer.html" %}
{% block extend_js %}{% endblock %}
</body>
</html>
18 changes: 13 additions & 5 deletions selfblog/blog/templates/detail.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,11 @@
{% block keywords %}{{ post.tags }}{% endblock %}

{% block extend_style %}
{% if post.is_md %}
<link href="/static/blog/css/codehilite.css" rel="stylesheet" type="text/css" media="screen" />
{% else %}
<link href="/static/blog/css/code.css" rel="stylesheet" type="text/css" media="screen" />
<script src="/static/blog/js/jquery-1.8.1.min.js"></script>
<script src="/static/bootstrap/js/bootstrap-dropdown.js"></script>
<script>
$('.dropdown-toggle').dropdown()
</script>
{% endif %}
{% endblock %}

{% block main %}
Expand Down Expand Up @@ -99,3 +98,12 @@ <h2 class="under_line">
{% include "pingback.html" %}
</div>
{% endblock %}

{% block extend_js %}
<script src="/static/blog/js/jquery-1.8.1.min.js"></script>
<script src="/static/bootstrap/js/bootstrap-dropdown.js"></script>
<script>
$('.dropdown-toggle').dropdown()
</script>
{% endblock %}

7 changes: 4 additions & 3 deletions selfblog/blog/templates/includes/footer.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@
<div class="span4">
</div>
<div class="span4">
<p>版权所有 © 2010-2013 the5fire.com </p>
<p>版权所有 © 2010-2016 }} <a href="http://www.the5fire.com">the5fire.com</a></p>
<p>CC BY-NC-SA 3.0</p>
<p>
Powered by <a href="http://www.djangoproject.com" target="_blank">Django</a>.
Host on <a href="http://www.webfaction.com?affiliate=the5fire" target="_blank">WebFaction</a>.
Powered by <a href="http://www.djangoproject.com" target="_blank">Django</a>.
</p>
<p>
Host on <a href="https://m.do.co/c/4b3f2684a507" target="_blank">DigitalOcean $5/月</a>.
<p>
当前{{ online_num }}人在线,表示毫无压力
{% if online_num > 50 %}
<strong>囧~</strong>
Expand Down
12 changes: 6 additions & 6 deletions selfblog/blog/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from django.shortcuts import render
from ipware.ip import get_real_ip

from selfblog.settings import PAGE_NUM, RECENTLY_NUM, HOT_NUM, FIF_MIN
from django.conf import settings
from .models import Post, Category, Page, Widget
from utils.cache import LRUCacheDict, cache

Expand All @@ -26,8 +26,8 @@ def get_context_data(self, *args, **kwargs):
try:
context['categories'] = Category.available_list()
context['widgets'] = Widget.available_list()
context['recently_posts'] = Post.get_recently_posts(RECENTLY_NUM)
context['hot_posts'] = Post.get_hots_posts(HOT_NUM)
context['recently_posts'] = Post.get_recently_posts(settings.RECENTLY_NUM)
context['hot_posts'] = Post.get_hots_posts(settings.HOT_NUM)
context['pages'] = Page.objects.filter(status=0)
context['online_num'] = len(cache.get('online_ips', []))
except Exception as e:
Expand All @@ -52,7 +52,7 @@ def get(self, request, *args, **kwargs):
return super(IndexView, self).get(request, *args, **kwargs)

def get_context_data(self, **kwargs):
paginator = Paginator(self.object_list, PAGE_NUM)
paginator = Paginator(self.object_list, settings.PAGE_NUM)
kwargs['posts'] = paginator.page(self.cur_page)
kwargs['query'] = self.query
return super(IndexView, self).get_context_data(**kwargs)
Expand Down Expand Up @@ -146,12 +146,12 @@ def set_lru_read(self, ip, post):
# 保存别人正在读
lru_views = cache.get('lru_views')
if not lru_views:
lru_views = LRUCacheDict(max_size=10, expiration=FIF_MIN)
lru_views = LRUCacheDict(max_size=10, expiration=settings.FIF_MIN)

if post not in lru_views.values():
lru_views[ip] = post

cache.set('lru_views', lru_views, FIF_MIN)
cache.set('lru_views', lru_views, settings.FIF_MIN)

def get_context_data(self, **kwargs):
context = super(PostDetailView, self).get_context_data(**kwargs)
Expand Down
3 changes: 2 additions & 1 deletion selfblog/manage.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import sys

if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "selfblog.settings")
PROFILE = os.environ.get('DJANGOSELFBLOG_PROFILE', 'develop')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "selfblog.settings.%s" % PROFILE)
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
Empty file.
100 changes: 14 additions & 86 deletions selfblog/selfblog/settings.py → selfblog/selfblog/settings/base.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
#coding:utf-8
# Django settings for selfblog project.
# coding:utf-8
import os
from os import path
from platform import platform
if 'centos' in platform():
DEBUG = False
else:
DEBUG = True
TEMPLATE_DEBUG = DEBUG

ROOT_PATH = path.abspath(path.join(path.dirname('settings.py'), path.pardir))

Expand All @@ -16,67 +10,15 @@
ALLOWED_HOSTS = ['localhost', '.the5fire.com']

MANAGERS = ADMINS

if DEBUG:
DOMAIN = 'http://localhost:8000'
DB_NAME = 'selfblog.sqlite3'
DB_USER = 'root'
DB_PWD = 'root'
else:
DOMAIN = 'http://www.the5fire.com'
DB_NAME = 'mydb'
DB_USER = 'the5fire'
DB_PWD = 'the5fire'

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': DB_NAME, # Or path to database file if using sqlite3.
'USER': DB_USER, # Not used with sqlite3.
'PASSWORD': DB_PWD, # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Asia/Shanghai'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'zh-cn'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True

MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
#STATIC_ROOT = ''

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
# STATIC_ROOT = ''
STATIC_URL = '/static/'

# Additional locations of static files
Expand All @@ -89,7 +31,7 @@
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#'django.contrib.staticfiles.finders.DefaultStorageFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
Expand All @@ -99,7 +41,7 @@
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
#'django.template.loaders.eggs.Loader',
# 'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
Expand Down Expand Up @@ -145,22 +87,11 @@
'weixin',
)

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
if DEBUG:
INSTALLED_APPS = INSTALLED_APPS + ('debug_toolbar', )
MIDDLEWARE_CLASSES = MIDDLEWARE_CLASSES + ('debug_toolbar.middleware.DebugToolbarMiddleware', )
LOG_FILE = '/tmp/blog.log'
else:
LOG_FILE = '/home/the5fire/virtualenvs/bloga/logs/all.log'

LOG_PATH = os.path.join(ROOT_PATH, '..', '..')
LOGGING = {
'version': 1,
'disable_existing_loggers': True,

'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
Expand All @@ -176,20 +107,18 @@
},

'handlers': {
'null': {
'level': 'DEBUG',
'class': 'django.utils.log.NullHandler',
},
'console': {
'level': 'INFO',
'class': 'logging.StreamHandler',
'formatter': 'verbose'
},
'file': {
'file_info': {
'level': 'INFO',
'class': 'logging.FileHandler',
'class': 'logging.handlers.RotatingFileHandler',
'formatter': 'verbose',
'filename': LOG_FILE,
'filename': os.path.join(LOG_PATH, 'info.log'),
'maxBytes': 1024 * 1024 * 100,
'backupCount': 10,
'mode': 'a',
},
'mail_admins': {
Expand All @@ -200,12 +129,12 @@
},
'loggers': {
'': {
'handlers': ['file', 'console'],
'handlers': ['file_info', 'console'],
'level': 'INFO',
'propagate': True,
},
'django': {
'handlers': ['file', 'console'],
'handlers': ['file_info', 'console'],
'level': 'DEBUG',
'propagate': True,
},
Expand All @@ -216,7 +145,6 @@
},
}
}

CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
Expand All @@ -235,7 +163,7 @@
}


#配置文章开头使用rst格式无显示的问题
# 配置文章开头使用rst格式无显示的问题
RESTRUCTUREDTEXT_FILTER_SETTINGS = {
'doctitle_xform': False,
}
Expand Down
Loading

0 comments on commit 16fb9f4

Please sign in to comment.