分类标签归档:FastApi开发

[ python asyncio使用 ]


fastapi启动websocket服务, 并且使用async

from fastapi import FastAPI, WebSocket, Depends, WebSocketDisconnect, WebSocketException
from fastapi.responses import HTMLResponse

from extends.redis.conn import redis_connection
from config.settings import get_settings, Settings
from typing import TypedDict, Litera

< Read more >

[ fastapi基础面试题 ]


FastAPI有以下几个优势:

高性能:FastAPI基于Starlette框架构建,利用了Python 3.7+中的异步特性,使得它能够处理高并发的请求。它使用异步请求处理框架uvicorn,性能比传统的基于线程或进程的服务器更高。

快速开发:FastAPI提供了一个简洁、声明性的语法,使得开发者能够快速地构建Web API。它支持自动进行请求参数验证和文档生成,减少了繁琐的手动操作,提高了开发效率。

强大的类型提示和自动文档生成:FastAPI利用Python的类型提示功能,能够在运行时自动验证请求和响应数据的类型,并生成详细的API文档。这使得团队协作变得更加容易,同时也方便了前后端的对

< Read more >

[ fastapi使用sqlalchemy2.0异步数据库 ]


fastapi使用sqlalchemy2.0异步数据库

pip install SQLAlchemy
pip install aiomysql
pip install pydantic-settings
pip install python-dotenv

配置文件config.py

from pydantic_settings import BaseSettings
from functools import lru_cache

class Settings(BaseSettings):
    app_name: str = "chf-app"
    databa

< Read more >

[ fastapi使用sqlalchemy+mysql ]


sqlalchemy中使用mysql

一.依赖安装

第三方包

pip install sqlalchemy
pip intalll pymysql

二.在fastapi中使用

databases.py文件 1. engine创建连接 2. sessionlocal为获取连接 3. Base用来映射数据库表

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

SQLALCHE

< Read more >

[ sqlalchemy+alembic数据库迁移 ]


  1. 安装
pip install alembic 
  1. 初始化
alembic init alembic
  1. 修改配置文件 alembic.ini文件 指定地址
sqlalchemy.url = mysql+pymysql://root:chenhaifeng@47.120.55.99:3306/fastapi
  1. env.py文件 指定表metadata
# target_metadata = mymodel.Base.metadata
from applications.extensions import metadata
from applications.models im

< Read more >

[ [databases异步]FastApi ]


Databases异步数据库官方文档

在fastapi中的使用

  1. 先安装
pip install databases
pip install databases[aiomysql]
pip install pymysql
  1. main.py文件
from typing import List

import databases
import sqlalchemy
from fastapi import FastAPI
from pydantic import BaseModel

DATABASE_URL = "mysql+pymysql://root:chenhaifeng@

< Read more >