django - 如何通过 Django 中的表单数据发布将文件上传到 GAE?
问题描述
我有我的 Django webapp,它在我的一个模型中包含一个方法,用于将用户选择的文件(从表单)上传到指定的文件目录。但在 Google App Engine(使用 gcloud)上部署我的应用程序后,我无法使用该模型。我正在为我的 Django 应用程序使用 Google MySQL 数据库。此外,我无法在我的应用程序中使用 os.makedir() 方法,因为服务器提示存在只读权限
模型.PY
def upload_to(instance, filename):
now = timezone_now()
base, ext = os.path.splitext(filename)
ext = ext.lower()
rootpath = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
return rootpath + f"/face_detector/static/face_detector/img/{now:%Y%m%d%H%M%S}{ext}"
# Do add the date as it prevents the same file name from occuring twice
# the ext is reserved for the file type and don't remove it
class PicUpClass(models.Model):
picture = models.ImageField(_("picture"), upload_to=upload_to, blank=True, null=True)
我得到的错误
/add-dataset [Errno 30] 处的 OSError 只读文件系统:'/srv/face_detector/static/face_detector/img/20200228084934.jpg' 请求方法:POST 请求 URL: https ://agevent-269406.appspot.com /add-dataset Django 版本:3.0.2 异常类型:OSError 异常值:[Errno 30] 只读文件系统:'/srv/face_detector/static/face_detector/img/20200228084934.jpg' 异常位置:/env/lib /python3.7/site-packages/django/core/files/storage.py 在 _save,第 267 行 Python 可执行文件:/env/bin/python3.7 Python 版本:3.7.6
我是python的菜鸟,所以请给我一些基本的解决方案。
解决方案
您出现此 Read-only file system 错误的原因是默认 models.ImageField 将上传的图像保存到您的项目文件夹中,并且它对于 Google App Engine 应用程序是只读的。
您必须使用Google Cloud Storage上传图片(如果不是临时数据,则为最佳选择),否则对于临时文件,您可以将它们写入 /tmp 目录,该目录将存储在实例的 RAM中,但如果您删除实例,则会被删除,您扩大或缩小您的实例,或者如果您的实例没有流量(用户)。如果您使用手动缩放,这将不是问题。但是正如我之前所说,对于自动缩放 tmp 目录是有风险的。
对于 tmp 目录:
你可以设置你的 rootpath = '/tmp/'
您可以通过 views.py 中的代码从 tmp 目录中检索图像,以在 HTML 中提供它们。
推荐阅读
- python - Python os.getenv() 在 Windows 上返回不正确的值 - 有替代方案吗?
- python-3.x - 递归第二次不起作用。- Python
- javascript - external function call, promise, async and Mongo - confused
- perl - 今天的日期匹配不正确
- python - 函数未返回预期实例
- java - 拆分和隐蔽以使从文本文件中读取的值加倍时找不到源错误
- asynchronous - F# 在另一个线程上运行阻塞调用,在异步工作流中使用
- android - 如何使用 okio/okhttp 解码 http 请求数据包
- elasticsearch - Elasticsearch 重新索引竞争条件
- c++ - 检测两条线是否相交的算法在 SFML 中没有给出准确/想要的结果