You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在GAE的/tmp目录存储文件并在Django HTML中访问?

Answers to Your App Engine /tmp Directory Questions

Let's tackle your two questions one by one, based on App Engine Standard Python 3 behavior:


1. How to save files to the /tmp directory?

Yep, it's that straightforward! You just need to set your file's save path to start with /tmp — App Engine automatically grants write access to this directory for your instance.

For example, if you're writing a simple text file in Python:

with open('/tmp/my_temp_file.txt', 'w') as temp_file:
    temp_file.write("This is stored in the instance's temp directory!")

If you're handling uploaded files in Django, you can modify the file's destination to /tmp as well. Just keep in mind: the /tmp directory is instance-specific and ephemeral. If your instance is scaled down, restarted, or replaced, any files stored there will be permanently deleted.


2. How to access /tmp files in Django HTML templates?

The {% static %} tag only works with files in your app's configured static directories (like static/), so it won't directly access /tmp files. Instead, you'll need to create a dedicated view to serve these temp files, then link to that view in your template.

Here's how to set this up:

Step 1: Create a view to serve temp files

Add this to your Django app's views.py:

from django.http import FileResponse, HttpResponseNotFound
import os

def serve_temp_file(request, filename):
    temp_file_path = os.path.join('/tmp', filename)
    
    # Check if the file exists to avoid errors
    if os.path.isfile(temp_file_path):
        # Return the file as a response (set as_attachment=True to force download)
        return FileResponse(open(temp_file_path, 'rb'), as_attachment=False)
    else:
        return HttpResponseNotFound("Temp file not found")

Step 2: Add a URL route

Update your app's urls.py to map a URL to the view:

from django.urls import path
from . import views

urlpatterns = [
    # ... your other routes ...
    path('serve-tmp/<str:filename>/', views.serve_temp_file, name='serve_temp_file'),
]

Use Django's {% url %} tag to generate the correct URL for your temp file:

<!-- For a downloadable file -->
<a href="{% url 'serve_temp_file' filename='my_temp_file.txt' %}">View Temp File</a>

<!-- For an image -->
<img src="{% url 'serve_temp_file' filename='my_temp_image.jpg' %}" alt="Temp Image">

Important note: Since /tmp is instance-specific, if your app is running multiple instances, a request might hit an instance that doesn't have the file you saved. If you need persistent, cross-instance file storage, consider using Cloud Storage instead.


内容的提问来源于stack exchange,提问作者Aayush Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 19:32:43