在本教程中,我们将使用 FastAPI 创建一个基本的博客应用程序作为后端,使用 HTML 和 CSS 作为前端,以及 JSON 文件,用于执行基本的 CRUD(创建、读取、更新、删除)操作。
FastAPI 是一个使用 Python 构建 API 的现代 Web 框架,以其简单、速度和内置的异步操作支持而闻名。
下面的实现看起来像这样:
先决条件
开始之前,请确保您已安装以下软件:
- Python 3.7+
- FastAPI
- Uvicorn(用于运行 FastAPI 应用程序)
要安装FastAPI和Uvicorn,您可以使用pip:
pip install fastapi uvicorn python-multipart
项目结构
该项目的结构如下:
/blog_app ├── static │ └── style.css ├── templates │ ├── index.html │ ├── post.html │ ├── create_post.html ├── blog.json ├── main.py
第 1 步:设置 FastAPI
创建一个 main.py 文件,其中将包含 FastAPI 应用程序。
from fastapi import FastAPI, Request, Form from fastapi.responses import HTMLResponse, RedirectResponse from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates import json import os app = FastAPI() app.mount("/static", StaticFiles(directory="static"), name="static") templates = Jinja2Templates(directory="templates") # Load or initialize blog data BLOG_FILE = "blog.json" if not os.path.exists(BLOG_FILE): with open(BLOG_FILE, "w") as f: json.dump([], f) def read_blog_data(): with open(BLOG_FILE, "r") as f: return json.load(f) def write_blog_data(data): with open(BLOG_FILE, "w") as f: json.dump(data, f) @app.get("/", response_class=HTMLResponse) async def home(request: Request): blogs = read_blog_data() return templates.TemplateResponse("index.html", {"request": request, "blogs": blogs}) @app.get("/post/{post_id}", response_class=HTMLResponse) async def read_post(request: Request, post_id: int): blogs = read_blog_data() post = blogs[post_id] if 0 <h2> <strong>第 2 步:设置 HTML 和 CSS</strong> </h2> <p>在模板文件夹中,创建以下 HTML 文件:</p> <p>index.html<br> 该文件将列出所有博客文章。<br> </p> <pre class="brush:php;toolbar:false"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Blog App</title> <link rel="stylesheet" href="/static/style.css"> <h1 id="Blog-Posts">Blog Posts</h1> <a href="/create_post">Create New Post</a> <div> {% for post in blogs %} <div class="post"> <h2 id="post-title">{{ post.title }}</h2> <p>{{ post.content[:100] }}...</p> <a href="/post/%7B%7B%20loop.index0%20%7D%7D">Read more</a> <form method="post" action="/delete_post/%7B%7B%20loop.index0%20%7D%7D"> <button type="submit">Delete</button> </form> </div> {% endfor %} </div>
post.html
此文件将显示博客文章的完整内容。
<meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{{ post.title }}</title> <link rel="stylesheet" href="/static/style.css"> <h1 id="post-title">{{ post.title }}</h1> <p>{{ post.content }}</p> <a href="/">Back to Home</a>
create_post.html
该文件将包含用于创建新帖子的表单。
<meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Create a New Post</title> <link rel="stylesheet" href="/static/style.css"> <h1 id="Create-a-New-Post">Create a New Post</h1>Back to Home
第 3 步:使用 CSS 设计样式
在 static 文件夹中,创建一个 style.css 文件以添加一些基本样式。
body { font-family: Arial, sans-serif; padding: 20px; background-color: #f0f0f0; } h1 { color: #333; } a { text-decoration: none; color: #0066cc; } .post { background-color: #fff; padding: 10px; margin-bottom: 15px; border-radius: 5px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } button { background-color: #ff4d4d; border: none; padding: 5px 10px; color: white; border-radius: 3px; cursor: pointer; } button:hover { background-color: #ff1a1a; } input, textarea { width: 100%; padding: 8px; margin-bottom: 10px; }
第 4 步:运行应用程序
现在一切都已设置完毕,请使用 Uvicorn 运行 FastAPI 应用程序。
uvicorn main:app --reload
在浏览器中访问http://127.0.0.1:8000,您应该会看到博客主页。
作为作业,您可以使用数据库 ?️ 而不仅仅是 JSON 来创建全栈 Web 应用程序。
使用数据库,您可以添加更多功能、提高性能并增强整体 UI/UX。以获得更丰富的用户体验。
这就是本博客的全部内容了!请继续关注更多更新并继续构建令人惊叹的应用程序! ?✨
以上是使用 FastAPI、HTML、CSS 和 JSON 构建简单的博客应用程序的详细内容。更多信息请关注PHP中文网其他相关文章!

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

useanArray.ArarayoveralistinpythonwhendeAlingwithHomeSdata,performance-Caliticalcode,orinterFacingWithCcccode.1)同质性data:arrayssavememorywithtypedelements.2)绩效code-performance-clitionalcode-clitadialcode-critical-clitical-clitical-clitical-clitaine code:araysofferferbetterperperperformenterperformanceformanceformancefornalumericalicalialical.3)

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactssperformance.2)listssdonotguaranteeconeeconeconstanttanttanttanttanttanttanttanttimecomplecomecomecomplecomecomecomecomecomecomplecomectaccesslikearrikearraysodo。

toAccesselementsInapythonlist,useIndIndexing,负索引,切片,口头化。1)indexingStartSat0.2)否定indexingAccessesessessessesfomtheend.3)slicingextractsportions.4)iterationerationUsistorationUsisturessoreTionsforloopsoreNumeratorseforeporloopsorenumerate.alwaysCheckListListListListlentePtotoVoidToavoIndexIndexIndexIndexIndexIndExerror。

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

你可以通过使用pyenv、venv和Anaconda来管理不同的Python版本。1)使用pyenv管理多个Python版本:安装pyenv,设置全局和本地版本。2)使用venv创建虚拟环境以隔离项目依赖。3)使用Anaconda管理数据科学项目中的Python版本。4)保留系统Python用于系统级任务。通过这些工具和策略,你可以有效地管理不同版本的Python,确保项目顺利运行。

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基于基于duetoc的iMplation,2)2)他们的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函数函数函数函数构成和稳定性构成和稳定性的操作,制造


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

Dreamweaver Mac版
视觉化网页开发工具