引言
随着Web开发技术的不断进步,FastAPI和MySQL成为了许多开发者青睐的技术组合。FastAPI以其简洁、高效、易于扩展的特点在Python Web框架中脱颖而出,而MySQL则因其稳定、可靠、易用而成为数据存储的首选。本文将详细介绍如何将FastAPI与MySQL数据库无缝对接,实现高效开发。
准备工作
在开始之前,请确保您已安装以下软件:
- Python 3.6 或更高版本
- FastAPI
- uvicorn(用于运行FastAPI应用)
- MySQL数据库
您可以使用以下命令安装FastAPI和uvicorn:
pip install fastapi uvicorn
连接MySQL数据库
要连接MySQL数据库,您需要使用一个Python库,如mysql-connector-python或PyMySQL。以下是使用mysql-connector-python连接MySQL数据库的示例代码:
import mysql.connector
# 数据库配置
config = {
'user': 'your_username',
'password': 'your_password',
'host': 'localhost',
'database': 'your_database',
'raise_on_warnings': True,
}
# 连接数据库
cnx = mysql.connector.connect(**config)
cursor = cnx.cursor()
创建FastAPI应用
接下来,创建一个FastAPI应用。以下是创建一个基本FastAPI应用的示例代码:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"message": "Hello, World!"}
接口与数据库交互
现在,我们将创建一个接口,用于从MySQL数据库中获取数据。以下是示例代码:
from fastapi import FastAPI, HTTPException
app = FastAPI()
# 数据库配置
config = {
'user': 'your_username',
'password': 'your_password',
'host': 'localhost',
'database': 'your_database',
'raise_on_warnings': True,
}
# 连接数据库
cnx = mysql.connector.connect(**config)
cursor = cnx.cursor()
@app.get("/items/")
async def get_items():
query = "SELECT * FROM items"
cursor.execute(query)
result = cursor.fetchall()
return result
在这个示例中,我们创建了一个/items/接口,用于获取items表中的所有数据。
分页与查询参数
在实际应用中,您可能需要支持分页和查询参数。以下是支持分页和查询参数的示例代码:
from fastapi import FastAPI, Query
app = FastAPI()
# 数据库配置
config = {
'user': 'your_username',
'password': 'your_password',
'host': 'localhost',
'database': 'your_database',
'raise_on_warnings': True,
}
# 连接数据库
cnx = mysql.connector.connect(**config)
cursor = cnx.cursor()
@app.get("/items/")
async def get_items(page: int = 1, limit: int = 10):
offset = (page - 1) * limit
query = f"SELECT * FROM items LIMIT {limit} OFFSET {offset}"
cursor.execute(query)
result = cursor.fetchall()
return result
在这个示例中,我们添加了page和limit查询参数,以支持分页。
更新、删除与插入数据
除了查询数据外,您可能还需要对数据库进行更新、删除和插入操作。以下是示例代码:
from fastapi import FastAPI, HTTPException
app = FastAPI()
# 数据库配置
config = {
'user': 'your_username',
'password': 'your_password',
'host': 'localhost',
'database': 'your_database',
'raise_on_warnings': True,
}
# 连接数据库
cnx = mysql.connector.connect(**config)
cursor = cnx.cursor()
@app.post("/items/")
async def create_item(item_name: str):
query = "INSERT INTO items (name) VALUES (%s)"
cursor.execute(query, (item_name,))
cnx.commit()
return {"id": cursor.lastrowid, "name": item_name}
@app.put("/items/{item_id}")
async def update_item(item_id: int, item_name: str):
query = "UPDATE items SET name = %s WHERE id = %s"
cursor.execute(query, (item_name, item_id))
cnx.commit()
return {"id": item_id, "name": item_name}
@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
query = "DELETE FROM items WHERE id = %s"
cursor.execute(query, (item_id,))
cnx.commit()
return {"id": item_id}
在这个示例中,我们添加了创建、更新和删除数据的接口。
总结
本文介绍了如何将FastAPI与MySQL数据库无缝对接,实现高效开发。通过以上示例代码,您应该能够理解如何创建一个基本的FastAPI应用,并使用它来与MySQL数据库进行交互。希望这些信息能对您的开发工作有所帮助。
