Skip to content

Commit

Permalink
closed #4
Browse files Browse the repository at this point in the history
  • Loading branch information
dongweiming committed Jan 20, 2019
1 parent 0c8776a commit 726d703
Show file tree
Hide file tree
Showing 17 changed files with 69 additions and 36 deletions.
16 changes: 16 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
sudo: false
language: python
cache:
directories:
- $HOME/.cache/pip
before_script:
- pip install tox
matrix:
include:
- python: 3.6
env: TOXENV=flake8

install:
- pip install -U tox
script:
- tox
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# lyanna

[![Build Status](https://travis-ci.org/dongweiming/lyanna.svg?branch=master)](https://travis-ci.org/dongweiming/lyanna)

<p align="center">
My Blog Using Sanic
</p>
Expand Down
2 changes: 1 addition & 1 deletion app.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
from models.mc import cache
from models.blog import Post, Tag, MC_KEY_SITEMAP

from werkzeug.contrib.atom import AtomFeed
from werkzeug.utils import find_modules, import_string


Expand All @@ -36,6 +35,7 @@ def user(self):
def user_id(self):
return self.user.id if self.user else 0


app = Sanic(__name__, request_class=Request)
app.config.from_object(config)
auth.setup(app)
Expand Down
6 changes: 3 additions & 3 deletions config.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@
SENTRY_DSN = ''
REQUEST_TIMEOUT = 15

SITE_NAV_MENUS = [('blog.index', '首页'), ('blog.archives', '归档'), ('blog.tags', '标签'),
('index.search', '搜索'), ('index.feed', '订阅'),
('/page/aboutme', '关于我')]
SITE_NAV_MENUS = [('blog.index', '首页'), ('blog.archives', '归档'),
('blog.tags', '标签'), ('index.search', '搜索'),
('index.feed', '订阅'), ('/page/aboutme', '关于我')]

try:
from local_settings import * # noqa
Expand Down
3 changes: 2 additions & 1 deletion ext.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
from tortoise import Tortoise
from sanic_mako import SanicMako
from sanic_auth import Auth
import aiotask_context as context
import aiotask_context as context # noqa

from config import DB_URL, SENTRY_DSN

mako = SanicMako()
auth = Auth()


async def init_db(create_db=False):
await Tortoise.init(
db_url=DB_URL,
Expand Down
6 changes: 3 additions & 3 deletions forms.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import markupsafe
from sanic_wtf import SanicForm as _SanicForm, FileAllowed, FileRequired
from wtforms import (
PasswordField, StringField, SubmitField, BooleanField, IntegerField,
PasswordField, StringField, SubmitField, BooleanField,
SelectField, SelectMultipleField, TextAreaField, FileField)
from wtforms.widgets import HiddenInput
from wtforms.validators import DataRequired
Expand Down Expand Up @@ -41,6 +41,7 @@ def validate(self, extra_validators=None):
success = False
return success


class LoginForm(SanicForm):
name = StringField('Name', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
Expand All @@ -62,7 +63,7 @@ class PostForm(SanicForm):
content = TextAreaField('Content', default='')
can_comment = BooleanField('CanComment', default=True)
tags = SelectMultipleField('Tags', default=[])
author_id = SelectField('AuthorId', default='', validators=[DataRequired()])
author_id = SelectField('AuthorId', default='', validators=[DataRequired()]) # noqa
status = SwitchField('Published', choices=[('on', 1), ('off', 0)],
default='on')
is_page = BooleanField('IsPage', default=False)
Expand All @@ -77,4 +78,3 @@ class ProfileForm(SanicForm):
github_url = StringField('Github URL', default='')
linkedin_url = StringField('Linkedin URL', default='')
submit = SubmitField('Submit')

5 changes: 2 additions & 3 deletions hexo-exporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ async def write_post(file):
elif 'date:' in i:
date = i.split(':')[1].strip()
elif 'tags' in i:
i = i.split(':')[1].strip()[1:-1] if '[' in i else i.split(':')[1]
tags = filter(None, map(lambda x : x.strip(), i.split(',')))
i = i.split(':')[1].strip()[1:-1] if '[' in i else i.split(':')[1] # noqa
tags = filter(None, map(lambda x: x.strip(), i.split(',')))
content = ''.join(f.readlines())

try:
Expand All @@ -66,4 +66,3 @@ async def main():

if __name__ == '__main__':
run_async(main())

2 changes: 1 addition & 1 deletion models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ async def save(self, *args, **kwargs):

@classmethod
async def __flush__(cls, target):
await clear_mc(MC_KEY_ITEM_BY_ID % (target.__class__.__name__, target.id))
await clear_mc(MC_KEY_ITEM_BY_ID % (target.__class__.__name__, target.id)) # noqa
await target.clear_mc()

async def clear_mc(self):
Expand Down
6 changes: 4 additions & 2 deletions models/blog.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,8 @@ def _wrap_pre(self, inner):

# the empty span here is to keep leading empty lines from being
# ignored by HTML parsers
yield 0, ('<pre' + (style and ' style="%s"' % style) + (self.lang and f' class="hljs {self.lang}"') + '><span></span>')
yield 0, ('<pre' + (style and ' style="%s"' % style) + (
self.lang and f' class="hljs {self.lang}"') + '><span></span>')
for tup in inner:
yield tup
yield 0, '</pre>'
Expand Down Expand Up @@ -261,7 +262,8 @@ async def get_all(cls, with_page=True):
return await Post.sync_filter(status=Post.STATUS_ONLINE,
orderings=['-id'])
return await Post.sync_filter(status=Post.STATUS_ONLINE,
type__not=cls.TYPE_PAGE, orderings=['-id'])
type__not=cls.TYPE_PAGE,
orderings=['-id'])

@classmethod
async def cache(cls, ident):
Expand Down
1 change: 0 additions & 1 deletion models/comment.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import mistune
from tortoise import fields
from sanic_mako import render_template_def
from tortoise.query_utils import Q

from .base import BaseModel
Expand Down
8 changes: 4 additions & 4 deletions models/toc.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def _iter_toc(self, level):
first_level = 0
last_level = 0

yield '<div id="toc" class="toc-article"><strong class="toc-title">目录</strong><ol class="toc">\n'
yield '<div id="toc" class="toc-article"><strong class="toc-title">目录</strong><ol class="toc">\n' # noqa

for toc in self.toc_tree:
index, text, l, raw = toc
Expand All @@ -55,12 +55,12 @@ def _iter_toc(self, level):
# based on first level
first_level = l
last_level = l
yield f'<li class="toc-item toc-level-{l - 1}"><a class="toc-link" href="#{title}"><span class="toc-text">{text}</span></a>'
yield f'<li class="toc-item toc-level-{l - 1}"><a class="toc-link" href="#{title}"><span class="toc-text">{text}</span></a>' # noqa
elif last_level == l:
yield f'</li>\n<li class="toc-item toc-level-{l - 1}"><a class="toc-link" href="#{title}"><span class="toc-text">{text}</span></a>'
yield f'</li>\n<li class="toc-item toc-level-{l - 1}"><a class="toc-link" href="#{title}"><span class="toc-text">{text}</span></a>' # noqa
elif last_level == l - 1:
last_level = l
yield f'<ol class="toc-child">\n<li class="toc-item toc-level-{l - 1}"><a class="toc-link" href="#{title}"><span class="toc-text">{text}</span></a>'
yield f'<ol class="toc-child">\n<li class="toc-item toc-level-{l - 1}"><a class="toc-link" href="#{title}"><span class="toc-text">{text}</span></a>' # noqa
elif last_level > l:
yield '</li>'
while last_level > l:
Expand Down
2 changes: 1 addition & 1 deletion models/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ def iter_pages(self, left_edge=2, left_current=2,
for num in range(1, self.pages + 1):
if (
num <= left_edge
or self.page - left_current - 1 < num < self.page + right_current
or self.page - left_current - 1 < num < self.page + right_current # noqa
or num > self.pages - right_edge
):
if last + 1 != num:
Expand Down
15 changes: 15 additions & 0 deletions tox.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[tox]
minversion=2.3.1
envlist = py36, py37, flake8
skip_missing_interpreters = true

[testenv]
deps = pytest

[testenv:flake8]
basepython = python3
skip_install = true
deps =
flake8
commands =
flake8 .
4 changes: 2 additions & 2 deletions views/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
from sanic_mako import render_template

from ext import mako, auth
from config import UPLOAD_FOLDER, PER_PAGE
from models import Post, User, create_user, Tag
from config import PER_PAGE
from models import Post, User, Tag
from models.utils import Pagination
from models.user import generate_password
from models.profile import get_profile, set_profile
Expand Down
7 changes: 3 additions & 4 deletions views/blog.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,13 @@
from tortoise.query_utils import Q

from ext import mako
from models.consts import K_POST
from config import PER_PAGE
from models.mc import cache
from models.profile import get_profile
from models.utils import Pagination
from models.blog import (
MC_KEY_ARCHIVES, MC_KEY_ARCHIVE, MC_KEY_TAGS, MC_KEY_TAG)
from models import Post, Tag, PostTag, ReactItem, ReactStats
from models import Post, Tag, PostTag

bp = Blueprint('blog', url_prefix='/')

Expand Down Expand Up @@ -55,7 +54,7 @@ async def _post(request, ident, is_preview=False):
post = await Post.get_or_404(ident)
if not is_preview and post.status != Post.STATUS_ONLINE:
abort(404)
post_id = post.id

github_user = request['session'].get('user')
stats = await post.stats
reaction_type = None
Expand Down Expand Up @@ -120,7 +119,7 @@ async def tags(request):
@cache(MC_KEY_TAG % '{tag_id}')
async def tag(request, tag_id):
tag = await Tag.cache(tag_id)
post_ids = await PostTag.filter(tag_id=tag_id).order_by('-post_id').values_list(
post_ids = await PostTag.filter(tag_id=tag_id).order_by('-post_id').values_list( # noqa
'post_id', flat=True)
posts = await Post.get_multi(post_ids)
return {'tag': tag, 'posts': posts}
8 changes: 4 additions & 4 deletions views/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from sanic.log import logger
from sanic.response import redirect, text, HTTPResponse
from sanic_mako import render_template
from sanic_oauth.providers import GithubClient, UserInfo
from sanic_oauth.providers import GithubClient
from werkzeug.contrib.atom import AtomFeed

from ext import mako, auth
Expand Down Expand Up @@ -88,7 +88,7 @@ async def oauth(request, post_id=None):
user, info = await client.user_info()
except Exception as exc:
logger.exception(exc)
return redirect(cfg.oauth_redirect_path)
return redirect(config.oauth_redirect_path)

user = await create_github_user(user)
request['session']['user'] = user.to_dict()
Expand All @@ -98,8 +98,8 @@ async def oauth(request, post_id=None):

@cache(MC_KEY_FEED)
async def _feed(request):
feed = AtomFeed(title=SITE_TITLE, updated=datetime.now(), feed_url=request.url,
url=request.host)
feed = AtomFeed(title=SITE_TITLE, updated=datetime.now(),
feed_url=request.url, url=request.host)
posts = (await Post.get_all())[:10]
for post in posts:
body = post.html_content
Expand Down
12 changes: 6 additions & 6 deletions views/j.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,9 @@

from sanic import Blueprint
from sanic.response import json
from sanic.exceptions import abort
from sanic_mako import render_template_def

from models.consts import K_POST
from models import Post, ReactItem, ReactStats, Comment
from models import Post, ReactItem, Comment

bp = Blueprint('j', url_prefix='/j')

Expand Down Expand Up @@ -58,10 +56,12 @@ async def comments(request, post_id):

start = (page - 1) * per_page
comments = (await post.comments)[start: start + per_page]
liked_comment_ids = await post.comment_ids_liked_by(user['gid'])

user = request['session'].get('user')

liked_comment_ids = []
if user:
liked_comment_ids = await post.comment_ids_liked_by(user['gid'])

return json({
'r': 0,
'html': await render_template_def(
Expand Down Expand Up @@ -93,7 +93,7 @@ async def react(request, user, post):

stats = await post.stats
reaction_type = None
liked_comment_ids = []

if user:
reaction_type = await post.get_reaction_type(user['gid'])
return json({'r': int(not rv),
Expand Down

0 comments on commit 726d703

Please sign in to comment.