【FastAPI搭建好的开发框架】非异步操作数据库,附源码

编程入门 行业动态 更新时间:2024-10-09 18:21:08

【FastAPI搭建好的开发框架】非异步操作数据库,附<a href=https://www.elefans.com/category/jswz/34/1770099.html style=源码"/>

【FastAPI搭建好的开发框架】非异步操作数据库,附源码

【FastAPI搭建好的产品框架,直接开发】

前言

最近工作中有机会接触FastAPI这个框架,所以就把官方文档看了一遍,对框架的各个特性及使用方法做了总结。并搭建了一个基础框架,照着就可以直接上手开发。

  • 源码下载地址
  • 如想要完整详解教程,请去我的系列博文,连接在此。

一、FastAPI有哪些厉害之处?

FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 3.6+ 并基于标准的 Python类型提示。

关键特性:

  • 快速:可与 NodeJS 和 Go 比肩的极高性能(归功于 Starlette 和 Pydantic)。最快的 Python web框架之一。
  • 高效编码:提高功能开发速度约 200% 至 300%。*
  • 更少 bug:减少约 40% 的人为(开发者)导致错误。
  • 智能:极佳的编辑器支持。处处皆可自动补全,减少调试时间。
  • 简单:设计的易于使用和学习,阅读文档的时间更短。
  • 简短:使代码重复最小化。通过不同的参数声明实现丰富功能。bug 更少。
  • 健壮:生产可用级别的代码。还有自动生成的交互式文档。
  • 标准化:基于(并完全兼容)API 的相关开放标准:OpenAPI (以前被称为Swagger) 和 JSON Schema。

二、使用步骤

1.系统目录结构

1.1、一级目录

  • [bin ] 系统配置文件
  • [logs] 日志
  • [server] 系统服务

1.1、server下二级目录

主要代码都在server下,下面会主要说下文件作用。

  • [app] app应用
  • [extensions] 系统拓展
  • [script] 脚本
  • [test] 测试
  • [config.py] 系统server配置文件
  • [manage.py] 主方法

目录就不做细说了,下载代码后可以自己看下。


2.配置文件

下面是系统配置文件,如果有需要,可自行增删;
想要跑起来项目,请先将数据库信息自行修改为自己本地的;

# define your config here
# coding=gbk
import os
# from starlette.datastructures import SecretDEBUG = os.getenv("DEBUG", True)MAX_CONNECTIONS_COUNT = 10
MIN_CONNECTIONS_COUNT = 4SECRET_KEY = 'ST-3KugLz80ptYAnrr0kiVj8MWzwwWVczwI4Fvd7V3qgGtpDsVkvA21LdadhixSW'
SESSION_TIMEOUT = 30 * 60 * 60ALLOWED_HOSTS = ["127.0.0.1", 
]APPSECRET = "MJX3qyRvFPN"HOST = '127.0.0.1'
PORT = 8000if os.getenv("ENV") == "dev":SERVER_URL = "http://127.0.0.1:8000"SERVER_HOST = "127.0.0.1"SERVER_PORT = "8000"AGENT_VERSION = "v1.0"SFTP = False# db connect configDB = {"user": 'root',"pass": 'password',"host": '127.0.0.1',"port": '3306',"db": 'fastapi',}# redis connect configREDIS = {"name": 'cjh_local',"pass": '',"host": '127.0.0.1',"port": '6379',"db": '1',}
else:raise Exception("set ENV dev test pro")EQUIP_STATUS = {"a": "工作","o": "离线","q": "停用"
}AILI_CODE = "f2a5cbdeaaaaaaaaaaadec17f8cd9a21"
API_KEY = "01223842382"

3.将项目跑起来

3.1安装python依赖包

在bin > conf 目录下,requirements.txt 文件里,有系统相关的依赖包,执行如下命令安装;

pip install -r requirements.txt

3.2 利用pycharm将项目运行起来

1、利用pycharm,配置信息如下。

2、运行服务,服务起来后如下图;

3、查看自动生成的接口交互文档,既在路由后面加上docs

4、查看 redoc 接口文档,既在路由后面加上redoc

至此,项目已运行起来。


4.如何写接口

4.1 如何建表模型

  • 与其他框架类似,直接参考使用。
# coding=gbk
"""
@author: 陈建华
@file: test.py
@time: 2021/2/17 11:38
"""
from sqlalchemy import Column, DateTime, String, text
from sqlalchemy.dialects.mysql import INTEGER, VARCHAR, DATETIME
from sqlalchemy.types import String, Integer, CHAR, BIGINT
from sqlalchemy.orm import Session, relationship, contains_eager
from server.app.models.base import Base
from server.app.utils.datetime_tools import zone_datetime
from server.app import models
DELETE_STATE = {"state": "2"}class Test(Base):__tablename__ = 'test'id = Column(INTEGER, autoincrement=True, primary_key=True, comment='标识')name = Column(String(100), comment='用户名称')code = Column(String(32), comment='身份照号')phone = Column(String(128), comment='手机号')count = Column(String(4), comment='用水人数')price_type = Column(String(64), comment='水价类型')create_time = Column(DATETIME, default=zone_datetime)@classmethodasync def install(cls, db, name, code, phone, count, price_type):_ = cls(**{"name": name,"code": code,"phone": phone,"count": count,"price_type": price_type,})db.add(_)dbmit()return _@classmethodasync def create_or_update(cls, db, name, code, phone, count, price_type):owner_obj = db.query(cls).filter(cls.code == code).first()if owner_obj:owner_obj.name = nameowner_obj.phone = phoneowner_obj.count = countowner_obj.price_type = price_typedbmit()return owner_objelse:return await cls.install(db, name, code, phone, count, price_type)@classmethodasync def get_info(cls, db, id):user_obj = db.query(cls).filter(cls.id == id).first()return user_obj.name, user_obj.code

4.2 如何同步表结构

调用封装好的 makemigrations 方法,可直接将表模型中表字段在数据库之后实际创建出来。使用方式如下。

4.3 如何写接口

1、接口参数支持 python36+ 类型提示。
2、定义方法用async,就必须用await联合使用。
3、返回响应是可以定义专门的响应模型的。
4、在get、post等方法中定义二级的路由
如有不清楚的,可以查看我的fastapi系列博文,有专门详解,链接在此

# encoding: utf-8
# coding=gbk
"""
@author: 陈建华
@file: test.py
@time: 2021/2/17 11:10
"""
from fastapi import APIRouter, Depends, Form
from starlette.requests import Request
from server.app.models.test import *
from server.app.schemas.base import HttpResponseModel, HttpResponseListModel
from server.app.utils.database import get_db
from server.app.utils.responses import response_code_set
from server.app.utils.dependencies import verify_token
router = APIRouter()@router.get("/test/",tags=["cjh测试一级路由___测试对表进行查询,带外键,外多对多外键"],responses=response_code_set({'ret': '自定义注释后的返回值'})
)
async def test(request: Request,data_id: int = ...,db: Session = Depends(get_db),
):try:ret = await Test.get_info(db, data_id)return HttpResponseListModel(message="获取数据成功",content={"total": len(ret),"data": ret,})except Exception as e:return HttpResponseModel(code=500,message=e.args[0],)

4.4 如何用路由调用接口

在 server > app > init.py 文件之后,放了系统的一级路由,如下图所示,照着用就可以了。

# coding=gbk
from fastapi import FastAPI
from starlette.exceptions import HTTPException
from starlette.middleware.cors import CORSMiddleware
from starlette.middleware.sessions import SessionMiddleware
# from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY
# from starlette.staticfiles import StaticFilesfrom server.app.core.auth import router as auth_router
from server.app.core.test import router as test_router# from app.utils.db_loader import connect_db, disconnect_db
from server.app.utils.scheduler import init_scheduler
from server.app.utils.error_handlers import http_error_handler
from server import configapp = FastAPI()scheduler = None# add middleware
app.add_middleware(CORSMiddleware,allow_origins=config.ALLOWED_HOSTS,allow_credentials=True,allow_methods=["*"],allow_headers=["*"],max_age=500,  # 浏览器缓存CORS返回结果的最大时长,默认为600(单位秒)
)app.add_middleware(SessionMiddleware,max_age=config.SESSION_TIMEOUT,  # 30 minute, in secondssecret_key=config.SECRET_KEY)# connect to database
# 定时任务
# app.add_event_handler("startup", init_scheduler)# error handling
app.add_exception_handler(HTTPException, http_error_handler)# include various routes
app.include_router(auth_router, prefix="/auth")
app.include_router(test_router, prefix="/test")     # cjh测试-一级路由

总结

这里对文章进行总结:
以上就是今天要讲的内容,本文仅仅介绍了fastapi的常规使用,而fastapi提供了大量能使我们快速便捷地开发web的函数和方法。可以稍微花点时间看下我总结的系列博文。
链接在此

更多推荐

【FastAPI搭建好的开发框架】非异步操作数据库,附源码

本文发布于:2024-02-06 11:07:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1748641.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:源码   框架   操作   数据库   FastAPI

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!