程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python uses fastapi to upload files

編輯:Python

Catalog

Use File File upload

Use UploadFile File upload

UploadFile Properties of

Setting the upload file is optional

Upload multiple files

Knowledge points supplement

Use File File upload

Use Form Form upload file ,fastapi Use File Get uploaded files .

The parameter type specified is bytes:file: bytes = File(), At this time, all the contents of the file will be read into memory , Suitable for small files .

Use File It needs to be installed in advance python-multipart

from fastapi import FastAPI, File ​app = FastAPI() ​@app.post("/files/")async def create_file(file: bytes = File()): return {"file_size": len(file)}

As long as the type of the variable is declared in the path operation function bytes And used File, be fastapi All the contents of the uploaded file will be read into the parameters .

Use UploadFile File upload

For large documents , It is not suitable to read all the contents of the file into memory , At this time to use UploadFile

from fastapi import FastAPI, UploadFile ​app = FastAPI() ​@app.post("/uploadfile/")async def create_upload_file(file: UploadFile): return {"filename": file.filename}

and bytes comparison , Use UploadFile It has the following benefits :

No need to use File() As the default value of the parameter in the path operation function

The contents of the file will not be loaded into memory , Instead, a certain amount of data is read in batches , Hard disk storage while reading .

You can get the metadata of the file .

Variables of this type can be operated like file variables .

UploadFile Properties of

filename: The type is str, To get the name of the file , such as :myimage.png

content_type: The type is str, Used to get the type of file , such as :image/png

file: Class file object , It's a standard python File object

In addition to these four basic attributes ,UploadFile There are three more async Method :

write, take str perhaps bytes Write to file

read: Reading documents

seek: Move the cursor

close: Close file

# Get file content contents = await myfile.read() Setting the upload file is optional

The default setting is None that will do

from typing import Union ​ from fastapi import FastAPI, File, UploadFile ​ app = FastAPI() ​ ​ @app.post("/files/") async def create_file(file: Union[bytes, None] = File(default=None)): if not file: return {"message": "No file sent"} else: return {"file_size": len(file)} ​ ​ @app.post("/uploadfile/") async def create_upload_file(file: Union[UploadFile, None] = None): if not file: return {"message": "No upload file sent"} else: return {"filename": file.filename} Upload multiple files

The type of the parameter of the parameter is list : The list element is bytes perhaps UploadFile

from typing import List ​ from fastapi import FastAPI, File, UploadFile ​ app = FastAPI() ​ ​ @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]): return {"filenames": [file.filename for file in files]} Knowledge points supplement

1.FastAPI brief introduction

FastAPI What is it?

FastAPI It's a modern , Fast ( High performance )python web frame . Based on standards python Type tips , Use python3.6+ structure API Of Web frame .

FastAPI The main features are as follows :

Fast : Very high performance , And NodeJS and Go Quite a ( Thank you for that Starlette and Pydantic), It's the fastest Python One of the frames .

Fast coding : Increase the development speed by about 200% To 300%.

Less bug: The reduction is about 40% Human errors caused by developers .

intuitive : Powerful editor support , Less debugging time .

Simple : Easy to use and learn . Reduce the time spent reading documents .

The code is concise : Minimize code duplication . Each parameter can declare multiple functions , Reduce the number of programs bug.

robust : Production code automatically generates interactive documents .

Based on standards : Based on and fully compatible with API Open standards for :OpenAPI and JSON Pattern .

FastAPI Standing on the shoulders of giants :

Starlette Used to build Web parts .

Pydantic For the data part .

Environmental preparation

install fastapi

pip install fastapi

For production environment , I need one more ASGI The server , Such as Uvicorn or Hypercorn

pip install "uvicorn[standard]"

Getting started sample program

Create a new one main.py, Write the following program :

from fastapi import FastAPIapp = FastAPI()@app.get("/")def read_root():return {"Hello": "World"}@app.get("/items/{item_id}")def read_item(item_id: int, q: str = None):return {"item_id": item_id, "q": q}

Run the program :

uvicorn main:app --reload
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [28720]
INFO: Started server process [28722]
INFO: Waiting for application startup.
INFO: Application startup complete.

This is about Python utilize fastapi This is the end of the article on uploading files , More about Python fastapi Please search the previous articles of SDN or continue to browse the related articles below. I hope you will support SDN more in the future !



  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved