Flask 框架入门:快速搭建个人博客网站

Python3.8

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

Flask 框架入门:快速搭建个人博客网站

Flask 是一个轻量级 Python Web 框架,适合快速开发小型应用。下面分步指导搭建基础博客网站:


1. 环境准备

安装必要依赖:

pip install flask flask-sqlalchemy flask-wtf


2. 项目结构

创建基础目录:

/blog
  ├── app.py          # 主程序
  ├── templates/      # HTML模板
  ├── static/         # CSS/JS文件
  └── models.py       # 数据模型


3. 数据模型(models.py)

使用 SQLite 存储博客文章:

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100))
    content = db.Column(db.Text)
    created_at = db.Column(db.DateTime, default=datetime.now)


4. 主程序(app.py)

初始化应用和路由:

from flask import Flask, render_template, request, redirect
from models import db, Post

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db'
app.config['SECRET_KEY'] = 'your_secret_key'
db.init_app(app)

@app.route('/')
def index():
    posts = Post.query.all()
    return render_template('index.html', posts=posts)

@app.route('/create', methods=['GET', 'POST'])
def create_post():
    if request.method == 'POST':
        title = request.form['title']
        content = request.form['content']
        new_post = Post(title=title, content=content)
        db.session.add(new_post)
        db.session.commit()
        return redirect('/')
    return render_template('create.html')


5. 模板文件

templates/index.html(首页):

<!DOCTYPE html>
<html>
<head>
    <title>我的博客</title>
</head>
<body>
    <h1>最新文章</h1>
    {% for post in posts %}
        <div>
            <h2>{{ post.title }}</h2>
            <p>{{ post.content[:100] }}...</p>
            <small>{{ post.created_at }}</small>
        </div>
    {% endfor %}
    <a href="/create">写新文章</a>
</body>
</html>

templates/create.html(创建页):

<form method="POST">
    <input type="text" name="title" placeholder="标题" required>
    <textarea name="content" placeholder="内容" required></textarea>
    <button type="submit">发布</button>
</form>


6. 启动应用

在终端运行:

export FLASK_APP=app.py
flask run

访问 http://localhost:5000 即可查看博客


7. 功能扩展建议
  • 用户认证:添加 flask-login 实现登录
  • 样式美化:在 static/ 添加 CSS 文件
  • 分页功能:使用 paginate = Post.query.paginate(page=1, per_page=5)
  • 部署上线:推荐使用 Heroku 或 PythonAnywhere

提示:开发时启用调试模式:

if __name__ == '__main__':
    app.run(debug=True)

通过这个基础框架,您可以在 30 分钟内搭建可运行的博客原型,后续可根据需求逐步扩展功能。

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值