哈喽,大家好!今天给你们带来了通过python flask库来开发出一个完整的个人博客的教程。博客功能包含注册用户,发表内容,审核内容,发表评论,展现内容。现在由于0.1版本可能存在一些问题,比如没有日期,头像等等。
重要!!!全博客只包含三个文件,全部代码加起来不到500行!
使用方法:
首先安装所需库
pip install flask
结构目录
app.py``templates` `---blog.html``static` `---style.css
下面就是完整代码:
app.py
from flask import Flask, render_template, request, redirect, url_for, session``import sqlite3`` ``app = Flask(__name__)``app.secret_key = "my-secret-key"`` ``# 数据库连接及初始化``conn = sqlite3.connect('blog.db',timeout=10, check_same_thread=False)``c = conn.cursor()``c.execute('''CREATE TABLE IF NOT EXISTS users` `(id INTEGER PRIMARY KEY AUTOINCREMENT,` `username TEXT,` `password TEXT)''')``c.execute('''CREATE TABLE IF NOT EXISTS articles` `(id INTEGER PRIMARY KEY AUTOINCREMENT,` `title TEXT,` `content TEXT,` `user_id INTEGER,` `status INTEGER)''')``c.execute('''CREATE TABLE IF NOT EXISTS comments` `(id INTEGER PRIMARY KEY AUTOINCREMENT,` `content TEXT,` `article_id INTEGER,` `user_id INTEGER)''')``conn.commit()`` ``# 辅助函数:从数据库中查询文章列表``def get_articles():` `c.execute("SELECT articles.id, title, content FROM articles WHERE status = 1")` `return c.fetchall()`` ``# 辅助函数:从数据库中查询文章信息和评论列表``def get_article(article_id):` `c.execute(f"SELECT articles.id, title, content FROM articles WHERE id = {article_id} AND status = 1")` `article = c.fetchone()` `if article:` `c.execute(f"SELECT content FROM comments WHERE article_id = {article_id}")` `comments = c.fetchall()` `return article, comments` `else:` `return None, []`` ``# 页面路由:首页``@app.route('/')``def index():` `articles = get_articles()` `return render_template('blog.html', page='index', articles=articles)`` ``# 页面路由:注册页面``@app.route('/register', methods=['GET', 'POST'])``def register():` `if request.method == 'POST':` `username = request.form['username']` `password = request.form['password']` `c.execute(f"INSERT INTO users(username, password) VALUES('{username}', '{password}')")` `conn.commit()` `return redirect(url_for('login'))` `else:` `return render_template('blog.html', page='register')`` ``# 页面路由:登录页面``@app.route('/login', methods=['GET', 'POST'])``def login():` `if request.method == 'POST':` `username = request.form['username']` `password = request.form['password']` `c.execute(f"SELECT * FROM users WHERE username = '{username}' AND password = '{password}'")` `user = c.fetchone()` `if user:` `session['username'] = user[1]` `session['user_id'] = user[0]` `return redirect(url_for('index'))` `else:` `return render_template('blog.html', page='login', error='用户名或密码错误')` `else:` `return render_template('blog.html', page='login')`` ``# 辅助函数:检查用户是否已经登录``def check_login():` `if 'username' not in session:` `return False` `else:` `return True`` ``# 页面路由:发布文章页面``@app.route('/post_article', methods=['GET', 'POST'])``def post_article():` `if not check_login():` `return redirect(url_for('login'))` `if request.method == 'POST':` `title = request.form['title']` `content = request.form['content']` `user_id = session['user_id']` `c.execute(f"INSERT INTO articles(title, content, user_id, status) VALUES('{title}', '{content}', {user_id}, 0)")` `conn.commit()` `return redirect(url_for('index'))` `else:` `return render_template('blog.html', page='post_article')`` ``# 页面路由:文章详情页面及评论``@app.route('/article/<int:article_id>', methods=['GET', 'POST'])``def article(article_id):` `article, comments = get_article(article_id)` `if not article:` `return redirect(url_for('index'))` `if request.method == 'POST':` `if not check_login():` `return redirect(url_for('login'))` `content = request.form['content']` `user_id = session['user_id']` `c.execute(f"INSERT INTO comments(content, article_id, user_id) VALUES('{content}', {article_id}, {user_id})")` `conn.commit()` `return redirect(url_for('article', article_id=article_id))` `else:` `return render_template('blog.html', page='article', article=article, comments=comments)`` ``# 页面路由:注销登录``@app.route('/logout')``def logout():` `session.pop('username', None)` `session.pop('user_id', None)` `return redirect(url_for('index'))`` ``# 页面路由:文章审核页面(需要管理员权限)``@app.route('/approve_article', methods=['GET', 'POST'])``def approve_article():` `if not check_login():` `return redirect(url_for('login'))` `if 'username' in session and session['username'] == 'admin':` `if request.method == 'POST':` `article_id = request.form['article_id']` `action = request.form['action']` `if action == 'approve':` `c.execute(f"UPDATE articles SET status = 1 WHERE id = {article_id}")` `elif action == 'reject':` `c.execute(f"DELETE FROM articles WHERE id = {article_id}")` `conn.commit()` `c.execute("SELECT articles.id, title, content FROM articles WHERE status = 0")` `articles = c.fetchall()` `return render_template('blog.html', page='approve_article', articles=articles)` `else:` `return redirect(url_for('index'))`` ``if __name__ == '__main__':` `app.debug=True` `app.run()
blog.html:
<!DOCTYPE html>``<html>``<head>` `<title>我的博客</title>` `<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">``</head>``<body>` `<header>` `<h1>Python学霸</h1>` `{% if 'username' in session %}` `<p>你好,{{ session['username'] }}</p>` `{% endif %}` `{% if 'username' in session %}` `<li><a href="{{ url_for('logout') }}">退出</a></li>` `{% else %}` `<li><a href="{{ url_for('login') }}">登录</a></li>` `<li><a href="{{ url_for('register') }}">注册</a></li>` `{% endif %}` `{% if 'username' in session %}` `<li><a href="{{ url_for('post_article') }}">发表文章</a></li>` `{% endif %}` `{% if 'username' in session and session['username'] == 'admin' %}` `<li><a href="{{ url_for('approve_article') }}">审核文章</a></li>` `{% endif %}` `<nav>` `<ul>` `<li><a href="{{ url_for('index') }}">首页</a></li>` `</ul>` `</nav>` `</header>`` ` `<section>` `{% if page == 'index' %}` `<h2>最新文章</h2>` `{% for article in articles %}` `<div class="article">` `<h3><a href="{{ url_for('article', article_id=article[0]) }}">{{ article[1] }}</a></h3>` `<p>{{ article[2] }}</p>` `</div>` `{% endfor %}` `{% elif page == 'register' %}` `<h2>注册</h2>` `<form action="{{ url_for('register') }}" method="post">` `<label for="username">用户名:</label>` `<input type="text" id="username" name="username" required>` `<label for="password">密码:</label>` `<input type="password" id="password" name="password" required>` `<input type="submit" value="注册">` `</form>` `{% elif page == 'login' %}` `<h2>登录</h2>` `<form action="{{ url_for('login') }}" method="post">` `<label for="username">用户名:</label>` `<input type="text" id="username" name="username" required>` `<label for="password">密码:</label>` `<input type="password" id="password" name="password" required>` `<input type="submit" value="登录">` `{% if error %}` `<p class="error">{{ error }}</p>` `{% endif %}` `</form>` `{% elif page == 'post_article' %}` `{% if 'username' in session %}` `<h2>发表文章</h2>` `<form action="{{ url_for('post_article') }}" method="post">` `<label for="title">标题:</label>` `<input type="text" id="title" name="title" required>` `<label for="content">内容:</label>` `<textarea id="content" name="content" rows="5" required></textarea>` `<input type="submit" value="发表">` `</form>` `{% else %}` `<p>请先登录再发表文章。</p>` `{% endif %}` `{% elif page == 'article' %}` `<h2>{{ article[1] }}</h2>` `<p>{{ article[2] }}</p>` `{% if 'username' in session %}` `<h3>发表评论</h3>` `<form action="{{ url_for('article', article_id=article[0]) }}" method="post">` `<textarea id="content" name="content" rows="3" required></textarea>` `<input type="submit" value="提交">` `</form>` `{% else %}` `<p>请先登录再发表评论。</p>` `{% endif %}` `{% for comment in comments %}` `<div class="comment">` `<p>{{ comment[0] }}</p>` `</div>` `{% endfor %}` `{% elif page == 'approve_article' %}` `{% if 'username' in session and session['username'] == 'admin' %}` `<h2>审核文章</h2>` `<ul>` `{% for article in articles %}` `<li>` `<h3>{{ article[1] }}</h3>` `<p>{{ article[2] }}</p>` `<form action="{{ url_for('approve_article') }}" method="post">` `<input type="hidden" name="article_id" value="{{ article[0] }}">` `<input type="radio" name="action" value="approve" required> 审核通过` `<input type="radio" name="action" value="reject"> 拒绝审核` `<input type="submit" value="提交">` `</form>` `</li>` `{% endfor %}` `</ul>` `{% else %}` `<p>你没有权限访问该页面。</p>` `{% endif %}` `{% endif %}` `</section>`` ` `<footer>` `<p>© {{ year }} Python学霸,保留所有权利。</p>` `</footer>``</body>``</html>
style.css:
html, body {` `height: 100%;` `margin: 0;` `padding: 0;` `font-family: Arial, sans-serif;``}`` ``body {` `display: flex;` `flex-direction: column;` `padding-left: 50px;`` padding-right: 50px;``}`` ``header {` `background-color: #556c86;` `color: #fff;` `padding: 20px;``}`` ``h1 {` `margin: 0;``}`` ``nav ul {` `list-style-type: none;` `margin: 0;` `padding: 0;``}`` ``nav ul li {` `display: inline-block;` `margin-right: 10px;``}`` ``nav ul li a {` `color: #fff;` `text-decoration: none;``}`` ``.article {` `background-color: #f5f5f5;` `margin-bottom: 20px;` `padding: 20px;``}`` ``.article h3 {` `margin: 0;``}`` ``.comment {` `background-color: #f5f5f5;` `padding: 10px;` `margin-bottom: 10px;``}` `a {` `color: #000;` `text-decoration: none;``}``section {` `padding: 2rem;``}`` ``section h2 {` `font-size: 2rem;` `margin-bottom: 1.5rem;``}`` ``section h3 {` `margin-bottom: 1rem;` `font-size: 1.5rem;``}`` ``/* Form styles */`` ``form {` `margin-bottom: 1rem;``}`` ``label {` `display: block;` `margin-bottom: 0.5rem;` `font-weight: 700;``}`` ``input[type="text"], input[type="password"], textarea {` `width: 100%;` `padding: 0.5rem;` `margin-bottom: 1rem;` `border: 1px solid #ced4da;` `border-radius: 0.25rem;``}`` ``input[type="submit"], input[type="button"] {` `background-color: #007bff;` `color: #fff;` `padding: 0.5rem 1rem;` `border: none;` `border-radius: 0.25rem;` `cursor: pointer;` `font-size: 1.2rem;``}``input[type="submit"]:hover, input[type="button"]:hover {` `opacity: 0.8;``}`` ``textarea {` `resize: vertical;` `min-height: 10rem;``}`` ``footer {` `color: #000;` `padding: 10px;` `text-align: center;` `margin-top: auto;``}
以上就是“Python极限挑战——开发出Flask个人博客”的全部内容,希望对你有所帮助。
关于Python技术储备
学好 Python 不论是就业还是做副业赚钱都不错,但要学会 Python 还是要有一个学习规划。最后大家分享一份全套的 Python 学习资料,给那些想学习 Python 的小伙伴们一点帮助!
一、Python所有方向的学习路线
Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。
二、Python必备开发工具
三、Python视频合集
观看零基础学习视频,看视频学习是最快捷也是最有效果的方式,跟着视频中老师的思路,从基础到深入,还是很容易入门的。
四、实战案例
光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。
五、Python练习题
检查学习结果。
六、面试资料
我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。
最后祝大家天天进步!!
上面这份完整版的Python全套学习资料已经上传至优快云官方,朋友如果需要可以直接微信扫描下方优快云官方认证二维码免费领取【保证100%免费】。