FastAPI を使用してデータを POST した後にファイルをダウンロードするには?
FastAPI とファイル処理を使用する場合、一般的なタスクの 1 つは、ユーザーが送信後にファイルをダウンロードできるようにすることです。 POST リクエストを通じてデータを送信します。これは、FileResponse クラスを利用し、ヘッダーとコンテンツ タイプを適切に構成することで実現できます。
以下のコードでは、データを処理してオーディオを返す POST エンドポイントを設定する方法を示します。ファイル(MP3)をダウンロードします。フォーム データ タイプを使用してユーザー入力をキャプチャし、オーディオ ファイルを生成します。
オプション 1: 個別のダウンロード エンドポイントを使用する
このアプローチでは、ファイルのダウンロードを処理します。
<code class="python">from fastapi import FastAPI, Request, Form, File, UploadFile from fastapi.responses import FileResponse, HTMLResponse from fastapi.templating import Jinja2Templates from gtts import gTTS app = FastAPI() templates = Jinja2Templates(directory="templates") def text_to_speech(language: str, text: str) -> str: tts = gTTS(text=text, lang=language, slow=False) filepath = "temp/welcome.mp3" tts.save(filepath) return f"Text to speech conversion successful to {filepath}" @app.get("/") def home(request: Request): return templates.TemplateResponse("index.html", {"request": request}) @app.post("/text2speech") def text2speech(request: Request, message: str = Form(...), language: str = Form(...)): if message and language: output = text_to_speech(language, message) path = "temp/welcome.mp3" filename = os.path.basename(path) headers = {"Content-Disposition": f"attachment; filename={filename}"} return FileResponse(path, headers=headers, media_type="audio/mp3")</code>
GET エンドポイントはメイン ページとして機能し、POST エンドポイントはユーザー入力を処理してオーディオ ファイルを生成します。 FileResponse は、ファイルのダウンロードに適切なヘッダーの設定を処理します。
テンプレートに、ファイルのダウンロードをトリガーするリンクを追加できます:
<code class="html"> <title>Download File</title> <a href="%7B%7B%20url_for('text2speech')%20%7D%7D">Download File</a> </code>
オプション 2: エンドポイント ファイル内ダウンロード
または、データを処理する同じエンドポイント内でファイルのダウンロードを処理できます。
<code class="python">from fastapi import FastAPI, Request, Form app = FastAPI() def text_to_speech(language: str, text: str) -> str: tts = gTTS(text=text, lang=language, slow=False) filepath = "temp/welcome.mp3" tts.save(filepath) return f"Text to speech conversion successful to {filepath}" @app.post("/text2speech") def text2speech(request: Request, message: str = Form(...), language: str = Form(...)): output = text_to_speech(language, message) return {"filepath": filepath}</code>
テンプレートでは、JavaScript を使用して、から返されたファイルパスを使用してファイルのダウンロードをトリガーできます。エンドポイント:
<code class="html"><script> const filepath = "{{ filepath }}"; window.location.href = filepath; </script></code>
大きなファイルの処理
メモリ制限を超えるファイルについては、StreamingResponse:
<code class="python">from fastapi.responses import StreamingResponse @app.post("/text2speech") def text2speech(request: Request, message: str = Form(...), language: str = Form(...)): ... def iterfile(): with open(filepath, "rb") as f: yield from f headers = {"Content-Disposition": f"attachment; filename={filename}"} return StreamingResponse(iterfile(), headers=headers, media_type="audio/mp3")</code>
ダウンロード後のファイルの削除
ディスク領域の蓄積を防ぐために、ファイルをダウンロードした後は削除することをお勧めします。 BackgroundTasks を使用すると、ファイルの削除をバックグラウンド タスクとしてスケジュールできます:
<code class="python">from fastapi import BackgroundTasks @app.post("/text2speech") def text2speech(request: Request, background_tasks: BackgroundTasks, ...): ... background_tasks.add_task(os.remove, path=filepath) return FileResponse(filepath, headers=headers, media_type="audio/mp3")</code>
以上がFastAPI を使用してデータを POST した後にファイルをダウンロードするにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

numpyarraysarasarebetterfornumeroperations andmulti-dimensionaldata、whilethearraymoduleissuitable forbasic、1)numpyexcelsinperformance and forlargedatasentassandcomplexoperations.2)thearraymuremememory-effictientivearientfa

NumPyArraySareBetterforHeavyNumericalComputing、whilethearrayarayismoreSuitableformemory-constrainedprojectswithsimpledatatypes.1)numpyarraysofferarays andatiledance andpeperancedatasandatassandcomplexoperations.2)thearraymoduleisuleiseightweightandmemememe-ef

ctypesallowsinging andmanipulatingc-stylearraysinpython.1)usectypestointerfacewithclibrariesforperformance.2)createc-stylearraysfornumericalcomputations.3)passarraystocfunctions foreffientientoperations.how、how、becuutiousmorymanagemation、performanceo

Inpython、「リスト」は、「リスト」、自由主義的なもの、samememory効率が高く、均質な偶然の瞬間の想起された「アレイ」の「アレイ」の「アレイ」の均質な偶発的な想起されたものです

pythonlistsandarraysaraybothmutable.1)listsareflexibleandsupportheTeterdatabutarlessmemory-efficient.2)Arraysaremorememory-efficientiant forhomogeneousdative、ressivelessatile、ressing comerttytytypecodeusageodoavoiderorors。

PythonとCにはそれぞれ独自の利点があり、選択はプロジェクトの要件に基づいている必要があります。 1)Pythonは、簡潔な構文と動的タイピングのため、迅速な開発とデータ処理に適しています。 2)Cは、静的なタイピングと手動メモリ管理により、高性能およびシステムプログラミングに適しています。

PythonまたはCの選択は、プロジェクトの要件に依存します。1)迅速な開発、データ処理、およびプロトタイプ設計が必要な場合は、Pythonを選択します。 2)高性能、低レイテンシ、および緊密なハードウェアコントロールが必要な場合は、Cを選択します。

毎日2時間のPython学習を投資することで、プログラミングスキルを効果的に改善できます。 1.新しい知識を学ぶ:ドキュメントを読むか、チュートリアルを見る。 2。練習:コードと完全な演習を書きます。 3。レビュー:学んだコンテンツを統合します。 4。プロジェクトの実践:実際のプロジェクトで学んだことを適用します。このような構造化された学習計画は、Pythonを体系的にマスターし、キャリア目標を達成するのに役立ちます。


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

ZendStudio 13.5.1 Mac
強力な PHP 統合開発環境

Dreamweaver Mac版
ビジュアル Web 開発ツール

VSCode Windows 64 ビットのダウンロード
Microsoft によって発売された無料で強力な IDE エディター

AtomエディタMac版ダウンロード
最も人気のあるオープンソースエディター

SecLists
SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。

ホットトピック









