FastAPI 从文件读写

FastAPI read&write from file

开始学习python,遇到了一点小问题。 我尝试使用只有 2 个请求的 FastAPI 创建小聊天,get(msg) & post(msg).

使用来自 pydantic 的 BaseModel 的按摩所以它有 2 个字段:昵称和按摩内容

如果我使用代码中的本地数据库,它工作正常(我用 post 插入到 dict 然后将它移动到数据库)并且它呈现得很好并且 Json 喜欢。

但是我想使用文件而不是本地数据库,我遇到的问题是:

  1. 无法使写入同时包含两个字段(它只需要 nickname\massage)
  2. 看起来不像JSON。

我写的代码:(# 是我使用 DB 的部分,运行良好)

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

#db = []

class Text(BaseModel):
    nickname:str
    text:str

@app.get('/')
def index():
    return {'key' : 'value'}

@app.get('/chat/recieve')
def recieve_massages():
#    return db
    with open('chat.txt',mode='r') as myfile:
        return myfile.readlines()

@app.post('/chat/send')
def send_massage(massage: Text):
#    db.append(massage.dict())
#    return db[-1]
    with open('chat.txt',mode='a') as myfile:
        return myfile.write(massage)

您可以将Line-demited JSON写入文件:

import json

@app.get('/chat/recieve')
def recieve_messages():
    with open('chat.txt',mode='r') as myfile:
        return [json.loads(i) for i in myfile.readlines()]

@app.post('/chat/send')
def send_message(massage: Text):
    with open('chat.txt',mode='a') as myfile:
        return myfile.write(message.json()+'\n') #Make sure there is a line between the records

如果您需要存储的数据变得更加复杂,请考虑使用合适的数据库,例如 sqllite