如何解决FastAPI 从文件读写
我开始学习python,遇到了一个小问题。 我尝试使用 FastAPI 创建小聊天,只有 2 个请求,get(msg) 和 post(msg)。
使用来自 pydantic 的 BaseModel 进行按摩,因此它有 2 个字段:昵称和按摩内容
如果我使用代码中的本地数据库它工作正常(我用 post 插入到 dict 然后将它移动到数据库)并且它呈现的很好,就像 Json 一样。
- 不能让写入同时使用两个字段(只需要昵称\按摩)
- 它看起来不像 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 举报,一经查实,本站将立刻删除。