@功能

2018-01-19  本文已影响0人  马梦里

由于 @ 是在回复中进行的,所以在回复的函数中添加此功能;

from models import Model
Model = Model

class Reply(Model):
    @classmethod
    def valid_names(cls):
        names = super().valid_names()
        names = names + [
            ('content', str, ''),
            ('topic_id', str, 0),
            ('user_id', str, 0),
        ]
        return names

    def user(self):
        from .user import User
        u = User.one(id=self.user_id)
        return u
from flask import (render_template, request, redirect, url_for, Blueprint, )

from models.mail import Mail
from routes import *

from models.reply import Reply
from utils import log

main = Blueprint('reply', __name__)

def users_from_content(content):
    # 不能解决 @在文本中间 比如 123@name abc,这样就不能获得name了
    parts = content.split(' ')
    users = []
    for p in parts:
        if p.startswith('@'):
            username = p[1:]
            u = User.one(username=username)
            users.append(u)
    return users
# 有个 bug 如果回复内容中含有 @ ,而后面跟着不是用户名,将会报错
def send_mails(sender, receivers, content):
    for r in receivers:
        form = dict(
            title='你被 {} AT 了'.format(sender.username),
            content=content,
            sender_id=sender.id,
            receiver_id=r.id,
        )
        m = Mail.new(form)
        log(m)
@main.route("/add", methods=["POST"])
def add():
    log('reply add')
    form = request.form
    u = current_user()

    # 发邮件
    log('before send mail', form)
    content = form['content']
    log('reply', content)
    users = users_from_content(content)
    log('reply', users)
    send_mails(u, users, content)
    log('after send mail')

    m = Reply.new(form, user_id=u.id)
    return redirect(url_for('topic.detail', id=m.topic_id))
上一篇 下一篇

猜你喜欢

热点阅读