-
[fastapi] upload json filepython 2023. 2. 25. 13:43
json file 하나를 업로드하여 파일 내 데이터를 리턴하는 api 작성.
import uvicorn import json from fastapi import FastAPI, File, UploadFile app = FastAPI(title="test-json-file-upload", version='1.0.0',) ## file upload test @app.post("/upload") def upload(file: UploadFile = File(...)): try: # with open(file.filename, 'wb') as f: # f.write(contents) # print(f"[upload] file.filename {file.filename}") # with file.file.read() as contents: # json_input = json.loads(contents) # error! contents = file.file.read() json_input = json.loads(contents) except Exception as err: return {"message": f"There was an error uploading {file.filename}", "errMsg": f"{err}"} finally: file.file.close() return {"message": f"Successfully uploaded {file.filename}", "data": json_input} if __name__ == '__main__': uvicorn.run("main:app", host='127.0.0.1', port=4000, reload=True)
여러파일을 가져올 경우
@app.post("/files/") async def create_files(files: List[bytes] = File(...)): return {"file_sizes": [len(file) for file in files]} @app.post("/uploadfiles") async def create_upload_files(files: List[UploadFile] = File(...)): UPLOAD_DIRECTORY = "./" for file in files: contents = await file.read() with open(os.path.join(UPLOAD_DIRECTORY, file.filename), "wb") as fp: fp.write(contents) return {"filenames": [file.filename for file in files]}
'python' 카테고리의 다른 글
[fastapi] 로컬PC에 세팅 시 해야할 Tasks (0) 2023.03.30 python으로 json data 처리하기 (0) 2023.03.17 python으로 dummy 데이터와 REST API test code 작성하기 (0) 2023.03.14 매번 검색하는 기본 코드 - python version (0) 2023.01.17 pyinstaller로 실행프로그램 만들면서 빡쳤던점 정리 (1) 2023.01.17