项目结构
文件目录
requirements.txt
flask-bootstrap==3.3.7.1
flask-login==0.5.0
flask-script==2.0.6
flask==2.0.1
werkzeug==2.0.1
error404.jpg
是一个404的图片。
error404.html
处理404页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>python+flask博客系统-错误</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<link rel="shortcut icon" href="https://demosc.chinaz.net/Files/pic/iconsico/8117/f2.ico">
</head>
<body>
<div align="center" id="error-show">
<h1>未发现此内容</h1>
<img src="/benefiter/image/error404.jpg" width="525" height="394">
<br>
</div>
</body>
</html>
index.html
主页:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>python+flask博客系统-首页</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link rel="shortcut icon" href="http://www.icosky.com/icon/ico/System/Micro/Web.ico">
</head>
<body>
{% if message %}
<script>
alert("{{message}}")
</script>
{% endif %}
<div class="jumbotron text-center" id="welcome">
<h1>python+flask博客系统</h1>
<p>无sql 无django</p>
</div>
<hr>
<a href="/benefiter/logout">退出登录...</a>
<div id="choose">
<a href="/benefiter/write" target="_blank">
<button class="btn btn-primary">
写博客
</button>
</a>
<br>
<br>
<a href="/benefiter/search" target="_blank">
<button class="btn btn-primary">
搜索
</button>
</a>
</div>
</body>
</html>
login.html
为登录页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>python+flask博客系统-登录</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link rel="shortcut icon" href="https://demosc.chinaz.net/Files/pic/iconsico/8122/w4.ico">
</head>
<body>
{% if message %}
<div id="error" align="center">
<p>{{message}}</p>
</div>
{% endif %}
<div align="center">
<form method="post" action="/benefiter/login/judge">
<label>用户名:</label>
<input type="text" name="username">
<br>
<label>密码: </label>
<input type="password" name="password">
<br>
<input type="submit" value="登录" class="btn btn-primary" name="login">
</form>
</div>
<hr>
<div id="create-user" align="center">
<a href="/benefiter/login/create">创建账号...</a>
</div>
</body>
</html>
create-user.html
是创建账号的页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>python+flask博客系统-创建账号</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link rel="shortcut icon" href="https://demosc.chinaz.net/Files/pic/iconsico/8139/h12.ico">
</head>
<body>
{% if message %}
<div id="error" align="center">
<p>{{message}}</p>
</div>
{% endif %}
<div align="center">
<form method="post" action="/benefiter/login/create-judge">
<label>用户名:</label>
<input type="text" name="username">
<br>
<label>密码: </label>
<input type="password" name="password">
<br>
<input type="submit" value="创建" class="btn btn-primary" name="create">
</form>
</div>
</body>
</html>
search.html
是搜索页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>python+flask博客系统-搜索</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<link rel="shortcut icon" href="https://demosc.chinaz.net/Files/pic/iconsico/5897/s13.ico">
</head>
<body>
<div align="left" id="search">
<form action="/benefiter/searcher" method="post">
<label>输入搜索内容: </label>
<input type="text" name="key">
<input type="submit" name="search" class="btn btn-primary" value="搜索">
</form>
</div>
<hr>
<div align="left" id="news">
{% if blogs %}
<ul>
{% for b in blogs %}
<li>
<a href="/benefiter/blog/{{b}}" target="_blank">
{{b}}
</a>
</li>
{% endfor %}
</ul>
{% endif %}
</div>
</body>
</html>
write.html
是写文章的页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>python+flask博客系统-写文章</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<link rel="shortcut icon" href="https://demosc.chinaz.net/Files/pic/iconsico/8139/h12.ico">
</head>
<body>
<div class="container" align="center">
<label>
本编辑器使用
<a href="https://www.runoob.com/html/html-tutorial.html" target="_blank">
html
</a>
。你可以粘贴你的html到下面或使用
<a href="https://www.w3cschool.cn/tools/index?name=html2markdown" target="_blank">
markdown转为html的服务
</a>
和
<a href="https://pdf.yozocloud.cn/p/pdf2html" target="_blank">
pdf转为html的服务
</a>
。
</label>
<form method="post" action="/benefiter/write">
<label>输入标题</label>
<input name="title" type="text">
<br>
<textarea name="code" rows="24" cols="90" id="html">
输入html代码
</textarea>
<br>
<input name="upload" type="submit" value="发布" class="btn btn-primary">
</form>
</div>
</body>
</html>
app.py
为主要程序:
import uuid
import os
import glob
import difflib
from flask import *
from flask_bootstrap import Bootstrap
from flask_login import LoginManager, UserMixin, login_required, \
logout_user, login_user
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.utils import secure_filename
users = [
{
'username': 'benefit1',
'id': 1,
'password': generate_password_hash('abc')
},
{
'username': 'benefit2',
'id': 2,
'password': generate_password_hash('sea')
},
]
def get_user(username):
for i in users:
if i.get('username') == username:
return i
return None
def create_user(username, password):
users.append(
{'username': username,
'id': uuid.uuid4(),
'password': generate_password_hash(password)}
)
def has_user(username):
for i in users:
if i.get('username') == username:
return True
return False
class User(UserMixin):
def __init__(self, user: dict):
self.username = user.get('username')
self.password_hash = user.get('password')
self.id = user.get('id')
def verify_password(self, password: str):
if self.password_hash is None:
return False
return check_password_hash(self.password_hash, password)
def get_id(self):
return self.id
@staticmethod
def get(user_id):
if not user_id:
return None
for i in users:
if i.get('id') == user_id:
return User(i)
return None
def get_similarity(string1, string2):
return round(difflib.SequenceMatcher(None, string1, string2).quick_ratio(), 3) * 100
app = Flask(__name__)
app.secret_key = os.urandom(24)
app.config['UPLOAD_FOLDER'] = 'static/uploads/'
bootstrap = Bootstrap(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
@login_manager.user_loader
def load_user(user_id):
return User.get(user_id)
@app.route('/benefiter/login')
@app.route('/benefiter/login/')
def login():
return render_template('login.html')
@app.route('/benefiter/login/judge', methods=['POST'])
def judge():
if request.form.get('login'):
username = request.form.get('username')
password = request.form.get('password')
user_info = get_user(username)
if user_info:
user = User(user_info)
if user.verify_password(password):
login_user(user)
return redirect(request.args.get('next') or url_for('index'))
return render_template('login.html', message='用户名或密码有误')
@app.route('/benefiter/login/create')
@app.route('/benefiter/login/create/')
def create():
return render_template('create-user.html')
@app.route('/benefiter/login/create-judge', methods=['POST'])
def create_judge():
if request.form.get('create'):
username = request.form.get('username')
password = request.form.get('password')
if not has_user(username):
create_user(username, password)
with open('static/users.db', 'w', encoding='utf-8') as fp:
fp.write(str(users))
return redirect(url_for('login'))
return render_template('create-user.html', message='账户可能已存在')
@app.route('/benefiter')
@app.route('/benefiter/')
@login_required
def index(message=None):
return render_template('index.html', message=message)
@app.route('/benefiter/logout')
@app.route('/benefiter/logout/')
@login_required
def logout():
logout_user()
return redirect(url_for('login'))
@app.route('/benefiter/write', methods=['GET', 'POST'])
@app.route('/benefiter/write/', methods=['GET', 'POST'])
@login_required
def upload():
if request.method == 'POST':
if request.form.get('upload'):
title = request.form.get('title')
html = request.form.get('code')
if not html:
return redirect(url_for('index', message='html上传失败!'))
if os.path.isfile(f'static/uploads/{title}.html'):
return redirect(url_for('index', message='已有html!'))
try:
with open(f'static/uploads/{title}.html', 'w+',
encoding='utf-8') as fp:
fp.write(html)
except (Exception, Warning):
return redirect(url_for('index', message='html上传失败!'))
return redirect(url_for('index', message='html上传成功!'))
return render_template('write.html')
@app.route('/benefiter/search')
@app.route('/benefiter/search/')
@login_required
def search():
return render_template('search.html', blogs=[])
@app.route('/benefiter/searcher', methods=['POST'])
@app.route('/benefiter/searcher/', methods=['POST'])
@login_required
def searcher():
if request.form.get('search'):
blogs = glob.glob('static/uploads/*.html')
blogs = [i.replace('\\', '/') for i in blogs]
blogs = [i.split('/')[-1] for i in blogs]
blogs = [i.split('.')[0] for i in blogs]
key = request.form.get('key')
blogs = [i for i in blogs if get_similarity(i, key) > 5]
if blogs:
return render_template('search.html', blogs=blogs)
else:
return render_template('search.html', blogs=[])
return render_template('search.html', blogs=[])
@app.route('/benefiter/blog/<blog>')
@app.route('/benefiter/blog/<blog>/')
@login_required
def look_blog(blog):
try:
with open(f'static/uploads/{blog}.html', 'r', encoding='utf-8') as f:
html = f.read()
except (Exception, Warning):
return render_template('error404.html')
return html
@app.route('/benefiter/image/<image>')
@app.route('/benefiter/image/<image>/')
def imager(image):
try:
return send_from_directory('static/images', image)
except (Exception, Warning):
return render_template('error404.html')
@app.errorhandler(404)
def error404(err):
return render_template('error404.html'), 404
if __name__ == '__main__':
app.run(port=9938)