python - 我无法在 FastAPI 中读取上传的 csv 文件

标签 python csv fastapi

我正在尝试遍历 csv 文件。但是,接收到的文件很难阅读。我搜索了这个,我找不到明确的解决方案!

@app.get("/uploadsequence/")
async def upload_sequence_form():
    return HTMLResponse("""
            <!DOCTYPE html>
            <html>
                <head>
                    <title>sequence upload</title>
                </head>
                <body>
                    <h1>upload sequence .CSV file</h1>
                    <form method='post' action='/uploadsequence/' enctype='multipart/form-data'>
                        Upload a csv file: <input type='file' name='csv_file'>
                        <input type='submit' value='Upload'>
                    </form>
                </body>
            </html>
            """)

@app.post("/uploadsequence/")
async def upload_sequence(csv_file: UploadFile = File(...), db = Depends(get_db)):
        csv_file_encoded = TextIOWrapper(csv_file.file, encoding='utf-8')
        csv_reader = csv.DictReader(csv_file_encoded)
        for row in csv_reader:
            if row["Well Type"] in ["RIG MAINTENANCE","RIG MOVE","RIG COMMISSIONING","ABANDONMENT","LEARNINGCURVE"]:
                crud.insert_sequence_record(db=db, row=row,is_drilling=False)
            else:
                crud.insert_sequence_record(db=db, row=row,is_drilling=True)
它给了我这个错误:csv_file_encoded = TextIOWrapper(csv_file.file, encoding='utf-8') AttributeError: 'SpooledTemporaryFile' object has no attribute 'readable'我改了UploadFilebytes :
@app.post("/uploadsequence/")
async def upload_sequence(csv_file: bytes = File(...), db = Depends(get_db)):
        csv_file_encoded = TextIOWrapper(csv_file, encoding='utf-8')
        csv_reader = csv.DictReader(csv_file_encoded)
        for row in csv_reader:
            if row["Well Type"] in ["RIG MAINTENANCE","RIG MOVE","RIG COMMISSIONING","ABANDONMENT","LEARNINGCURVE"]:
                crud.insert_sequence_record(db=db, row=row,is_drilling=False)
            else:
                crud.insert_sequence_record(db=db, row=row,is_drilling=True)
它给出了这个错误:csv_file_encoded = TextIOWrapper(csv_file, encoding='utf-8') AttributeError: 'bytes' object has no attribute 'readable'我摆脱了编码:
@app.post("/uploadsequence/")
async def upload_sequence(csv_file: bytes = File(...), db = Depends(get_db)):
        # csv_file_encoded = TextIOWrapper(csv_file, encoding='utf-8')
        csv_reader = csv.DictReader(csv_file)
        for row in csv_reader:
            if row["Well Type"] in ["RIG MAINTENANCE","RIG MOVE","RIG COMMISSIONING","ABANDONMENT","LEARNINGCURVE"]:
                crud.insert_sequence_record(db=db, row=row,is_drilling=False)
            else:
                crud.insert_sequence_record(db=db, row=row,is_drilling=True)
它给出了这个错误:self._fieldnames = next(self.reader) _csv.Error: iterator should return strings, not int (did you open the file in text mode?)

最佳答案

我使用以下内容来读取 csv 文件。 codecs.iterdecode为我工作。

csv_reader = csv.reader(codecs.iterdecode(csv_file.file,'utf-8'))

关于python - 我无法在 FastAPI 中读取上传的 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63868046/

相关文章:

python - 我在 python 速成类(class)书中学习文件和异常。无法弄清楚为什么它说 votes = Judge.read() 没有可写的属性

python - 多个 json 转 csv

python-3.x - asyncpg - 无法执行操作 : another operation is in progress

python - sqlalchemy.exc.OperationalError : (psycopg2. OperationalError) 与 PostgreSQL

python - 如何限制 FastAPI 请求 header 中的内容类型

python - 在另一个数据框行内的数据框行中查找单词

python - 在 Python、wx.python 中使用变量名中的占位符

python - csv 中第一位数字的数字频率,不导入

mysql - 在数据库中查找尽可能接近的精确匹配 - 哪种方式更好?

csv - awk 可以处理在引用字段中包含逗号的 CSV 文件吗?