flask 李子

8 篇文章 0 订阅
6 篇文章 0 订阅

在这里插入图片描述

在这里插入图片描述
start.py

from models import *

from modules.A import a_blue
app.register_blueprint(a_blue)


@app.template_filter('ci')
def ci(num):
    return str(num) + '次'


if __name__ == '__main__':
    # db.drop_all()
    # db.create_all()
    app.run(port=9991)

setting.py

DEBUG = True
SQLALCHEMY_ECHO = True
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:yang@127.0.0.1:3306/aaaaaa?charset=utf8'
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
SECRET_KEY = 'abc'
# PER_PAGE_NUM=2

models.py

from apps import *

class User(db.Model):
    id = db.Column(db.Integer,primary_key=True,comment='用户表主键')
    uname = db.Column(db.String(30),comment='用户姓名',unique=True)
    pwd = db.Column(db.String(20),comment='用户密码')
    pst = db.Column(db.String(50),comment='个性签名')


class Book(db.Model):
    id = db.Column(db.Integer,primary_key=True,comment='文章表主键')
    title = db.Column(db.String(30),comment='标题')
    pic = db.Column(db.String(100),default='default.jpg')
    content = db.Column(db.Text,comment='内容')
    num = db.Column(db.Integer,comment='浏览量')


class Comment(db.Model):
    id = db.Column(db.Integer,primary_key=True,comment='评论表主键')
    content = db.Column(db.String(250),comment='评论内容')
    user_id = db.Column(db.Integer,db.ForeignKey(User.id),comment='外键指向用户')
    book_id = db.Column(db.Integer,db.ForeignKey(Book.id),comment='外键指向文章')

apps.py

from flask import Flask,Blueprint,render_template,request,redirect,url_for,flash,session,make_response,g,current_app
from flask_sqlalchemy import SQLAlchemy
import sys,os
from flask_uploads import UploadSet,IMAGES,configure_uploads

app = Flask(__name__)
app.config.from_object('setting')
db = SQLAlchemy(app=app)

enter = getattr(sys.modules['__main__'], '__file__')   # 初始化成文件类型
root_path = os.path.dirname(enter)+'/static/upload'
app.config['UPLOADED_XINS_DEST'] = root_path  # 设置上传路径
app.config['UPLOADED_XINS_ALLOW'] = IMAGES  # 允许类型
xins = UploadSet('XINS')  # 实例化图片上传类,设置上传的统一名称
configure_uploads(app, xins)  # 将app的config配置注册到UploadSet实例xins



创建modules文件夹下创建A.py
A.py\

from flask import Blueprint
from models import *
a_blue = Blueprint('aaa',__name__)

# 注册
@a_blue.route('/reg',methods=['POST','GET'])
def reg():
    if request.method == 'POST':
        name = request.form.get('uname')
        pwd = request.form.get('pwd')
        repwd = request.form.get('repwd')
        # users = User.query.all()
        # for user in users:
        #     if name != user.uname:
        if not all([name,pwd,repwd]):
            flash('信息填写不完整')
        elif pwd != repwd:
            flash('密码不一致!')
        elif len(pwd) < 6:
            flash('密码长度不能小于6位')
        else:
            new_user = User(uname=name,pwd=pwd,pst='热爱生活')
            db.session.add(new_user)
            flash('注册成功')
            return redirect(url_for('aaa.login'))
            # else:
            #     return '同名不能注册'
    return render_template('reg.html')

# 登录
@a_blue.route('/login',methods=['POST','GET'])
def login():
    if request.method == 'POST':
        name = request.form.get('uname')
        pwd = request.form.get('pwd')
        if not all([name,pwd]):
            flash('信息填写不完整')
        else:
            one_user = User.query.filter(User.uname==name).first()
            if not one_user:
                flash('用户不存在')
            else:
                if pwd != one_user.pwd:
                    flash('密码错误')
                else:
                    session['name'] = one_user.uname
                    session['id'] = one_user.id
                    session['num'] = 0
                    flash('登录成功')
                    return redirect(url_for('aaa.user_detail'))
    return render_template('login.html')

# 用户详情
@a_blue.route('/user_detail',methods=['POST','GET'])
def user_detail():
    user_id = session.get('id')
    one_user = User.query.get(user_id)
    return render_template('user_detail.html',one_user = one_user)

# 发表文章
@a_blue.route('/add_book',methods=['POST','GET'])
def add_book():
    one_user = session.get('name')
    if not one_user:
        return '发表文章必须登录用户'
    else:
        if request.method == 'POST':
            title = request.form.get('title')
            content = request.form.get('content')
            pic = request.files.get('pic')
            pic_url = xins.save(pic)
            num = session.get('num')
            book = Book(title=title,content=content,pic=pic_url,num=num)
            db.session.add(book)
            return redirect(url_for('aaa.user_detail'))
        return render_template('add_book.html')

# 文章列表
@a_blue.route('/book_list')
def book_list():
    one_user = session.get('name')
    kw = request.args.get('kw',"")
    books = Book.query.filter(Book.title.like('%'+ kw + '%')).all()
    return render_template('book_list.html',books=books,kw=kw,one_user = one_user)

# 发表的文章
@a_blue.route('/post_book')
def post_book():
    one_user = session.get('name')
    if not one_user:
        return '发表文章必须登录用户'
    else:
        # page = int(request.args.get('page',1))
        # books = Book.query.order_by(Book.id.desc()).paginate(page,1)
        books = Book.query.filter(Book.num==Book.num+'次').all()
        return render_template('post_book.html',books=books)

# 文章详情
@a_blue.route('/book_detail')
def book_detail():
    book_id = request.args.get('book_id')
    one_book = Book.query.get(book_id)
    one_book.num += 1
    comments = Comment.query.filter(Comment.book_id==book_id).all()
    return render_template('book_detail.html',one_book=one_book,comments=comments)

# 退出
@a_blue.route('/logout')
def logout():
    # session.pop('id',None)
    session.pop('name',None)
    return redirect(url_for('aaa.user_detail'))

# 批量删除
@a_blue.route('/delete_books',methods=['POST'])
def delete_books():
    book_ids = request.form.getlist('book_ids')
    # books = Book.query.get(book_ids)
    for book_id in book_ids:
        one_book = Book.query.get(book_id)
        db.session.delete(one_book)
    return redirect(url_for('aaa.post_book'))

# 添加评论
@a_blue.route('/add_comment',methods=['POST','GET'])
def add_comment():
    content = request.form.get('content')
    uid = session.get('id')
    book_id = request.args.get('book_id')
    boook = Comment(content=content,user_id=uid,book_id=book_id)
    db.session.add(boook)
    return redirect(url_for('aaa.book_detail',book_id=book_id))


# @a_blue.route('/comments',methods=['POST'])
# def comments():
#     comments = Comment.query.all()
#     return redirect(url_for('aaa.book_detail',comments=comments))



add_book.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加文章</title>
    <script src="../static/web/tinymce/js/tinymce/tinymce.min.js"></script>
    <script src="../static/web/js/tinymce_setup.js"></script>
</head>
<body>
<form method="post" enctype="multipart/form-data">
    文章标题 :<input type="text" name="title">   <input type="file" name="pic"> <br>
    文章内容 :<input type="text" name="content" id="rich_content"><br>
    <input type="submit" value="发表文章">
</form>
</body>
</html>


book_detail.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文章详情</title>
</head>
<body>
{{ one_book.title }}<br>
{#{{ one_book.pic }}#}

{{ one_book.content | safe}}<br><br>
<form action="{{ url_for('aaa.add_comment',book_id=one_book.id) }}" method="post">
评论 :<textarea name="content"></textarea><br>
    <input type="submit" value="发表评论"><br><br>
    所有评论 :<br>
    {% for comment in comments %}
    {{ loop.index }}{{ comment.content }}<br>
    {% endfor %}

</form>
</body>
</html>


book_list.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文章列表</title>
</head>
<body>
{% extends 'user_detail.html' %}
{% block content %}
    {{ super() }}
    <form action="">
    <input type="text" value="{{ kw }}" name="kw">
    <input type="submit" value="搜索">
    </form><br>

{% for book in books %}
    {{ book.title }}<br>
{% endfor %}
{% endblock content %}

</body>
</html>


login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
<form action="" method="post">
    用户名 :<input type="text" name="uname">
    密码 :<input type="password" name="pwd">
    <input type="submit" value="登录">
    {% for foo in get_flashed_messages() %}
    {{ foo }}
    {% endfor %}

</form>
</body>
</html>

post_book.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>发布的文章</title>
    <script type="text/css" src="../static/web/js/jquery.js"></script>
    <link rel="stylesheet" type="text/css" href="../static/web/css/jquery.pagination.css">
    <script src="../static/web/js/jquery.pagination.min.js"></script>
</head>
<body>

<form action="{{ url_for('aaa.delete_books') }}" method="post">
{% for book in books %}
    <input type="checkbox" value="{{ book.id }}" name="book_ids">
    {{ book.id }} | <a href="{{ url_for('aaa.book_detail',book_id=book.id) }}">{{ book.title }}</a>|{{ book.num | ci}}
    | <img src="../static/upload/{{ book.pic }}" width="100px"/> <br>
{% endfor %}
<input type="submit" value="批量删除">
</form>
{#<a href="{{ url_for('aaa.post_book',page=1) }}">1</a>#}
{#<a href="{{ url_for('aaa.post_book',page=2) }}">2</a>#}
{#<a href="{{ url_for('aaa.post_book',page=3) }}">3</a>#}

{#    <div id="page"></div>#}
{#    <script>#}

{#    $(function () {#}
{#        $('#page').pagination({#}
{#            currentPage : {{ books.page }},#}
{#            cocalPage : {{ books.pages }},#}
{#            callback:function (current) {#}
{#                window.location.href = '?page='+ current#}
{#            }#}
{#        })#}
{#    })#}
{#    </script>#}
</body>
</html>

reg.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册</title>
</head>
<body>
<form method="post">
    用户名 :<input type="text" name="uname">
    密码 :<input type="password" name="pwd">
    确认密码 :<input type="password" name="repwd">
    <input type="submit" value="注册">
    {% for foo in get_flashed_messages() %}
    {{ foo }}
    {% endfor %}
</form>
</body>
</html>

user_detail.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户详情</title>
</head>
<body>
{% block content %}
    {% if session.get('name') %}
        您好 【{{ one_user.uname }}| <a href="{{ url_for('aaa.logout') }}">退出</a>
        {% else %}
        您好 【】| <a href="{{ url_for('aaa.login') }}">登录</a>
    {% endif %}<br>
    用户名 :{{ one_user.uname }}<br>
    个性签名 :{{ one_user.pst }}<br>

    <a href="{{ url_for('aaa.add_book',user_id=one_user.id) }}">添加文章</a> <br>
    <a href="{{ url_for('aaa.post_book',user_id=one_user.id) }}">我发布的文章</a> <br>
{% endblock content %}
</body>
</html>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值