1 Star 4 Fork 3

madamadadane / fastapi-postgresql-example-app

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
MIT

FastAPI Uvicorn peewee Python PostgreSQL MIT License

fastapi-postgresql-example-app

fastapi-postgresql-example-app 是一个使用 Fastapi 编写的后端接口系统,数据库采用 PostgreSQL,可以方便快速的编写后端接口,支持 docker 部署。

演示

演示地址:http://39.99.145.119:18000/docs

演示

配置和运行

数据库配置

如果不使用 docker 安装,则需要提前安装好 postgresql 数据库,然后修改 .env 中的数据库配置:

SECRET_KEY=secret
DEBUG=True
DB_CONNECTION=postgres://postgres:123456@localhost/traffic
HOST=localhost
PORT=54321
USERNAME=postgres
PASSWORD=123456
DATABASE=traffic

安装运行

# 安装依赖
pip install -r requirements.txt
# 启动 可以使用下面的方法
uvicorn app.main:app --reload --host 0.0.0.0 --port 18000

接口开发

数据表设计

数据表在 app/db/schemas.py 中进行设计,编写完成后保存会自动在数据库中生成设计的数据表,无需手动创建。

创建 摄像头 数据表:

# 摄像头列表
class Traffic_Cameras(BaseModel):
    id = AutoField(primary_key=True)
    camera_id = CharField() # 摄像头ID
    camera_name = CharField() # 摄像头名称
    camera_type = CharField() # 摄像头类型
    camera_lonlat = CharField(null=True, help_text="经纬度", verbose_name="经纬度") # 经纬度
    camera_road_id = CharField() # 摄像头道路ID
    camera_position = CharField() # 安装位置
    camera_scene = CharField(null=True) # 镜头
    camera_video_url = CharField(null=True) # 视频流地址
    camera_original_image_url = CharField(null=True) # 原始图片地址
    camera_image_url = CharField(null=True) # 标注后的图片地址
    created_at = DateTimeField(default=datetime.datetime.now)
    updated_at = DateTimeField(default=datetime.datetime.now)

在末尾的 create_tables 中添加 Traffic_Cameras 表名称,只有在 create_tables 中添加了表名称,才会自动创建数据表,否则不会自动创建。

# 创建数据表
def create_tables(db):
    db.create_tables([
        User,
        Traffic_Cameras,
        Traffic_Road,
        Traffic_Event_Code,
        Traffic_Lane_Code
    ])

编写 api 接口

  1. app/api/routes/ 路径下编写 api 接口
# 查询摄像头列表
@router.get("/selectlist", name="查询摄像头列表", dependencies=[Depends(get_db)])
async def cameras_selectlist(
    road_id: str,
    request: Request=None
):
    query = Traffic_Cameras.select().where(Traffic_Cameras.camera_road_id == road_id).dicts()
    results = [item for item in query]

    return {

        "code": 200,
        "message": "查询成功",
        "data": results
    }
  1. 编写好接口后,需要在 app/api/routes/api.py 中引入编写的接口文档
from app.api.routes import (
  authentication,
  users,
  traffic_cameras,
)

router = APIRouter()
router.include_router(authentication.router, tags=["authentication"], prefix="/users")
router.include_router(users.router, tags=["users"], prefix="/user")
router.include_router(traffic_cameras.router, tags=["监控摄像头"], prefix="/traffic_cameras")

访问 api 接口

启动项目后,可以通过 http://localhost:18000/docs 访问接口:

docs

设置接口访问权限

可以设置接口的访问权限,可以对 增删改 等的接口设置成需要登录才能访问,没有登录用户不能访问。

在接口函数的参数部分配置 Depends(get_current_user_authorizer()), 即可开启权限验证,需要在接口的请求头部携带 token 才可以正常访问接口。

# 创建摄像头
@router.post("/create", name="创建摄像头", dependencies=[Depends(get_db), Depends(get_current_user_authorizer())])
async def create_cameras(
    Create_Camera_Item: Create_Camera_Item,
    request: Request = None
):
    results = Create_Camera_Item.__dict__
    results['camera_id'] = str(uuid.uuid4())
    Traffic_Cameras.create(**results)
    print('创建摄像头', results)

    return {
        "code": 200,
        "message": "创建成功",
        "data": results
    }

设置访问权限之后,接口会出现带锁的样式,此时如果不带 token 访问会返回错误,如下图所示:

error

这时需要先登录,获取到可用的 token ,在 Available authorizations 输入获取到 token,这样就可以正常访问借口了。

authorizations

再次访问接口,即可获取到接口数据。

正常访问

使用 docker 部署

使用 Dockerfile

使用 Dockerfile 时,需要先自行安装 postgresql 数据库,并在 .env 中配置好数据库参数。

注意:在配置数据库参数时,需要注意 HOST 最好配制成 IP 形式,以防访问不到 postgresql 数据库。

编写 Dockerfile 文件:

FROM python

WORKDIR /home/fastapi

COPY . .

RUN pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple

EXPOSE 18000

CMD ["uvicorn", "app.main:app", "--reload", "--host", "0.0.0.0", "--port", "18000"]

构建镜像并运行:

# 构建镜像
docker build -t fastapi-postgresql-example-app .

# 运行镜像
docker run -d -p 18000:18000 -v $PWD/static/images:/home/fastapi/static/images --name fastapi-postgresql-example-app fastapi-postgresql-example-app

使用 docker-compose

编写 docker-compose.yml 文件:

version: '3'

services:
  app:
    restart: always # 代表只要Docker启动,那么这个容器就跟着一起启动
    build: './'
    container_name: fastapi-postgresql-example-app # 指定容器名称
    ports:
      - "18000:18000"
    volumes:
      - './static/images:/home/fastapi/static/images'
    environment: # 指定时区
      TZ: Asia/Shanghai
    depends_on:
      - db
  db:
    restart: always
    image: postgres # 指定镜像名称
    container_name: fastapi-postgres # 指定容器名称 --name
    ports: # -p
      - 54321:5432 # 指定端口号的映射
    environment:
      POSTGRES_PASSWORD: 123456 # 指定 postgresql 的 postgres 用户登录密码
      TZ: Asia/Shanghai # 指定时区
    volumes:
      - './postgresData/data:/var/lib/postgresql/data' # 映射数据卷

启动和关闭 docker-compose

docker-compose up -d
docker-compose down

注意:运行 docker-compose 之后,由于 postgresql 数据库中并没有 traffic 数据库,所以需要手动将 postgreData/traffic.sql 导入到 postgresql 数据库中。此时,由于 fastapi-postgresql-example-app 也启动了,但是连接 postgresql 数据库失败,可能需要重新启动一下 fastapi-postgresql-example-app 容器。

线上部署

线上部署时,需要注意以下几点:

  • 要修改 数据库 的配置,hostport 修改为云服务器的 IP端口
  • 对于 fastapi-postgresql-example-app 来说,可以使用内网 IP访问数据库
  • 线上部署时,注意修改 docker-compose.env 中的数据库密码,不要使用 123456 这样简单的密码
  • 线上部署成功后,需要设置云服务器的安全组端口,才能进行远程访问
  • 修改 .env 中的 图片访问和保存地址:
# 图片访问和保存地址
ImagesUrl=http://{远程IP}:18000/api
ROOT_FILE_PATH=/home/fastapi/static/images

项目结构

Files related to application are in the app directories. Application parts are:

app
├── api              - web related stuff.
│   ├── dependencies - dependencies for routes definition.
│   ├── errors       - definition of error handlers.
│   └── routes       - web routes.
├── core             - application configuration, startup events, logging.
├── db               - db related stuff.
│   └── repositories - all crud stuff.
├── models           - pydantic models for this application.
│   ├── domain       - main models that are used almost everywhere.
│   └── schemas      - schemas for using in web routes.
├── resources        - strings that are used in web responses.
├── services         - logic that is not just crud related.
└── main.py          - FastAPI application creation and configuration.

License

MIT

MIT License Copyright (c) 2021 Wenwei Fu Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

简介

fastapi-postgresql-example-app 是一个使用 Fastapi 编写的后端接口系统,数据库采用 PostgreSQL,可以方便快速的编写后端接口,支持 docker 部署。 展开 收起
Python 等 4 种语言
MIT
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
1
https://gitee.com/fuwenwei501/fastapi-postgresql-example-app.git
git@gitee.com:fuwenwei501/fastapi-postgresql-example-app.git
fuwenwei501
fastapi-postgresql-example-app
fastapi-postgresql-example-app
master

搜索帮助