Python Fastapi:1.Fastapi介绍;GET和POST请求的写法

该文章已生成可运行项目,

Fast API

异步框架,支持高并发,方法前面可以配合async进行异步通信

需要安装两个东西:fastAPI、uvicorn

同步:一件事情没有做完----卡住
异步:不会卡住,会继续进行

启动第一个程序:

from fastapi import FastAPI
import uvicorn

app = FastAPI()


@app.get("/")
async def hello():
    return {"data": "HELLO!"}


if __name__ == "__main__":
    uvicorn.run(app="main:app", host="0.0.0.0", port=8080, reload=False)

GET请求

使用fastAPI来接受GET请求的方法
FastAPI具有两种接收参数的方法

  • 直接将参数写在路由里面。
@app.get("/get/{uid}")
async def read_get(uid: str):
    return {"Now your uid": uid}

访问/get/1

得到Now your uid : 1

  • 通过问号来输入参数
# 指明请求参数,即用?&
@app.get("/get2")
async def read_get2(uid: str, name: str):
    return "Welcome!"+name+", your uid is"+uid

访问/get2?uid=3&name=xiaoming
“Welcome!xiaoming, your uid is3”

POST请求

需要安装python-multipart
from fastapi import FastAPI, Form
from typing import Optional

@app.post("/post1")
async def read_post1(uid:Optional[str] = Form()):
    return {"uid": uid}
本文章已经生成可运行项目
`CORSMiddleware` 是 FastAPI 中用于处理 **跨域资源共享(CORS)** 的中间件。当你遇到浏览器报错如: ``` Access to fetch at 'http://localhost:8000/login' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy ``` 这就是典型的跨域问题,需要用 `CORSMiddleware` 来解决。 --- ## ✅ 什么是 CORS? - **CORS**(Cross-Origin Resource Sharing)是浏览器的一种安全机制。 - 它限制了网页从一个源(origin)向另一个不同源的服务器发起请求。 - 源 = 协议 + 域名 + 端口,三者任意一个不同就算跨域。 例如: - 前端运行在:`http://127.0.0.1:5500`(VSCode Live Server) - 后端运行在:`http://127.0.0.1:8000` → 虽然 IP 相同,但 **端口不同 → 跨域** --- ## ✅ 如何使用 `CORSMiddleware` 解决跨域 只需在你的 FastAPI 应用中注册该中间件,并配置允许的来源即可。 ### 🔧 示例代码(完整配置) ```python from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() # --- 配置 CORS --- origins = [ "http://localhost", "http://localhost:8080", "http://127.0.0.1:5500", # VSCode Live Server "http://127.0.0.1:3000", # React/Vue 默认端口 "https://yourfrontend.com", ] app.add_middleware( CORSMiddleware, allow_origins=origins, # 允许访问的前端域名 allow_credentials=True, # 允许携带 cookies allow_methods=["*"], # 允许的 HTTP 方法(GETPOST 等) allow_headers=["*"], # 允许的请求头 ) ``` --- ### 🛠️ 参数详解 | 参数 | 说明 | |------|------| | `allow_origins` | 白名单列表,指定哪些前端域名可以访问后端。⚠️ 生产环境不要用 `["*"]` | | `allow_credentials` | 是否允许发送 Cookie 或 Authorization 头。如果为 `True`,则 `allow_origins` 不能为 `["*"]` | | `allow_methods` | 允许的 HTTP 方法,如 `["GET", "POST"]` 或 `["*"]` 表示全部 | | `allow_headers` | 允许的请求头字段,如 `"Content-Type", "Authorization"` 等,也可用 `["*"]` | --- ### ⚠️ 常见错误与解决方案 #### ❌ 错误写法(会导致异常): ```python app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, # ❌ 冲突!不能同时设置 ) ``` > 报错信息: > ``` > Error: Disallowed CORS origin: Credentials are allowed, but origin '*' is not allowed. > ``` #### ✅ 正确做法: 如果你需要支持凭据(如 cookie),就不能使用 `*`,必须明确列出域名: ```python app.add_middleware( CORSMiddleware, allow_origins=[ "http://localhost:3000", "http://127.0.0.1:5500" ], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) ``` --- ### ✅ 实际应用中的推荐配置(开发环境) ```python # backend/main.py 或 startup 文件中 from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI(debug=True) app.add_middleware( CORSMiddleware, allow_origins=["http://127.0.0.1:5500"], # 根据你的前端地址修改 allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) ``` 这样你就可以用 VSCode 的 **Live Server** 打开 `index.html` 并成功调用 `/login` 接口了。 --- ### ✅ 测试是否生效 前端测试代码(HTML + JS): ```html <script> fetch("http://127.0.0.1:8000/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ account: "test", password: "123456" }) }) .then(r => r.json()) .then(console.log); </script> ``` 如果没有报 CORS 错误,且能收到响应,说明配置成功! ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值