import os
from functools import wraps
from datetime import datetime
from models import app, db, User, Article
from forms import LoginForm, RegisterForm, ArticleAddForm, ArticleEditForm
from flask import session, redirect, url_for, request, \
flash, render_template, make_response
from uuid import uuid4
from werkzeug.utils import secure_filename
# settings
def user_login_request(f):
"""
login wrapper
"""
@wraps(f)
def login_request(*args, **kwargs):
if 'user' not in session:
return redirect(url_for('login', next_url=request.url))
return f(*args, **kwargs)
return login_request
def change_name(name):
info = os.path.splitext(name)
name_in = datetime.now().strftime('%Y%m%d%H%M%S') + str(uuid4().hex) + info[-1]
return name_in
@app.route('/')
def jump():
return redirect(url_for('login'))
@app.route('/login/', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
data = form.data
session['user'] = data['account']
flash('success login', 'ok')
return redirect(url_for('art_list', page=1))
return render_template('login.html', title='user login', form=form)
@user_login_request
@app.route('/logout/', methods=['GET', 'POST'])
def logout():
session.pop('user', None)
return redirect(url_for('login'))
@app.route('/register/', methods=['GET', 'POST'])
def register():
form = RegisterForm()
if form.validate_on_submit():
data = form.data
user = User(
username=data['account'],
password=data['re_pwd'],
)
db.session.add(user)
db.session.commit()
flash('success register', 'ok')
return redirect(url_for('login'))
return render_template('register.html', title='register', form=form)
@user_login_request
@app.route('/article/add/', methods=['GET', 'POST'])
def article_add():
# print('article add')
form = ArticleAddForm()
if form.validate_on_submit():
data = form.data
# print(data)
file_name = secure_filename(form.logo.data.filename)
logo_filename = change_name(file_name)
if not os.path.exists(app.config['uploads']):
os.makedirs(app.config['uploads'])
form.logo.data.save(os.path.join(app.config['uploads'], logo_filename))
user = User.query.filter_by(username=session['user']).first()
user_id = user.id
article = Article(
title=data['title'],
user_id=user_id,
logo=logo_filename,
content=data['content']
)
db.session.add(article)
db.session.commit()
flash('article publish success', 'ok')
return redirect(url_for('art_list', page=1))
return render_template('article_add.html', title='publish article', form=form)
@user_login_request
@app.route("/article/edit/<int:pk>/", methods=["GET", "POST"]) # 编辑文章
def art_edit(pk):
form = ArticleEditForm()
article = Article.query.get_or_404(ident=pk)
if request.method == 'GET':
form.content.data = article.content
if form.validate_on_submit():
if form.logo.data:
print(form.logo.data)
get_name = secure_filename(form.logo.data.filename)
filename = change_name(get_name)
if not os.path.exists(app.config['uploads']):
os.makedirs(app.config['uploads'])
form.logo.data.save(os.path.join(app.config['uploads'], filename))
article.logo = filename
if form.content.data != article.content:
article.content = form.content.data
db.session.add(article)
db.session.commit()
return redirect(url_for('art_list', page=1))
return render_template("article_edit.html", form=form, title="编辑文章", article=article)
@user_login_request
@app.route("/article/list/<int:page>/", methods=["GET"]) # 文章列表
def art_list(page):
if not page:
page = 1
# 只展示当前用户才能看到的内容
user = User.query.filter_by(username=session["user"]).first()
user_id = user.id
page_data = Article.query.filter_by(user_id=user_id) \
.order_by(Article.add_time.desc()).paginate(page=page, per_page=5)
# print(page_data)
return render_template("article_list.html", title="文章列表", page_data=page_data)
@user_login_request
@app.route("/article/del/<int:pk>/", methods=["GET"]) # 删除文章
def art_del(pk):
article = Article.query.get_or_404(ident=pk)
db.session.delete(article)
db.session.commit()
flash("删除 %s 成功!" % article.title, "ok")
return redirect(url_for('art_list', page=1))
@app.route("/captcha/", methods=["GET"])
def captcha():
from app.generate_img import generate_buf_picture
img_bin, text = generate_buf_picture()
session['captcha'] = text
response = make_response(img_bin)
response.headers['Content-Type'] = 'image/jpeg'
return response
if __name__ == '__main__':
app.run(debug=True)
网友评论