Python实战开发及案例分析(1)——Web开发

        Python 是一种多功能的编程语言,在 Web 开发方面也有广泛的应用,尤其是通过使用 Django 和 Flask 这样的框架。这两种框架各有特点:Django 提供一个全面的、高度集成的 Web 开发体验,而 Flask 则更加轻量级和灵活。

案例分析:使用 Flask 构建一个简单的博客应用

项目背景:构建一个简单的博客应用,允许用户查看文章列表和单篇文章的详细内容。

技术栈

  • Flask:轻量级的 Web 应用框架。
  • SQLite:简单的文件数据库,适用于小型应用。
  • Jinja2:强大的模板引擎,与 Flask 集成提供 HTML 输出的动态数据渲染。
步骤 1: 环境准备和项目结构

        首先,确保安装了 Flask 和相关库。

pip install Flask

项目结构

/myblog
    /static
    /templates
    app.py
    /database
        schema.sql
步骤 2: 创建 Flask 应用和路由
# app.py
from flask import Flask, render_template, request, url_for, redirect

app = Flask(__name__)

# 数据库初始化(简化演示)
def init_db():
    import sqlite3
    conn = sqlite3.connect('database/blog.db')
    with open('database/schema.sql', 'r') as f:
        conn.executescript(f.read())
    conn.commit()
    conn.close()

@app.route('/')
def index():
    conn = sqlite3.connect('database/blog.db')
    cur = conn.cursor()
    cur.execute('SELECT id, title, summary FROM posts')
    posts = cur.fetchall()
    conn.close()
    return render_template('index.html', posts=posts)

@app.route('/post/<int:post_id>')
def post(post_id):
    conn = sqlite3.connect('database/blog.db')
    cur = conn.cursor()
    cur.execute('SELECT title, content FROM posts WHERE id = ?', (post_id,))
    post = cur.fetchone()
    conn.close()
    if post:
        return render_template('post.html', post=post)
    else:
        return render_template('404.html'), 404

if __name__ == '__main__':
    app.run(debug=True)
步骤 3: 创建 HTML 模板

templates/index.html

<!doctype html>
<html>
<head>
    <title>My Blog</title>
</head>
<body>
    <h1>Blog Posts</h1>
    {% for post in posts %}
        <h2><a href="{{ url_for('post', post_id=post[0]) }}">{{ post[1] }}</a></h2>
        <p>{{ post[2] }}</p>
    {% endfor %}
</body>
</html>

templates/post.html

<!doctype html>
<html>
<head>
    <title>{{ post[0] }}</title>
</head>
<body>
    <h1>{{ post[0] }}</h1>
    <p>{{ post[1] }}</p>
</body>
</html>

扩展案例分析:为博客应用增加更多功能

步骤 4: 添加用户认证

项目背景:用户认证是多用户博客系统的基础功能,允许用户注册、登录并进行文章的发布和编辑。

技术栈扩展

  • Flask-Login:用于处理用户登录的 Flask 扩展。
  • Werkzeug:用于密码散列和安全性检查。
pip install flask-login

代码实现

from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from werkzeug.security import generate_password_hash, check_password_hash

app.config['SECRET_KEY'] = 'your_secret_key'

login_manager = LoginManager()
login_manager.init_app(app)

# 用户模型
class User(UserMixin):
    def __init__(self, id, username, password_hash):
        self.id = id
        self.username = username
        self.password_hash = password_hash

# 用户加载
@login_manager.user_loader
def load_user(user_id):
    # 这里应实际查询数据库
    return User(user_id, "User", "password_hash")

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        # 这里应实际查询数据库检查用户名和密码
        user = User(1, username, generate_password_hash(password))
        if user and check_password_hash(user.password_hash, password):
            login_user(user)
            return redirect(url_for('index'))
    return render_template('login.html')

@app.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('index'))

templates/login.html

<!doctype html>
<html>
<head>
    <title>Login</title>
</head>
<body>
    <h1>Login</h1>
    <form method="post">
        <input type="text" placeholder="Username" name="username" required>
        <input type="password" placeholder="Password" name="password" required>
        <button type="submit">Login</button>
    </form>
</body>
</html>
步骤 5: 实现评论功能

项目背景:让读者能对文章进行评论是提高博客互动性的重要功能。

代码实现

# 评论模型(示例简化,实际应有更完善的数据库支持)
class Comment(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.String(1000))
    post_id = db.Column(db.Integer)
    user_id = db.Column(db.Integer)

@app.route('/post/<int:post_id>', methods=['GET', 'POST'])
@login_required
def post(post_id):
    if request.method == 'POST':
        comment_content = request.form['comment']
        comment = Comment(content=comment_content, post_id=post_id, user_id=current_user.id)
        db.session.add(comment)
        db.session.commit()
        return redirect(url_for('post', post_id=post_id))
    # 获取文章和评论
    post = ... # 查询文章详情
    comments = ... # 查询评论列表
    return render_template('post.html', post=post, comments=comments)

        继续扩展我们的Flask博客应用,我们可以进一步增加一些高级功能,比如文章的分类、搜索功能、以及更高级的用户权限管理。这些功能将使我们的博客系统更加完善和专业。

步骤 6: 添加文章分类

项目背景:对博客文章进行分类可以帮助用户更快地找到他们感兴趣的内容。

技术实现

  1. 数据库修改:在数据库中添加一个分类表,并更新文章表以包括分类关联。
  2. 模型更新:在Flask应用中添加对应的模型类。
  3. UI更新:在文章创建和编辑表单中添加分类选项。

代码实现

# 模型定义
class Category(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), unique=True)

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100))
    body = db.Column(db.String(1000))
    category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
    category = db.relationship('Category', backref=db.backref('posts', lazy=True))

# 在创建和编辑博客文章的表单中加入分类选择
@app.route('/new-post', methods=['GET', 'POST'])
@login_required
def new_post():
    if request.method == 'POST':
        title = request.form['title']
        body = request.form['body']
        category_id = request.form['category']
        post = Post(title=title, body=body, category_id=category_id)
        db.session.add(post)
        db.session.commit()
        return redirect(url_for('index'))
    categories = Category.query.all()
    return render_template('new_post.html', categories=categories)

templates/new_post.html

<!doctype html>
<html>
<head>
    <title>New Post</title>
</head>
<body>
    <h1>Create New Post</h1>
    <form method="post">
        <input type="text" placeholder="Title" name="title" required>
        <textarea placeholder="Body" name="body" required></textarea>
        <select name="category">
            {% for category in categories %}
            <option value="{{ category.id }}">{{ category.name }}</option>
            {% endfor %}
        </select>
        <button type="submit">Publish</button>
    </form>
</body>
</html>
步骤 7: 实现搜索功能

项目背景:搜索功能允许用户快速找到他们感兴趣的文章。

技术实现

  1. 搜索逻辑:实现一个简单的基于标题和内容的搜索。
  2. 用户界面:在主页添加一个搜索框。

代码实现

@app.route('/search', methods=['GET'])
def search():
    query = request.args.get('query')
    posts = Post.query.filter(
        Post.title.contains(query) | Post.body.contains(query)
    ).all()
    return render_template('index.html', posts=posts)

templates/index.html(添加搜索框):

<form action="{{ url_for('search') }}" method="get">
    <input type="text" name="query" placeholder="Search...">
    <button type="submit">Search</button>
</form>

结论

(1)通过这个简单的博客应用,我们可以看到 Flask 提供了构建 Web 应用的基础架构,如路由、请求处理和模板渲染。使用 SQLite 作为数据库支持,我们可以轻松地实现数据存储和查询。Flask 是一个灵活而强大的工具,适用于从小型个人项目到大型企业级应用的 Web 开发。它的轻量级和灵活性使开发者能够快速构建原型并根据需求进行扩展。对于更复杂的应用,可能需要更多的配置和第三方库的支持,但 Flask 的简单性使其成为学习和实现 Web 开发的优秀起点。

(2)通过这些扩展,Flask 应用不仅增加了用户认证和评论功能,还提高了整体的交互性和功能性。每个新功能的实现都涉及到后端逻辑和前端显示的修改,展示了如何在实际的 Web 开发项目中逐步构建和扩展应用的能力。这些技能对于任何希望在 Web 开发领域进一步发展的开发者都是非常宝贵的。

(3)通过这些高级功能,我们的Flask博客应用不仅增强了用户体验,还通过分类和搜索提高了内容的可发现性。每个新功能的实现都涉及后端逻辑和前端显示的修改,展示了在实际的Web开发项目中如何逐步构建和扩展应用的能力。这为进一步的功能开发和系统维护打下了坚实的基础。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/589217.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

注册表获取autoCAD安装位置

注意事项 注意&#xff1a;①64位操作系统注册表会重定向&#xff0c;RegOpenKeyEx第4个参数得加上KEY_WOW64_64KEY&#xff1b;②RegOpenKeyEx遍历子项时注意第2和第4参数&#xff0c;参考图&#xff1a; ③RegQueryValueEx同样得注意第6参数 完整代码 std::unordered_map…

Mybatis进阶(映射关系多对一 )

文章目录 1.需求分析2.应用实例&#xff08;xml配置&#xff09;1.数据表设计2.entity设计&#xff08;不要使用toString会栈溢出&#xff09;1.Pet.java2.User.java 3.编写Mapper1.PetMapper.java2.UserMapper.java 4.编写Mapper.xml1.UserMapper.xml2.PetMapper.xml 5.测试Us…

OPPO A72/A55/K7X/A53真我Q3S等手机ROOT刷机后广电卡没信号不读卡解决办法

目前运营商除了移动联通电信以外&#xff0c;还存在1个中国广电&#xff0c;广电属于第四大运营商&#xff0c;由于广电起步较晚&#xff0c;对于手机频段要求也自然不一样&#xff0c;导致目前市面上部分手机出厂没有信号或者不读卡等问题&#xff0c;特别在手机被用户自行刷机…

如何快速的追加文章的内容(在不知道内容的情况下)

首先&#xff0c;需要用到的这个工具&#xff1a; 度娘网盘 提取码&#xff1a;qwu2 蓝奏云 提取码&#xff1a;2r1z 1、打开工具&#xff0c;切换到文章模块下&#xff0c;快捷键&#xff1a;Ctrl1 2、新建一个文章做演示&#xff0c;001 3、添加一个内容&#xff0c;就随…

蚂蚁面试:Springcloud核心组件的底层原理,你知道多少?

尼恩说在前面 在40岁老架构师 尼恩的读者交流群(50)中&#xff0c;最近有小伙伴拿到了一线互联网企业如得物、阿里、滴滴、极兔、有赞、希音、百度、网易、美团、蚂蚁、得物的面试资格&#xff0c;遇到很多很重要的相关面试题&#xff1a; 说说&#xff1a;蚂蚁面试&#xff1…

【Java】HOT100 贪心算法

目录 理论基础 一、简单贪心 LeetCode455&#xff1a;分发饼干 二、中等贪心 2.1 序列问题 LeetCode376&#xff1a;摆动序列 2.2 贪心股票问题 LeetCode121&#xff1a;买卖股票的最佳时机 LeetCode121&#xff1a;买卖股票的最佳时机ii 2.3 两个维度权衡问题 LeetCode135&…

【06016传感器原理与应用】第5章 气敏传感器 期末复习自考复习

第5章 气敏传感器 能够把气体信息变成电信号的装置。 一、学习目的与要求 通过本章的学习&#xff0c;熟悉并掌握气体传感器的工作原理和硬件组成结构。熟练掌握几种电阻式尤其TiO2、SnO2气敏传感器、非电阻式气敏传感器、固体电解质传感器、接触燃烧式气敏传感器的基本原理…

karpathy makemore 3

1 Introduction 这一章&#xff0c;karpathy通过分析参数初始化对模型的收敛的影响作为一个引子&#xff0c;让我们看到神经网络这一个复杂的系统&#xff0c;对grad非常敏感&#xff0c;以及有一些技巧可以解决grad敏感的问题。 2 准备工作 2.1 dataloader import torch b…

DS:顺序表、单链表的相关OJ题训练

欢迎各位来到 Harper.Lee 的学习小世界&#xff01; 博主主页传送门&#xff1a;Harper.Lee的博客主页 想要一起进步的uu可以来后台找我交流哦&#xff01; 在DS&#xff1a;单链表的实现 和 DS&#xff1a;顺序表的实现这两篇文章中&#xff0c;我详细介绍了顺序表和单链表的…

PAT (Advanced Level) - 1047 Student List for Course

模拟 #include <iostream> #include <cstring> #include <algorithm> #include <vector> using namespace std;const int N 40010, M 2510;int n, k; string name[N]; vector<int> list[M];int main() {scanf("%d%d", &n, &…

万万没想到,延缓帕金森病进展的“玄机”竟然就在腿上?【北京仁爱堂】

帕金森病患者的腿部变化&#xff0c;其实可以反应出很多问题。例如行走的变化问题、步态的异常等问题&#xff0c;可以反应病情轻重程度。而通过保持腿部肌肉活动的状态&#xff0c;也可以使帕金森病的症状得到一定的缓解&#xff0c;甚至有助于防止病情恶化。 帕金森病腿部变…

2024年五一数学建模竞赛C题论文首发

基于随机森林的煤矿深部开采冲击地压危险预测 摘要 煤炭作为中国重要的能源和工业原料&#xff0c;其开采活动对国家经济的稳定与发展起着至关重要的作用。本文将使用题目给出的数据探索更为高效的数据分析方法和更先进的监测设备&#xff0c;以提高预警系统的准确性和可靠性…

Photoshop前言

Photoshop前言 分辨率图像格式工具界面组件 分辨率 分辨率是指单位长度内包含的像素点的数量&#xff0c;其单位通常为像素/英寸&#xff08;ppi&#xff09;&#xff0c;300ppi表示每英寸包含300个像素点。对于1英寸1英寸大小的图像&#xff0c;若分辨率为72ppi&#xff0c;则…

基于Pytorch深度学习——多层感知机

本文章来源于对李沐动手深度学习代码以及原理的理解&#xff0c;并且由于李沐老师的代码能力很强&#xff0c;以及视频中讲解代码的部分较少&#xff0c;所以这里将代码进行尽量逐行详细解释 并且由于pytorch的语法有些小伙伴可能并不熟悉&#xff0c;所以我们会采用逐行解释小…

Visio 2021 (64bit)安装教程

Visio 2021 (64bit)安装教程 ​ 通知公告 Visio 2021 (64位) 是一款流程图和图表设计工具,主要用于创建和编辑各种类型的图表和图形。它提供了一个直观的界面和丰富的功能,可以帮助用户快速绘制专业的流程图、组织结构图、网络图、平面图、数据库模型等。 具体来说,Visio 20…

Go 语言数组

Go 语言提供了数组类型的数据结构。 数组是具有相同唯一类型的一组已编号且长度固定的数据项序列&#xff0c;这种类型可以是任意的原始类型例如整型、字符串或者自定义类型。 相对于去声明 number0, number1, ..., number99 的变量&#xff0c;使用数组形式 numbers[0], num…

Spring Cloud——Circuit Breaker上篇

Spring Cloud——Circuit Breaker上篇 一、分布式系统面临的问题1.服务雪崩2.禁止服务雪崩故障 二、Circuit Breaker三、resilience4j——服务熔断和降级1.理论知识2.常用配置3.案例实战&#xff08;1&#xff09;COUNT_BASED&#xff08;计数的滑动窗口&#xff09;&#xff0…

Spring Cloud——OpenFeign

Spring Cloud——OpenFeign 一、OpenFeign能干嘛二、OpenFeign的基本使用三、Feign的高级特性1.OpenFeign超时控制2.OpenFeign重试机制3.OpenFeign之性能优化HttpClient54.OpenFeign请求和响应压缩5.OpenFeign之Feign日志打印 四、参考 OpenFeign是一个声明式的Web服务客户端。…

Android --- 消息机制与异步任务

在Android中&#xff0c;只有在UIThread(主线程)中才能直接更新界面&#xff0c; 在Android中&#xff0c;长时间的工作联网都需要在workThread(分线程)中执行 在分线程中获取服务器数据后&#xff0c;需要立即到主线程中去更新UI来显示数据&#xff0c; 所以&#xff0c;如…

程序员的五大方法论

前言&#xff1a; 最近看了一篇总结程序员学习&#xff0c;晋升方法的文章&#xff0c;颇有感想&#xff0c;决定分享给大家&#xff0c;原文地址&#xff1a;给程序员的5条学习方法论 (qq.com)https://mp.weixin.qq.com/s/xVFlF9qTf9c74Emmdm0DqA 在繁忙的工作中&#xff0c;持…
最新文章