微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

FastAPI 从文件读写

如何解决FastAPI 从文件读写

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

使用来自 pydantic 的 BaseModel 进行按摩,因此它有 2 个字段:昵称和按摩内容

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

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

  1. 不能让写入同时使用两个字段(只需要昵称\按摩)
  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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?