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

将 fastAPI POST 保存到 csv 选项 1选项 2

如何解决将 fastAPI POST 保存到 csv 选项 1选项 2

我有一个发送 json 数据的气象站,想制作一个 fastAPI 服务器来接收它并将其保存到磁盘。目前我有

from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class WeatherItem(BaseModel):
    wind_direction_raw: int
    rain_amount_raw: int
    timestamp: list = []
    elapsed_time: int
    wind_speed_raw: int
    message_id: int

@app.post("/station")
async def create_item(item: WeatherItem):
    return item

当我用 uvicorn main:app --host 192.168.1.151 --port 9494 启动它并从 curl 发送测试数据时效果很好

curl -X POST -H "Content-Type: application/json" --data '{"elapsed_time": 6245,"timestamp": [2020,7,26,12,2,21,6,208],"wind_direction_raw": 108,"wind_speed_raw": 5,"message_id": 666,"rain_amount_raw": "0"}' http://192.168.1.151:9494/station

现在我需要将这些数据保存到磁盘。我认为最简单的方法是将其附加到 csv 文件中。但我不知道如何将 pydantic 模型导出到 csv。有没有一种直接的方法可以做到这一点,还是首选其他序列化方法?我想在 R 中分析这些数据,因此我需要以一种可互换的格式将其存储在磁盘上。

解决方法

据我所知,您有以下选择:

选项 1

通过像这样枚举整个条目列表,将直接值附加到 CSV 文件中

<?php

// create a blank image
$image = imagecreatetruecolor(400,300);

// fill the background color
$bg = imagecolorallocate($image,0);

// choose a color for the ellipse
$col_ellipse = imagecolorallocate($image,255,255);

// draw the white ellipse
imagefilledellipse($image,200,150,300,$col_ellipse);

// output the picture
header("Content-type: image/png");
imagepng($image); ?>

(这是阻塞版本)

需要注意的是,您也可以创建一个字典并迭代这些值,然后附加它们,尽管很难保留条目之间的顺序..

选项 2

使用pandas将文件加载到内存中,附加到with open("myFile.csv","a") as f: f.write(f"{model.entry},{model.another_entry}") ,然后将数据保存到文件中

DataFrame
,

@Isabi 有一个很好的答案,让我走上了正轨,我已经接受了。但为了完整起见,我去了

import csv

...

@app.post("/station")
async def create_item(item: WeatherItem):

    write_path = "/home/pi/weather_station/data/weather_data_" + date.today().strftime("%Y-%m-%d") + ".csv"

    with open(write_path,"a") as f:
        writer = csv.writer(f)
        writer.writerow(dict(item).values())
    return item

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