编写fastapi接口服务

FastAPI是一个基于 Python 的后端框架,该框架鼓励使用 Pydantic 和 OpenAPI (以前称为 Swagger) 进行文档编制,使用 Docker 进行快速开发和部署以及基于 Starlette 框架进行的简单测试。

step1:安装必要库

python 复制代码
pip install fastapi uvicorn

step2:构建代码

创建main.py脚本文件,然后引入FastAPI模块,就可以构建接口了

python 复制代码
from fastapi import FastAPI, Query
 
app = FastAPI()
 
@app.post("/路由")
def hello():
    return {"Hello": "World"}
 
@app.post('/路由')
async def function(
        try:
            *
        except:
            *
return {'Hello': World}

这只是一个简单示例,也可以用get等替换post

step3:运行接口

和其他的模块不一样的是,FastAPI需要运行指定命令来运行api服务:

需要在当前目录下执行下面的命令,他会主动去找到main入口:

python 复制代码
uvicorn main:app --reload

step4:更多指南

欢迎参考官网:https://fastapi.tiangolo.com/

Other:自己写了个接口

是GitHub上一个开源的给图片添加盲水印的项目blind_watermark

python 复制代码
from fastapi import FastAPI
from fastapi.responses import FileResponse
import subprocess
from fastapi.middleware.cors import CORSMiddleware
from fastapi import Form
from blind_watermark.blind_watermark import WaterMark

app = FastAPI()

# 后台api允许跨域
app.add_middleware(
    CORSMiddleware,
    allow_origins='*',
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
@app.post("/embed")
async def embed_watermark(pwd: int = Form(), image_path: str = Form(), watermark_text: str = Form(), output_path: str = Form()):
    try:
        subprocess.run(["blind_watermark", "--embed", image_path, watermark_text, output_path])
        # return FileResponse(output_path, filename="embedded.png")
        bwm1 = WaterMark()
        bwm1.read_img(image_path)
        bwm1.read_wm(watermark_text,mode='str')
        bwm1.embed(output_path)
        watermark_size = len(bwm1.wm_bit)

        return {"image": FileResponse(output_path, filename="embedded.png"), "watermark_size": watermark_size}
    except Exception as e:
        return {"error": str(e)}


@app.post("/extract")
async def extract_watermark(pwd: int = Form(), wm_shape: int = Form(), image_path: str = Form()):
    try:
        subprocess.run(["blind_watermark", "--extract", "--pwd", str(pwd), "--wm_shape", str(wm_shape), image_path])
        bwm1 = WaterMark(password_img=int(pwd))
        wm_str = bwm1.extract(filename=image_path, wm_shape=wm_shape, mode='str')
        return {"success": "Watermark extracted successfully.",'watermark is:':wm_str}
    except Exception as e:
        return {"error": str(e)}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8886)

解释一下

extract也是同理,需要调用哪些功能,就在这里添加,然后return返回的内容就是用调用工具,比如postman调用后显示的内容

postman界面调用信息:

如果我的代码有不妥的地方,欢迎指正

相关推荐
勘察加熊人14 小时前
vue+d3js+fastapi实现天气柱状图折线图饼图
前端·vue.js·fastapi
Amd7943 天前
FastAPI中的依赖注入与数据库事务管理
fastapi·依赖注入·sqlalchemy·事务管理·异步编程·sql注入防护·数据库会话管理
背太阳的牧羊人3 天前
app = Flask(__name__)和app = FastAPI()有什么区别和联系
python·flask·fastapi
Amd7944 天前
FastAPI依赖注入作用域与生命周期控制
fastapi·作用域·依赖注入·资源管理·请求级作用域·应用级作用域·生命周期控制
老大白菜4 天前
FastAPI-Cache2: 高效Python缓存库
python·缓存·fastapi
老大白菜5 天前
Python FastAPI + Celery + RabbitMQ 分布式图片水印处理系统
分布式·python·fastapi
Amd7946 天前
FastAPI依赖注入实践:工厂模式与实例复用的优化策略
单例模式·性能优化·fastapi·工厂模式·依赖注入·多租户系统·实例复用
郁大锤6 天前
Flask与 FastAPI 对比:哪个更适合你的 Web 开发?
前端·flask·fastapi
Amd7947 天前
FastAPI依赖注入:从基础概念到应用
fastapi·错误处理·代码示例·认证系统·依赖注入测试·依赖解析·路由处理
清风序来8 天前
一,<FastApi>什么是FastApi?及框架介绍
fastapi