FastAPI is a Web framework written in Python with the latest optimizations in the Python Asyncio library. This article will show you how to set up a container-based development environment and how to implement a small Web service using FastAPI.

start

We will use Fedora as the base image to set up the development environment, and use Dockerfile to inject FastAPI, Uvicorn, and Aiofiles into the image.

FROM fedora:32
RUN dnf install -y python-pip \
    && dnf clean all \
    && pip install fastapi uvicorn aiofiles
WORKDIR /srv
CMD ["uvicorn"."main:app"."--reload"]
Copy the code

After saving the Dockerfile in your working directory, run the Podman command to build the container image.

$ podman build -t fastapi .
$ podman images
REPOSITORY TAG IMAGE ID CREATED SIZE
localhost/fastapi latest 01e974cabe8b 18 seconds ago 326 MB
Copy the code

Now we can start creating a simple FastAPI application and run it through the container image.

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello Fedora Magazine!"}
Copy the code

Save the above code to the main.py file and run it with the following command:

$ podman run --rm -v $PWD:/srv:z -p 8000:8000 --name fastapi -dFastapi $curl http://127.0.0.1:8000 {"message":"Hello Fedora Magazine!"
Copy the code

Thus, a FastAPi-based Web service runs. Since the –reload parameter is specified, the entire application is automatically reloaded whenever the main.py file changes. You can try returning the message “Hello Fedora Magazine!” Change it to something else and see how it works.

You can stop the application with the following command:

$ podman stop fastapi
Copy the code

Build a small Web service

Next, we’ll build an APPLICATION that requires I/O operations to see what FastAPI does and how it benefits in terms of performance (see FastAPI versus other Python Web frameworks here). For simplicity, we use the output of the DNF history command directly as the data for this application.

First, save the output of the DNF history command to a file.

$ dnf history | tail --lines=+3 > history.txt
Copy the code

In the command above, we used tail to remove unwanted header information from the DNF history output. Each remaining DNF transaction contains the following information:

  • id: transaction number (incremented each time a new transaction is run)
  • command: Running in a transactiondnfThe command
  • date: The date and time when the transaction is executed

Then modify the main.py file to add the relevant data structures.

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class DnfTransaction(BaseModel):
    id: int
    command: str
    date: str
Copy the code

FastAPI’s pyDantic library makes it easy to define a data class, and its type annotations provide easy validation of data.

Add a function to read data from the history.txt file.

import aiofiles

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class DnfTransaction(BaseModel):
    id: int
    command: str
    date: str


async def read_history():
    transactions = []
    async with aiofiles.open("history.txt") as f:
        async for line in f:
            transactions.append(DnfTransaction(
                id=line.split("|")[0].strip(""),
                command=line.split("|")[1].strip(""),
                date=line.split("|")[2].strip("")))
    return transactions
Copy the code

This function uses the aiofiles library, which provides an asynchronous API for processing files in Python so that opening or reading files does not block other requests to the server.

Finally, modify the root function to return the data in the transaction list.

@app.get("/")
async def read_root():
    return await read_history()
Copy the code

Execute the following command to see the output of the application.

$curl http://127.0.0.1:8000 | python - m json tool [{"id": 103,
"command": "update"."date": "The 2020-05-25 08:35"
},
{
"id": 102,
"command": "update"."date": "The 2020-05-23 him"
},
{
"id": 101,
"command": "update"."date": "The 2020-05-22 concluded"},... ]Copy the code

conclusion

FastAPI is becoming increasingly popular in the Python Web framework ecosystem by providing an easy way to build Web services using Asyncio. To learn more about FastAPI, check out the FastAPI documentation.

The code for this article can be found on GitHub.


Via: fedoramagazine.org/use-fastapi…

Written by Clement Verna and translated by HankChow

This article is originally compiled by LCTT and released in Linux China