用 Flask 打造高可用 REST API:从环境搭建到 PUT/DELETE 全栈实战

作者:API传播员 · 2025-11-07 · 阅读时间:6分钟

全球各地的开发者都在寻找快速高效的方法来构建功能强大的应用程序编程接口API),Python开发者也不例外。随着 Web 应用开发的兴起以及对可扩展后端服务需求的增加,掌握构建 REST API 的核心技能变得尤为重要。

本文将通过使用 Flask 这一轻量级 Python Web 框架,向您展示如何构建动态的 REST API。通过本指南,您不仅可以学习到不同 HTTP 方法的使用,还能掌握如何遵循 RESTful 设计原则来开发满足实际需求的 API 🚀。

💡 想让指标可衡量、团队节奏更透明?「开发任务管理系统 KPI」提示词可帮你基于 AI 超级提示词,快速制定与业务成果对齐的 KPI,兼顾用户参与度与交付质量!


一、为什么选择 Flask?🤔

  • 轻量级:最小核心,自由组合扩展
  • 生态丰富:SQLAlchemy、Marshmallow、JWT 等插件即插即用
  • 开发友好:自动重载、调试器、简洁路由装饰器
  • 生产就绪:Gunicorn + Nginx 轻松部署

二、环境准备 & 项目骨架 ⚙️

# 1. 创建虚拟环境
python -m venv venv
source venv/bin/activate      # Linux/macOS
venv\Scripts\activate         # Windows

# 2. 安装 Flask
pip install flask

🛠️ 写完依赖别忘了跑「代码优化」提示词,一键诊断慢查询与重复请求,让接口响应提速 30 %!

目录结构:

flask_books_api/
├── app.py
└── venv/

三、Hello Flask —— 最小可运行实例 ✨

# app.py
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return {"message": "你好,世界!"}

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

启动:

python app.py
# 浏览器访问 http://127.0.0.1:5000

四、RESTful 设计 & HTTP 方法回顾 📡

方法 语义 示例端点 用途
GET 读取 /books 获取集合
POST 创建 /books 新增资源
PUT 全量更新 /books/:title 替换资源
DELETE 删除 /books/:title 删除资源

五、实现 CRUD —— 以“图书”为例 📚

① 内存数据模型

books = []

② GET /books —— 获取全部

from flask import jsonify

@app.route('/books', methods=['GET'])
def get_books():
    return jsonify({'books': books})

③ POST /books —— 新增图书

from flask import request

@app.route('/books', methods=['POST'])
def add_book():
    new_book = request.get_json()
    books.append(new_book)
    return jsonify({'message': '书籍添加成功!'}), 201

④ PUT /books/ —— 更新图书</h3> <pre><code class="language-python">@app.route('/books/<string:title>', methods=['PUT']) def update_book(title): for book in books: if book['title'] == title: book['author'] = request.json.get('author', book['author']) book['read'] = request.json.get('read', book['read']) return jsonify({'message': '书籍更新成功!'}) return jsonify({'message': '书籍未找到!'}), 404</code></pre> <h3>⑤ DELETE /books/<title> —— 删除图书</h3> <pre><code class="language-python">@app.route('/books/<string:title>', methods=['DELETE']) def delete_book(title): global books books = [b for b in books if b['title'] != title] return jsonify({'message': '书籍删除成功!'})</code></pre> <hr /> <h2 id="title-5">六、Postman 测试全流程 🔍</h2> <ol> <li> <p><strong>POST 添加书</strong><br /> URL: <code>http://127.0.0.1:5000/books</code><br /> Body (JSON):</p> <pre><code class="language-json">{ "title": " Flask 入门", "author": "李雷", "read": true }</code></pre> <p>➜ 返回 201 + 成功消息</p> </li> <li> <p><strong>GET 查询全部</strong><br /> ➜ 返回书籍列表</p> </li> <li> <p><strong>PUT 修改作者</strong><br /> URL: <code>http://127.0.0.1:5000/books/Flask%20入门</code><br /> Body:</p> <pre><code class="language-json">{ "author": "韩梅梅", "read": false }</code></pre> </li> <li> <p><strong>DELETE 删除</strong><br /> ➜ 返回成功提示</p> </li> </ol> <blockquote> <p>📖 想给前端同事一份秒懂的接口文档?「<a href="https://prompts.explinks.com/standard_code_docs?from=explinks&sulg=build-powerful-rest-api-with-flask">代码文档生成器</a>」可自动生成标准化字段描述、请求/响应示例与错误码,让协作零阻力!</p> </blockquote> <hr /> <h2 id="title-6">七、进阶:分页、异常处理、蓝图(Bonus)⚡</h2> <pre><code class="language-python">from flask import abort, Blueprint api_bp = Blueprint('books', __name__, url_prefix='/api/v1') @api_bp.route('/books') def get_books_paged(): page = int(request.args.get('page', 1)) limit = int(request.args.get('limit', 5)) start = (page-1)*limit return jsonify(books[start:start+limit]) @api_bp.errorhandler(404) def resource_not_found(e): return jsonify(error=str(e)), 404 # 在工厂函数注册蓝图 app.register_blueprint(api_bp)</code></pre> <hr /> <h2 id="title-7">八、常见疑问 ❓</h2> <p><strong>Q1. 如何切换成数据库?</strong><br /> → 使用 SQLAlchemy + Flask-Migrate,模型替换内存列表即可</p> <p><strong>Q2. 如何实现 JWT 登录?</strong><br /> → 安装 <code>PyJWT</code>,登录后返回 token,后续请求在 Header 携带 <code>Authorization: Bearer <token></code></p> <p><strong>Q3. 怎样写单元测试?</strong><br /> → 使用 <code>pytest</code> 或内置 <code>unittest</code>,利用 <code>app.test_client()</code> 模拟请求</p> <blockquote> <p>🔍 上线前最后一步:跑「<a href="https://prompts.explinks.com/code_review_assistant?from=explinks&sulg=build-powerful-rest-api-with-flask">代码审查助手</a>」,自动捕捉潜在漏洞、性能隐患与风格问题,给出可执行反馈,确保 API 稳如磐石!</p> </blockquote> <hr /> <h2 id="title-8">九、总结 & 下一步 🏁</h2> <p>通过本教程,你已掌握:</p> <ul> <li>✅ Flask 环境搭建与最小运行实例</li> <li>✅ GET/POST/PUT/DELETE 全栈实现</li> <li>✅ Postman 手动测试流程</li> <li>✅ 蓝图、异常处理、分页等进阶技巧</li> </ul> <p>先用「<a href="https://prompts.explinks.com/code_generator_function?from=explinks&sulg=build-powerful-rest-api-with-flask">代码生成</a>」快速产出 SDK 与错误重试逻辑,再用 KPI 面板持续监控接口延迟、测试覆盖率与线上错误率,你的 Flask API 将更快、更稳地抢占市场 🚀!</p> <p>原文链接: <a href="https://www.explinks.com/links/d219dc8ca05b688fb85fdad618cd0376/?goto=https%3A%2F%2Finfinitysofthint.com%2Fblog%2Fbuild-powerful-rest-api-with-flask%2F" target="_blank" rel="nofollow">https://infinitysofthint.com/blog/build-powerful-rest-api-with-flask/</a></p> </span> </div> </div> </div> <!-- 右侧边栏通过sidebar.php引入 --> <div class="md:w-1/4 flex-shrink-0"> <div id="blog_content_top" style="padding-top: 120px;margin-top: -120px;"></div> <!-- 右侧边栏 --> <div class="w-full lg:w-full flex-shrink-0 space-y-6"> <!-- API精选广告 --> <div class="ad-box h-[160px] flex flex-col justify-center relative group" style="background: linear-gradient(135deg, #4f46e5, #3b82f6);"> <div class="absolute top-3 right-3 bg-yellow-400 text-xs text-gray-900 px-2 py-1 rounded-full font-bold">热门推荐</div> <div class="font-medium text-white text-center z-10 relative"> <div class="text-base font-bold mb-1">一个账号试用1000+ API</div> <div class="text-xs text-blue-100 mb-2">助力AI无缝链接物理世界 · 无需多次注册</div> <button type="button" class="bg-white text-blue-600 hover:bg-blue-50 px-3 py-1.5 rounded-full text-xs font-bold transition-all duration-300 transform hover:scale-105" onclick="window.location.href='https://www.explinks.com/apihub'"> 免费开始试用 → </button> </div> <div class="absolute inset-0 opacity-20"></div> </div> <!-- API提升广告 --> <div class="ad-box flex flex-col items-center justify-center h-[160px] relative overflow-hidden" style="background: linear-gradient(135deg, #8b5cf6, #6d28d9);"> <div class="z-10 relative text-center"> <div class="font-bold text-white text-base mb-1">3000+提示词助力AI大模型</div> <div class="text-xs text-blue-100 mb-2">和专业工程师共享工作效率翻倍的秘密</div> <button type="button" class="bg-yellow-400 hover:bg-yellow-300 text-gray-900 px-3 py-1 rounded-md text-xs font-bold transition-all duration-300 transform hover:scale-105" onclick="window.location.href='https://prompts.explinks.com/'"> 先免费试用、用好了再买 → </button> </div> <div class="absolute bottom-0 right-0"> <svg width="120" height="80" viewBox="0 0 120 80" fill="none" xmlns="http://www.w3.org/2000/svg" class="opacity-30"> <circle cx="100" cy="60" r="50" fill="rgba(255,255,255,0.2)"></circle> <circle cx="70" cy="50" r="30" fill="rgba(255,255,255,0.15)"></circle> </svg> </div> </div> <!-- 热门API --> <div class="mb-8 bg-white border border-gray-200 rounded-lg p-4 shadow-sm" style="background-color: #F9FAFBFF"> <h3 class="sidebar-title font-bold text-sm mb-3">热门API</h3> <ul class="space-y-1.5 pl-2 text-xs" style="line-height: 1.4rem;font-size: 0.875rem;"> <li class="text-gray-600">1. <a href="https://www.explinks.com/api/ai_text_generation" target="_blank" class="text-gray-600 hover:text-blue-500 text-sm" style="margin-left: 5px;">AI文本生成</a></li> <li class="text-gray-600">2. <a href="https://www.explinks.com/api/ai_text_to_image" target="_blank" class="text-gray-600 hover:text-blue-500 text-sm" style="margin-left: 5px;">AI图片生成_文生图</a></li> <li class="text-gray-600">3. <a href="https://www.explinks.com/api/ai_image_to_image" target="_blank" class="text-gray-600 hover:text-blue-500 text-sm" style="margin-left: 5px;">AI图片生成_图生图</a></li> <li class="text-gray-600">4. <a href="https://www.explinks.com/api/ai_image_edit" target="_blank" class="text-gray-600 hover:text-blue-500 text-sm" style="margin-left: 5px;">AI图像编辑</a></li> <li class="text-gray-600">5. <a href="https://www.explinks.com/api/ai_text_to_video" target="_blank" class="text-gray-600 hover:text-blue-500 text-sm" style="margin-left: 5px;">AI视频生成_文生视频</a></li> <li class="text-gray-600">6. <a href="https://www.explinks.com/api/ai_image_to_video" target="_blank" class="text-gray-600 hover:text-blue-500 text-sm" style="margin-left: 5px;">AI视频生成_图生视频</a></li> <li class="text-gray-600">7. <a href="https://www.explinks.com/api/ai_text_to_speech" target="_blank" class="text-gray-600 hover:text-blue-500 text-sm" style="margin-left: 5px;">AI语音合成_文生语音</a></li> <li class="text-gray-600">8. <a href="https://www.explinks.com/api/ai_cn_text_generation" target="_blank" class="text-gray-600 hover:text-blue-500 text-sm" style="margin-left: 5px;">AI文本生成(中国)</a></li> </ul> </div> <!-- 最新文章 #f1f5f9; #edf6ff;--> <div class="bg-white border border-gray-200 rounded-lg p-4 shadow-sm" style="background-color: #F9FAFBFF"> <h3 class="sidebar-title font-bold text-sm mb-3">最新文章</h3> <ul class="space-y-2 pl-2" style="line-height: 1.4rem;font-size: 0.875rem;"> <li class="flex "> <!-- <svg class="w-4 h-4 text-blue-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" style="margin-top: 5px;"> --> <!-- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 9l3 3m0 0l-3 3m3-3H8m13 0a9 9 0 11-18 0 9 9 0 0118 0z"></path> --> <!-- </svg> --> <a href="https://www.explinks.com/blog/api-documentation-guide-tool/" class="text-gray-600 hover:text-blue-500 block"> API文档:深入指南与前沿免费工具 – Apidog </a> </li> <li class="flex "> <!-- <svg class="w-4 h-4 text-blue-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" style="margin-top: 5px;"> --> <!-- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 9l3 3m0 0l-3 3m3-3H8m13 0a9 9 0 11-18 0 9 9 0 0118 0z"></path> --> <!-- </svg> --> <a href="https://www.explinks.com/blog/numpy-implementation-of-cross-entropy-from-theory-to-practice/" class="text-gray-600 hover:text-blue-500 block"> 交叉熵的Numpy实现:从理论到实践 </a> </li> <li class="flex "> <!-- <svg class="w-4 h-4 text-blue-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" style="margin-top: 5px;"> --> <!-- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 9l3 3m0 0l-3 3m3-3H8m13 0a9 9 0 11-18 0 9 9 0 0118 0z"></path> --> <!-- </svg> --> <a href="https://www.explinks.com/blog/google-deepmind-genie-3-shopify-3d-showroom-2h-launch-guide/" class="text-gray-600 hover:text-blue-500 block"> Google DeepMind发布 Genie 3与Shopify:2小时上线电商3D样板间实战 </a> </li> <li class="flex "> <!-- <svg class="w-4 h-4 text-blue-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" style="margin-top: 5px;"> --> <!-- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 9l3 3m0 0l-3 3m3-3H8m13 0a9 9 0 11-18 0 9 9 0 0118 0z"></path> --> <!-- </svg> --> <a href="https://www.explinks.com/blog/yt-gemini-deep-research-technology-practice/" class="text-gray-600 hover:text-blue-500 block"> Gemini Deep Research 技术实战:利用 Gemini Advanced API 构建自动化的深度研究 Agent </a> </li> <li class="flex "> <!-- <svg class="w-4 h-4 text-blue-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" style="margin-top: 5px;"> --> <!-- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 9l3 3m0 0l-3 3m3-3H8m13 0a9 9 0 11-18 0 9 9 0 0118 0z"></path> --> <!-- </svg> --> <a href="https://www.explinks.com/blog/yt-complete-guide-to-using-flux/" class="text-gray-600 hover:text-blue-500 block"> FLUX.1 Kontext API 使用完全指南:解锁文本驱动的智能图像编辑 </a> </li> <li class="flex "> <!-- <svg class="w-4 h-4 text-blue-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" style="margin-top: 5px;"> --> <!-- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 9l3 3m0 0l-3 3m3-3H8m13 0a9 9 0 11-18 0 9 9 0 0118 0z"></path> --> <!-- </svg> --> <a href="https://www.explinks.com/blog/yt-how-to-prevent-user-agent-spoofing-in-api-requests/" class="text-gray-600 hover:text-blue-500 block"> 如何防范User-Agent信息伪装引发的API访问风险 </a> </li> <li class="flex "> <!-- <svg class="w-4 h-4 text-blue-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" style="margin-top: 5px;"> --> <!-- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 9l3 3m0 0l-3 3m3-3H8m13 0a9 9 0 11-18 0 9 9 0 0118 0z"></path> --> <!-- </svg> --> <a href="https://www.explinks.com/blog/yq-ua-apple-payment-process-a-beginners-guide-to-integration/" class="text-gray-600 hover:text-blue-500 block"> 苹果支付流程:从零开始的接入指南 </a> </li> <li class="flex "> <!-- <svg class="w-4 h-4 text-blue-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" style="margin-top: 5px;"> --> <!-- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 9l3 3m0 0l-3 3m3-3H8m13 0a9 9 0 11-18 0 9 9 0 0118 0z"></path> --> <!-- </svg> --> <a href="https://www.explinks.com/blog/yt-openapi-guide-define-generate-integrate/" class="text-gray-600 hover:text-blue-500 block"> 全面掌握 OpenAPI 规范:定义、生成与集成指南 </a> </li> <li class="flex "> <!-- <svg class="w-4 h-4 text-blue-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" style="margin-top: 5px;"> --> <!-- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 9l3 3m0 0l-3 3m3-3H8m13 0a9 9 0 11-18 0 9 9 0 0118 0z"></path> --> <!-- </svg> --> <a href="https://www.explinks.com/blog/understanding-granularity-meaning-in-chinese/" class="text-gray-600 hover:text-blue-500 block"> 深入解析granularity是什么?颗粒度中文详解 </a> </li> <li class="flex "> <!-- <svg class="w-4 h-4 text-blue-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" style="margin-top: 5px;"> --> <!-- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 9l3 3m0 0l-3 3m3-3H8m13 0a9 9 0 11-18 0 9 9 0 0118 0z"></path> --> <!-- </svg> --> <a href="https://www.explinks.com/blog/how-developers-can-use-caching-to-improve-api-performance/" class="text-gray-600 hover:text-blue-500 block"> 开发者如何利用缓存技术提升API性能 </a> </li> <li class="flex "> <!-- <svg class="w-4 h-4 text-blue-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" style="margin-top: 5px;"> --> <!-- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 9l3 3m0 0l-3 3m3-3H8m13 0a9 9 0 11-18 0 9 9 0 0118 0z"></path> --> <!-- </svg> --> <a href="https://www.explinks.com/blog/why-orbitz-api-is-essential-for-travel-agencies-techno-softwares-can-help-you-build-the-hotel-booking-system/" class="text-gray-600 hover:text-blue-500 block"> Orbitz API 全攻略:旅行社高效整合酒店、航班与租车服务的必读指南 </a> </li> <li class="flex "> <!-- <svg class="w-4 h-4 text-blue-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" style="margin-top: 5px;"> --> <!-- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 9l3 3m0 0l-3 3m3-3H8m13 0a9 9 0 11-18 0 9 9 0 0118 0z"></path> --> <!-- </svg> --> <a href="https://www.explinks.com/blog/the-ultimate-guide-to-rest-api-naming-convention/" class="text-gray-600 hover:text-blue-500 block"> REST API命名规范的终极指南:清晰度和一致性的最佳实践 </a> </li> </ul> </div> </div> <!-- 固定广告位 --> <div id="latest-articles" style="margin: 20px;"></div> <div id="floating-ad" class="w-full lg:w-full flex-shrink-0 space-y-6" style="position: -webkit-sticky;position: sticky;top: 80px;"> <!-- index --> <div class="blog_detail_index_show" style="margin-top: 30px;"> <div class="hot_article_title"> 内容目录 </div> <div class="article-index" style="margin-top: 10px;"> <ol id="toc-content" class="space-y-3 text-gray-700 index-ol"><li class="flex items-center"><a href="#title-0" title="一、为什么选择 Flask?🤔">一、为什么选择 Flask?🤔</a></li><li class="flex items-center"><a href="#title-1" title="二、环境准备 & 项目骨架 ⚙️">二、环境准备 & 项目骨架 ⚙️</a></li><li class="flex items-center"><a href="#title-2" title="三、Hello Flask —— 最小可运行实例 ✨">三、Hello Flask —— 最小可运行实例 ✨</a></li><li class="flex items-center"><a href="#title-3" title="四、RESTful 设计 & HTTP 方法回顾 📡">四、RESTful 设计 & HTTP 方法回顾 📡</a></li><li class="flex items-center"><a href="#title-4" title="五、实现 CRUD —— 以“图书”为例 📚">五、实现 CRUD —— 以“图书”为例 📚</a></li><li class="flex items-center"><a href="#title-5" title="六、Postman 测试全流程 🔍">六、Postman 测试全流程 🔍</a></li><li class="flex items-center"><a href="#title-6" title="七、进阶:分页、异常处理、蓝图(Bonus)⚡">七、进阶:分页、异常处理、蓝图(Bonus)⚡</a></li><li class="flex items-center"><a href="#title-7" title="八、常见疑问 ❓">八、常见疑问 ❓</a></li><li class="flex items-center"><a href="#title-8" title="九、总结 & 下一步 🏁">九、总结 & 下一步 🏁</a></li></ol> </div> </div> <!-- top --> <div> <div style="font-size: 14px;margin: 20px 0 0 0;"><a href="#blog_content_top" style="color: #64baf8;">返回顶部</a></div> </div> </div> </div> </div> <!-- 相关文章区域 --> <div class="content-bottom"> <!-- 上一篇下一篇导航 --> <div class="flex justify-between items-center py-6 border-t border-b border-gray-200 my-8"> <a href="https://www.explinks.com/blog/index-html/" class="flex items-center text-blue-600 hover:text-blue-800 transition-colors"> <iconify-icon icon="mdi:arrow-left" width="20" height="20" class="mr-2"></iconify-icon> <div> <div class="text-xs text-gray-500">上一篇</div> <div class="font-medium">Python 搭建 HTTP 服务器速成指南:从 `http.server` 到 Flask,顺带搞定静态资源与模板渲染!</div> </div> </a> <a href="https://www.explinks.com/blog/looking-at-java-22-class-file-api-a4cb241ff785/" class="flex items-center text-blue-600 hover:text-blue-800 transition-colors text-right"> <div> <div class="text-xs text-gray-500">下一篇</div> <div class="font-medium">深入探讨Java 22:Class-File API | 作者:Ben Weidig - Medium</div> </div> <iconify-icon icon="mdi:arrow-right" width="20" height="20" class="ml-2"></iconify-icon> </a> </div> <!-- 相关文章区域 --> </div> </div> <!-- 页脚 --> <footer class="footer"> <div class="container py-6 text-xs"> <div class="flex justify-between"> <div> <div class="flex flex-wrap gap-3"> <a href="https://www.explinks.com/apihub" rel="noopener" class="hotlink">API大全</a> <a href="https://www.explinks.com/" rel="noopener" class="hotlink">API平台</a> <a href="https://www.explinks.com/" rel="noopener" class="hotlink">API集成平台</a> <a href="https://prompts.explinks.com/" rel="noopener" class="hotlink">提示词模板</a> <a href="https://prompts.explinks.com/" rel="noopener" class="hotlink">AI提示词</a> <a href="https://prompts.explinks.com/" rel="noopener" class="hotlink">AI提示词商城</a> <a href="https://prompts.explinks.com/" rel="noopener" class="hotlink">提示词网站</a> <a href="https://prompts.explinks.com/" rel="noopener" class="hotlink">prompt模板</a> <a href="https://prompts.explinks.com/search/?ai_model=DeepSeek" rel="noopener" class="hotlink">deepseek提示词</a> <a href="https://prompts.explinks.com/search?ai_ability=text_to_image" rel="noopener" class="hotlink">文生图提示词</a> <a href="https://www.explinks.com/" rel="noopener" class="hotlink">API市场</a> <a href="https://www.explinks.com/" rel="noopener" class="hotlink">API商城</a> </div> <div class="flex flex-wrap gap-3" style="margin-top: 10px;"> <a href="https://www.explinks.com/company/about" rel="noopener" class="hotlink">关于我们</a> <a href="https://www.explinks.com/company/joinus" rel="noopener" class="hotlink">招聘</a> <a href="https://www.explinks.com/company/service-agreemen" rel="noopener" class="hotlink">服务条款</a> <a href="https://www.explinks.com/company/privacy-policy" rel="noopener" class="hotlink">隐私协议</a> <a href="https://www.explinks.com/sitemap.xml" rel="noopener" class="hotlink">网站地图</a> </div> </div> <div class="text-right"> <div>Copyright © 2025 All Rights Reserved 北京高梵爱科科技有限公司</div> <div>公司地址:北京市海淀区中关村南大街5号</div> <div>增值电信业务经营许可证:京ICP-20190888 京ICP备19054249号-7</div> <div>意见反馈: 010-53326693 myf@gaofan.com</div> </div> </div> </div> </footer> <style> @media (min-width: 1536px) { .container { max-width: 1280px; } } h2 { position: relative; } h2::before { content: ""; display: block; width: 100%; margin-bottom: 15px; margin-top: 15px; border-top: 2px dashed #ccc; } .content-area h2{ border-bottom: 0px; } .markdown-body pre code{ white-space: pre; display: block; overflow-x: auto; } </style> <script> document.addEventListener('DOMContentLoaded', function() { // 悬浮广告控制 const floatingAd = document.getElementById('floating-ad'); const latestArticles = document.getElementById('latest-articles'); // 监听滚动事件 window.addEventListener('scroll', function() { const latestArticlesPosition = latestArticles.getBoundingClientRect().bottom; //const viewportHeight = window.innerHeight; const viewportHeight = 180; // 当最新文章底部进入视口时显示广告 if (latestArticlesPosition <= viewportHeight) { floatingAd.style.display = 'block'; } else { floatingAd.style.display = 'none'; } }); const toggleButton = document.getElementById('toggle-toc'); const tocContent = document.getElementById('toc-content'); toggleButton.addEventListener('click', function() { if (tocContent.style.display === 'none') { tocContent.style.display = 'block'; } else { tocContent.style.display = 'none'; } }); // 收藏功能 const favoriteBtn = document.getElementById('favorite-btn'); // 检查是否已收藏 const checkIfFavorited = () => { const favorites = JSON.parse(localStorage.getItem('favorites') || '[]'); const currentUrl = window.location.href; const currentTitle = document.title; const isFavorited = favorites.some(item => item.url === currentUrl); if (isFavorited) { favoriteBtn.classList.add('favorited'); favoriteBtn.querySelector('iconify-icon').setAttribute('icon', 'mdi:star-filled'); favoriteBtn.querySelector('span').textContent = '已收藏'; favoriteBtn.style.backgroundColor = '#facc15'; // 黄色背景 } else { favoriteBtn.classList.remove('favorited'); favoriteBtn.querySelector('iconify-icon').setAttribute('icon', 'mdi:star'); favoriteBtn.querySelector('span').textContent = '收藏'; favoriteBtn.style.backgroundColor = '#3b82f6'; // 恢复蓝色背景 } }; // 初始检查收藏状态 checkIfFavorited(); // 添加收藏点击事件 favoriteBtn.addEventListener('click', function() { const currentUrl = window.location.href; const currentTitle = document.title; const favorites = JSON.parse(localStorage.getItem('favorites') || '[]'); const isFavorited = favorites.some(item => item.url === currentUrl); if (isFavorited) { // 取消收藏 const newFavorites = favorites.filter(item => item.url !== currentUrl); localStorage.setItem('favorites', JSON.stringify(newFavorites)); // 显示提示 showToast('已取消收藏'); } else { // 添加收藏 favorites.push({ url: currentUrl, title: currentTitle, time: new Date().toISOString() }); localStorage.setItem('favorites', JSON.stringify(favorites)); // 显示提示 showToast('收藏成功!'); } // 更新按钮状态 checkIfFavorited(); }); // 提示消息功能 function showToast(message) { // 检查是否已存在toast,如果有则移除 const existingToast = document.querySelector('.toast-message'); if (existingToast) { existingToast.remove(); } // 创建新的toast元素 const toast = document.createElement('div'); toast.className = 'toast-message'; toast.textContent = message; // 设置样式 Object.assign(toast.style, { position: 'fixed', bottom: '30px', left: '50%', transform: 'translateX(-50%)', backgroundColor: 'rgba(0, 0, 0, 0.7)', color: 'white', padding: '10px 20px', borderRadius: '4px', zIndex: '9999', opacity: '0', transition: 'opacity 0.3s ease' }); // 添加到body document.body.appendChild(toast); // 显示toast setTimeout(() => { toast.style.opacity = '1'; }, 10); // 3秒后隐藏 setTimeout(() => { toast.style.opacity = '0'; setTimeout(() => { toast.remove(); }, 300); }, 3000); } }); </script> </body> </html>