python:Docker部署基于Fastapi接口

这几天文章更新的都不是很频繁,主要是在倒腾fastapi框架(当然,自身懒惰也有,年底比较忙也有),这个框架官方介绍就是高性能,易于学习,高效编码,生产可用,因为最近挺火的,也来蹭下。

本篇文章主要聊得是利用docker搭建fastapi接口,其余文章后面空了会补上来吧,下面进入正文。

步骤一:安装docker

安装docker,网上教程很多,可自行百度

步骤二:安装Fastapi

安装完成后,并编写一些接口,可先复制下方接口(这个后面文章会补上来…)

from enum import Enum
from fastapi import FastAPI


class ModelName(str, Enum):
    name = "zhangSan"
    school = "国立中山大学"
    history_school = "简介"


app = FastAPI()


@app.get("/")
async def root():
    return "hello world"


@app.get("/items/{item_id}")
def read_item(item_id):
    """
    路径参数
    :param item_id:
    :return:
    """

    return {"item_id": item_id}


@app.get("/item_type/{item_id}")
def read_type(item_id: int):
    """
    有类型的路径参数
    :param item_id:
    :return:
    """

    return {"item_id": item_id}


@app.get("/models/{model_name}")
def get_model(model_name: ModelName):
    if model_name == ModelName.name:
        return {"model_name": model_name, "message""名称正确,就是这个玩意 !"}

    if model_name.value == "国立中山大学":
        return {"model_name": model_name, "message""学校正确,就是这个玩意 !"}

    return {"model_name": model_name, "message""""
    Sun Yat-sen University 中山大学(Sun Yat-sen University),简称中大,位于广州市,由中华人民共和国教育部直属,是教育部、国家国防科技工业局和广东省共建的综合性全国重点大学,
    1924年,孙中山亲手将广州地区多所高校整合创立国立广东大学。1926年定名为国立中山大学。如今该校由1952年院系调整后分设的中山大学和中山医科大学于2001年10月合并而成。"""
}

步骤三:编写requirements文件

httpx
fastapi[all]

设置安装两个库(httpx是请求库,可以不用安装;fastapi[all]是安装全部,包括该库的依赖库)

步骤四:编写Dockerfile文件

# 引入python版本
FROM python:3.10.1

# 设置时间
RUN ln -sf /usr/share/zoneinfo/Asia/Beijing/etc/localtime

# 输出时间
RUN echo 'Asia/Beijing' >/etc/timezone

# 设置工作目录
WORKDIR /code

# 复制该文件到工作目录中
COPY ./requirements.txt /code/requirements.txt

# 禁用缓存并批量安装包(后面的链接是利用豆瓣源安装,速度会加快)
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt -i https://pypi.douban.com/simple/

# 复制代码到工作目录
COPY ./app /code/app

# 放开端口
EXPOSE 8085

# 命令行运行,启动uvicorn服务,指定ip和端口(--reload:让服务器在更新代码后重新启动。仅在开发时使用该选项。)
CMD ["uvicorn""app.main:app""--reload""--host""0.0.0.0""--port""8085"]

步骤五:构建镜像

PS E:\git_code\python-code\fastapiProject> docker build -t test-fastapi:1.0.0 .
[+] Building 28.3s (12/12) FINISHED
 => [internal] load build definition from Dockerfile                                                                                                                                                                                                                      0.0s
 => => transferring dockerfile: 460B                                                                                                                                                                                                                                      0.0s
 => [internal] load .dockerignore                                                                                                                                                                                                                                         0.0s
 => => transferring context: 2B                                                                                                                                                                                                                                           0.0s
 => [internal] load metadata for docker.io/library/python:3.10.1                                                                                                                                                                                                          2.3s
 => [internal] load build context                                                                                                                                                                                                                                         0.0s
 => => transferring context: 292B                                                                                                                                                                                                                                         0.0s
 => [1/7] FROM docker.io/library/python:3.10.1@sha256:6d2551cd76593672929813669bf7fbbd2f2c454a400b084a87122dc12fef8563                                                                                                                                                    0.0s
 => CACHED [2/7] RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime                                                                                                                                                                                              0.0s
 => CACHED [3/7] RUN echo 'Asia/Shanghai' >/etc/timezone                                                                                                                                                                                                                  0.0s
 => CACHED [4/7] WORKDIR /code                                                                                                                                                                                                                                            0.0s
 => [5/7] COPY ./requirements.txt /code/requirements.txt                                                                                                                                                                                                                  0.0s
 => [6/7] RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt -i https://pypi.douban.com/simple/                                                                                                                                                          25.4s
 => [7/7] COPY ./app /code/app                                                                                                                                                                                                                                            0.0s
 => exporting to image                                                                                                                                                                                                                                                    0.5s
 => => exporting layers                                                                                                                                                                                                                                                   0.4s
 => => writing image sha256:11a6ac0dab47fe6ad8cfc9d8509dbff8f4ffab80ba3d8af870b5105b6e31fc8c                                                                                                                                                                              0.0s
 => => naming to docker.io/library/test-fastapi:1.0.0                                                                                                                                                                                                                     0.0s

Use 'docker scan' to run Snyk tests against images to find vulnerabilities and learn how to fix them

步骤六:查看镜像

PS E:\git_code\python-code\fastapiProject> docker images
REPOSITORY                     TAG            IMAGE ID       CREATED          SIZE
test-fastapi                   1.0.0          11a6ac0dab47   27 minutes ago   1.01GB

步骤七:运行容器

PS E:\git_code\python-code\fastapiProject> docker run -d --name fastapi-test -p 8000:8085 test-fastapi:1.0.0
3969bed5826d58616bd80b1aa7624d1b741ab2064e490ecea4ee322be2756401

参数说明:

  • -d:参数指定 Docker 网络类型
  • --name:参数是起个名字
  • -p: 是容器内部端口绑定到指定的主机端口
  • test-fastapi:1.0.0 是刚刚构建的镜像

步骤八:查看容器

PS E:\git_code\python-code\fastapiProject> docker ps
CONTAINER ID   IMAGE                COMMAND                  CREATED          STATUS          PORTS                    NAMES
3969bed5826d   test-fastapi:1.0.0   "uvicorn app.main:ap…"   32 minutes ago   Up 32 minutes   0.0.0.0:8000->8085/tcp   fastapi-test

步骤九:访问接口

访问链接(ip是物理机ip),浏览器访问或postman访问均可

http://10.10.12.120:8000/models/zhangSan

返回结果:

{"model_name":"zhangSan","message":"名称正确,就是这个玩意 !"}

以上总结或许能帮助到你,或许帮助不到你,但还是希望能帮助到你,如有疑问、歧义,直接私信留言会及时修正发布;非常期待你的点赞和分享哟,谢谢!

未完,待续…

一直都在努力,希望您也是!

微信搜索公众号:就用python

文章作者:李 锋|编辑排版:梁莉莉

posted @ 2022-01-12 20:15  一名小测试  阅读(601)  评论(0编辑  收藏  举报