<filename>info/Modules/profile/views.py<gh_stars>0
# encoding=utf-8

from flask import Blueprint, g, render_template, abort, jsonify, request, current_app, flash
import re

from info.utils.common import LoginUser
from info.utils.response_code import RET
from info import db
from info import constants
from info.constants import QINIU_DOMIN_PREFIX


profileblue = Blueprint('profile', __name__)

@profileblue.route('/', methods = ['POST', 'GET'])
@LoginUser
def getProfile():
    # 查询现在登录的用户；
    login_user = g.login_user

    # 如果查询不到登录用户，报错；
    if not login_user:
        abort(404)

    datas = {
        'login_user': login_user.to_dict()
    }

    # 返回用户dict；
    return render_template('/news/html/user.html', datas = datas)


@profileblue.route('/user_base_info', methods = ['POST', 'GET'])
@LoginUser
def getUserBaseInfo():
    # 查询现在登录的用户；
    login_user = g.login_user

    if request.method == 'GET':
        if not login_user:
            abort(404)

        datas = {
            'login_user': login_user.to_dict()
        }

        return render_template('/news/html/user_base_info.html', datas = datas)


    elif request.method == 'POST':
        # 如果查询不到登录用户，报错；
        if not login_user:
            return jsonify(errno=RET.LOGINERR, errmsg='请先登录')

        base_infos = request.json
        signature = base_infos.get('signature')
        nick_name = base_infos.get('nick_name')
        gender = base_infos.get('gender')

        if not all([signature, nick_name, gender]):
            return jsonify(errno = RET.NODATA, errmsg = '数据不全')

        try:
            signature = str(signature)
            nick_name = str(nick_name)
            gender = str(gender)
        except Exception as err:
            return jsonify(errno = RET.DATAERR, errmsg = '数据格式错误')

        if not gender in ['MAN', 'WOMAN']:
            return jsonify(errno = RET.DATAERR, errmsg = '参数不正确')

        if not re.match(r'\w{2,20}', nick_name):
            return jsonify(errno = RET.DATAERR, errmsg = '昵称格式错误')

        if not re.match(r'(.{0,500})', signature):
            return jsonify(errno=RET.DATAERR, errmsg='签名错误')

        # 操作数据库；
        try:
            from info.models import News
            for item in News.query.filter(News.source==login_user.nick_name).all():
                item.source = nick_name

            login_user.signature = signature
            login_user.nick_name = nick_name
            login_user.gender = gender

            db.session.commit()

        except Exception as err:
            current_app.logger.error(err)
            return jsonify(errno = RET.DBERR, errmsg = '数据库操作失败')

        # 返回用户dict；
        return jsonify(errno=RET.OK, errmsg='保存成功')


@profileblue.route('/user_pic_info', methods=['POST', 'GET'])
@LoginUser
def userPicInfo():
    login_user = g.login_user
    outter_url = None

    if request.method == 'GET':
        return render_template('news/html/user_pic_info.html', datas = {'login_user':g.login_user.to_dict()})

    elif request.method == 'POST':
        try:
            image = request.files.get('avatar').read()
        except Exception as err:
            current_app.logger(err)
            return jsonify(errno = RET.IOERR, errmsg = '数据传输失败')

        if not image:
            return jsonify(errno = RET.IOERR, errmsg = '图片不能为空')

        try:
            from info.utils.image_storage import storage
            outter_url = storage(image)
        except Exception as err:
            current_app.logger.error(err)
            return jsonify(errno = RET.THIRDERR, errmsg = '第三方错误')

        if not outter_url:
            current_app.logger.error('数据传输到远端失败')
            return jsonify(errno = RET.THIRDERR, errmsg = '上传图片到远端失败')

        # 保存url到本地数据库；
        try:
            login_user.avatar_url = constants.QINIU_DOMIN_PREFIX + outter_url
            db.session.commit()
        except Exception as err:
            current_app.logger.error(err)
            return jsonify(errno = RET.DBERR, errmsg = '数据库操作失败')

        print(constants.QINIU_DOMIN_PREFIX + outter_url)

        return jsonify(err = RET.OK, errmsg = '上传成功', datas = {'outter_url':constants.QINIU_DOMIN_PREFIX + outter_url})

@profileblue.route('/passwd_change', methods=['POST', 'GET'])
@LoginUser
def passwdChange():
    if request.method == 'GET':
        return render_template('news/html/user_pass_info.html')

    elif request.method == 'POST':
        # 获取所有参数；
        passwd_infos = request.json
        current_passwd = passwd_infos.get('current_passwd')
        new_passwd = passwd_infos.get('new_passwd')
        confirm_passwd = passwd_infos.get('confirm_passwd')

        # 校验当前密码、新密码格式；
        if not all([current_passwd, new_passwd, confirm_passwd]):
            return jsonify(errno = RET.DATAERR, errmsg = 'datas not complite.')
        try:
            current_passwd, new_passwd, confirm_passwd = str(current_passwd), str(new_passwd), str(confirm_passwd)
        except Exception as err:
            return jsonify(errno = RET.DATAERR, errmsg = 'datas not allowed.')

        if not re.match(r'^[0-9a-zA-Z][\w]{5,}$', current_passwd) or not re.match(r'^[0-9a-zA-Z][\w]{5,}$', new_passwd) or not re.match(r'^[0-9a-zA-Z][\w]{5,}$', confirm_passwd):
            return jsonify(errno = RET.DATAERR, errmsg = 'datas not allowed.')

        # 校验两个新密码是否一致；
        if not new_passwd == confirm_passwd:
            return jsonify(errno = RET.DATAERR, errmsg = 'passwd doesn\'t match.')

        # try: database operation;
        try:
            login_user = g.login_user
            if not login_user.check_password(current_passwd):
                return jsonify(errno = RET.PWDERR, errmsg = 'current password doesn\'t match.')

            login_user.password = <PASSWORD>
            db.session.commit()
        except Exception as err:
            current_app.logger.error(err)
            return jsonify(errno = RET.DBERR, errmsg = 'database operation failed.')

        return jsonify(errno = RET.OK, errmsg = 'Successed.')


@profileblue.route('/show_collection')
@LoginUser
def showCollection():
    login_user = g.login_user
    my_collection = None
    current_page = int(request.args.get('current_page', 1))

    if not login_user:
        return jsonify(errno = RET.LOGINERR, errmsg = 'haven\'t login.')

    try:
        collection_this_page = login_user.collection_news.paginate(page=current_page, per_page = 1)
        my_collection = [item.to_review_dict() for item in collection_this_page.items]
        total_pages = collection_this_page.pages
    except Exception as err:
        current_app.logger.error(err)
        return jsonify(errno = RET.DBERR, errmsg = 'database operation failed.')

    datas = {
        'my_collection': my_collection,
        'total_pages':total_pages,
        'current_page':current_page
    }

    return render_template('news/html/user_collection.html', datas = datas)

@profileblue.route('/public_news', methods = ['POST', 'GET'])
@LoginUser
def publicNews():
    if request.method == 'POST':
        news_info = request.form
        title = news_info.get('title')
        category = news_info.get('category_id')
        digest = news_info.get('digest')
        image = None
        content = news_info.get('content')
        outter_url = None

        try:
            image = news_info.get('image').read()
            print(image)
        except Exception as err:
            flash('image transform failed.')

        if not all([title, category, digest, content]):
            return jsonify(errno = RET.NODATA, errmsg = 'data missing.')

        try:
            category = int(category)
        except Exception as err:
            return jsonify(errno = RET.DATAERR, errmsg = 'data type error.')

        if not re.match(r'(.|\n){1,20}$', title) or not re.match(r'(.|\n){2,200}$', digest) or not re.match(r'(.|\n){20,200000}$', content):
            return jsonify(errno =RET.PARAMERR, errmsg = '字数不符合要求:标题1-20字符，摘要2-200字符，内容20-20w字符')

        if image:
            try:
                from info.utils.image_storage import storage
                outter_url = storage(image)

                if not outter_url:
                    pass
                    # return jsonify(errno = 100, errmsg = '发布成功，但图片上传失败')
            except Exception as err:
                current_app.logger.error(err)
                return jsonify(errno = RET.DBERR, errmsg = '数据库操作失败')

        try:
            from info.models import News
            public_news = News()
            public_news.title = title
            public_news.source = g.login_user.nick_name
            public_news.user_id = g.login_user.id
            public_news.category_id = category
            public_news.digest = digest
            public_news.content = content
            public_news.status = 1
            public_news.index_image_url = constants.QINIU_DOMIN_PREFIX + outter_url if outter_url else None
            db.session.add(public_news)
            db.session.commit()
        except Exception as err:
            current_app.logger.error(err)
            return jsonify(errno = RET.DBERR, errmsg = '数据库操作失败')

        return jsonify(errno=RET.OK, errmsg='OK')

    elif request.method == 'GET':
        from info.models import Category
        all_categories = Category.query.filter(Category.id != 1).all()
        all_categories = [item.to_dict() for item in all_categories]
        return render_template('news/html/user_news_release.html', datas = {'all_categories':all_categories})


@profileblue.route('/user_publications')
@LoginUser
def userPublications():
    target_page = request.args.get('page', 1)
    try:
        target_page = int(target_page)
    except Exception:
        abort(404)

    try:
        from info.models import News, User


        all_news = News.query.filter(News.source == g.login_user.nick_name).order_by(News.create_time.desc()).paginate(page=target_page, per_page=constants.OTHER_NEWS_PAGE_MAX_COUNT)
        total_page = all_news.pages
        all_news = [item.to_review_dict() for item in all_news.items]
    except Exception as err:
        current_app.logger.error(err)
        abort(404)

    data = {
        'news_dict_li':all_news,
        'current_page':target_page,
        'total_page':total_page
    }

    return render_template('news/html/user_news_list.html', data = data)


@profileblue.route('/user_follow')
@LoginUser
def userFollow():
    login_user = g.login_user

    try:
        follwed_users = [item.to_dict() for item in login_user.followed.all()]
    except Exception as err:
        current_app.logger.error(err)
        return jsonify(ernro = RET.DBERR, errmsg = '数据库操作失败')

    data = {
        'users':follwed_users
    }

    return render_template('news/html/user_follow.html', data = data)
<filename>info/Modules/profile/views.py<gh_stars>0
# encoding=utf-8

from flask import Blueprint, g, render_template, abort, jsonify, request, current_app, flash
import re

from info.utils.common import LoginUser
from info.utils.response_code import RET
from info import db
from info import constants
from info.constants import QINIU_DOMIN_PREFIX


profileblue = Blueprint('profile', __name__)

@profileblue.route('/', methods = ['POST', 'GET'])
@LoginUser
def getProfile():
    # 查询现在登录的用户；
    login_user = g.login_user

    # 如果查询不到登录用户，报错；
    if not login_user:
        abort(404)

    datas = {
        'login_user': login_user.to_dict()
    }

    # 返回用户dict；
    return render_template('/news/html/user.html', datas = datas)


@profileblue.route('/user_base_info', methods = ['POST', 'GET'])
@LoginUser
def getUserBaseInfo():
    # 查询现在登录的用户；
    login_user = g.login_user

    if request.method == 'GET':
        if not login_user:
            abort(404)

        datas = {
            'login_user': login_user.to_dict()
        }

        return render_template('/news/html/user_base_info.html', datas = datas)


    elif request.method == 'POST':
        # 如果查询不到登录用户，报错；
        if not login_user:
            return jsonify(errno=RET.LOGINERR, errmsg='请先登录')

        base_infos = request.json
        signature = base_infos.get('signature')
        nick_name = base_infos.get('nick_name')
        gender = base_infos.get('gender')

        if not all([signature, nick_name, gender]):
            return jsonify(errno = RET.NODATA, errmsg = '数据不全')

        try:
            signature = str(signature)
            nick_name = str(nick_name)
            gender = str(gender)
        except Exception as err:
            return jsonify(errno = RET.DATAERR, errmsg = '数据格式错误')

        if not gender in ['MAN', 'WOMAN']:
            return jsonify(errno = RET.DATAERR, errmsg = '参数不正确')

        if not re.match(r'\w{2,20}', nick_name):
            return jsonify(errno = RET.DATAERR, errmsg = '昵称格式错误')

        if not re.match(r'(.{0,500})', signature):
            return jsonify(errno=RET.DATAERR, errmsg='签名错误')

        # 操作数据库；
        try:
            from info.models import News
            for item in News.query.filter(News.source==login_user.nick_name).all():
                item.source = nick_name

            login_user.signature = signature
            login_user.nick_name = nick_name
            login_user.gender = gender

            db.session.commit()

        except Exception as err:
            current_app.logger.error(err)
            return jsonify(errno = RET.DBERR, errmsg = '数据库操作失败')

        # 返回用户dict；
        return jsonify(errno=RET.OK, errmsg='保存成功')


@profileblue.route('/user_pic_info', methods=['POST', 'GET'])
@LoginUser
def userPicInfo():
    login_user = g.login_user
    outter_url = None

    if request.method == 'GET':
        return render_template('news/html/user_pic_info.html', datas = {'login_user':g.login_user.to_dict()})

    elif request.method == 'POST':
        try:
            image = request.files.get('avatar').read()
        except Exception as err:
            current_app.logger(err)
            return jsonify(errno = RET.IOERR, errmsg = '数据传输失败')

        if not image:
            return jsonify(errno = RET.IOERR, errmsg = '图片不能为空')

        try:
            from info.utils.image_storage import storage
            outter_url = storage(image)
        except Exception as err:
            current_app.logger.error(err)
            return jsonify(errno = RET.THIRDERR, errmsg = '第三方错误')

        if not outter_url:
            current_app.logger.error('数据传输到远端失败')
            return jsonify(errno = RET.THIRDERR, errmsg = '上传图片到远端失败')

        # 保存url到本地数据库；
        try:
            login_user.avatar_url = constants.QINIU_DOMIN_PREFIX + outter_url
            db.session.commit()
        except Exception as err:
            current_app.logger.error(err)
            return jsonify(errno = RET.DBERR, errmsg = '数据库操作失败')

        print(constants.QINIU_DOMIN_PREFIX + outter_url)

        return jsonify(err = RET.OK, errmsg = '上传成功', datas = {'outter_url':constants.QINIU_DOMIN_PREFIX + outter_url})

@profileblue.route('/passwd_change', methods=['POST', 'GET'])
@LoginUser
def passwdChange():
    if request.method == 'GET':
        return render_template('news/html/user_pass_info.html')

    elif request.method == 'POST':
        # 获取所有参数；
        passwd_infos = request.json
        current_passwd = passwd_infos.get('current_passwd')
        new_passwd = passwd_infos.get('new_passwd')
        confirm_passwd = passwd_infos.get('confirm_passwd')

        # 校验当前密码、新密码格式；
        if not all([current_passwd, new_passwd, confirm_passwd]):
            return jsonify(errno = RET.DATAERR, errmsg = 'datas not complite.')
        try:
            current_passwd, new_passwd, confirm_passwd = str(current_passwd), str(new_passwd), str(confirm_passwd)
        except Exception as err:
            return jsonify(errno = RET.DATAERR, errmsg = 'datas not allowed.')

        if not re.match(r'^[0-9a-zA-Z][\w]{5,}$', current_passwd) or not re.match(r'^[0-9a-zA-Z][\w]{5,}$', new_passwd) or not re.match(r'^[0-9a-zA-Z][\w]{5,}$', confirm_passwd):
            return jsonify(errno = RET.DATAERR, errmsg = 'datas not allowed.')

        # 校验两个新密码是否一致；
        if not new_passwd == confirm_passwd:
            return jsonify(errno = RET.DATAERR, errmsg = 'passwd doesn\'t match.')

        # try: database operation;
        try:
            login_user = g.login_user
            if not login_user.check_password(current_passwd):
                return jsonify(errno = RET.PWDERR, errmsg = 'current password doesn\'t match.')

            login_user.password = <PASSWORD>
            db.session.commit()
        except Exception as err:
            current_app.logger.error(err)
            return jsonify(errno = RET.DBERR, errmsg = 'database operation failed.')

        return jsonify(errno = RET.OK, errmsg = 'Successed.')


@profileblue.route('/show_collection')
@LoginUser
def showCollection():
    login_user = g.login_user
    my_collection = None
    current_page = int(request.args.get('current_page', 1))

    if not login_user:
        return jsonify(errno = RET.LOGINERR, errmsg = 'haven\'t login.')

    try:
        collection_this_page = login_user.collection_news.paginate(page=current_page, per_page = 1)
        my_collection = [item.to_review_dict() for item in collection_this_page.items]
        total_pages = collection_this_page.pages
    except Exception as err:
        current_app.logger.error(err)
        return jsonify(errno = RET.DBERR, errmsg = 'database operation failed.')

    datas = {
        'my_collection': my_collection,
        'total_pages':total_pages,
        'current_page':current_page
    }

    return render_template('news/html/user_collection.html', datas = datas)

@profileblue.route('/public_news', methods = ['POST', 'GET'])
@LoginUser
def publicNews():
    if request.method == 'POST':
        news_info = request.form
        title = news_info.get('title')
        category = news_info.get('category_id')
        digest = news_info.get('digest')
        image = None
        content = news_info.get('content')
        outter_url = None

        try:
            image = news_info.get('image').read()
            print(image)
        except Exception as err:
            flash('image transform failed.')

        if not all([title, category, digest, content]):
            return jsonify(errno = RET.NODATA, errmsg = 'data missing.')

        try:
            category = int(category)
        except Exception as err:
            return jsonify(errno = RET.DATAERR, errmsg = 'data type error.')

        if not re.match(r'(.|\n){1,20}$', title) or not re.match(r'(.|\n){2,200}$', digest) or not re.match(r'(.|\n){20,200000}$', content):
            return jsonify(errno =RET.PARAMERR, errmsg = '字数不符合要求:标题1-20字符，摘要2-200字符，内容20-20w字符')

        if image:
            try:
                from info.utils.image_storage import storage
                outter_url = storage(image)

                if not outter_url:
                    pass
                    # return jsonify(errno = 100, errmsg = '发布成功，但图片上传失败')
            except Exception as err:
                current_app.logger.error(err)
                return jsonify(errno = RET.DBERR, errmsg = '数据库操作失败')

        try:
            from info.models import News
            public_news = News()
            public_news.title = title
            public_news.source = g.login_user.nick_name
            public_news.user_id = g.login_user.id
            public_news.category_id = category
            public_news.digest = digest
            public_news.content = content
            public_news.status = 1
            public_news.index_image_url = constants.QINIU_DOMIN_PREFIX + outter_url if outter_url else None
            db.session.add(public_news)
            db.session.commit()
        except Exception as err:
            current_app.logger.error(err)
            return jsonify(errno = RET.DBERR, errmsg = '数据库操作失败')

        return jsonify(errno=RET.OK, errmsg='OK')

    elif request.method == 'GET':
        from info.models import Category
        all_categories = Category.query.filter(Category.id != 1).all()
        all_categories = [item.to_dict() for item in all_categories]
        return render_template('news/html/user_news_release.html', datas = {'all_categories':all_categories})


@profileblue.route('/user_publications')
@LoginUser
def userPublications():
    target_page = request.args.get('page', 1)
    try:
        target_page = int(target_page)
    except Exception:
        abort(404)

    try:
        from info.models import News, User


        all_news = News.query.filter(News.source == g.login_user.nick_name).order_by(News.create_time.desc()).paginate(page=target_page, per_page=constants.OTHER_NEWS_PAGE_MAX_COUNT)
        total_page = all_news.pages
        all_news = [item.to_review_dict() for item in all_news.items]
    except Exception as err:
        current_app.logger.error(err)
        abort(404)

    data = {
        'news_dict_li':all_news,
        'current_page':target_page,
        'total_page':total_page
    }

    return render_template('news/html/user_news_list.html', data = data)


@profileblue.route('/user_follow')
@LoginUser
def userFollow():
    login_user = g.login_user

    try:
        follwed_users = [item.to_dict() for item in login_user.followed.all()]
    except Exception as err:
        current_app.logger.error(err)
        return jsonify(ernro = RET.DBERR, errmsg = '数据库操作失败')

    data = {
        'users':follwed_users
    }

    return render_template('news/html/user_follow.html', data = data)
# encoding=utf-8 # 查询现在登录的用户； # 如果查询不到登录用户，报错； # 返回用户dict； # 查询现在登录的用户； # 如果查询不到登录用户，报错； # 操作数据库； # 返回用户dict； # 保存url到本地数据库； # 获取所有参数； # 校验当前密码、新密码格式； # 校验两个新密码是否一致； # try: database operation; # return jsonify(errno = 100, errmsg = '发布成功，但图片上传失败')