python - django - 陷入路径生成问题
问题描述
功能:
def custom_path(path):
new_path = os.path.abspath(path)
def get_path():
return new_path
return get_path
问题在于custom_path
,当在此get_image_path
函数中调用时,它会创建一个具有绝对路径的目录,例如<function custom_path at 0x7f432d99e158>/somedir/finalName.*ext
,但我希望它以字符串表示形式返回。我的代码:
def get_image_path(instance, file):
'''
saves file to some location
'''
file_path = custom_path*
new_file = random.randint(1, 45360789120)
name, ext = get_file_ext(file)
ranstr = random_string_generator(size=4)
final_ = f'{ranstr}_{new_file}{ext}'
return f'{file_path}/{new_file}/{final_}'
发件人:
from ... import custom_path, get_image_path
custom_path('posts')
class Post(models.Model):
...
...
image = models.FileField(upload_to=get_image_path, null=True,
blank=True, verbose_name='article image (optional)')
...
...
否则,我必须将此功能修改为...
def get_image_path(instance, file):
...
...
return f'posts*/{new_file}/{final_}' # and so on for *different models..
我也尝试过这样的事情......
def get_image_path(instance, file):
...
...
return f'{new_file}/{final_}'
base = os.path.dirname('posts/')
upload_path = base + os.path.join(str(get_image_path))
class Post(models.Model):
...
...
image = models.FileField(upload_to=upload_path, null=True,
blank=True, verbose_name='article image (optional)')
...
...
输出:''/newDir/newFile.*ext
,如何摆脱它?️️
解决方案
该函数custom_path
返回内部函数get_path
,因此它的工作方式如下:
foo = custom_path() # foo is a function
path = foo() # path is str now
或者,更短的代码:
path = custom_path()()
这是我的测试:
>>> import os
>>> def custom_path(path):
... new_path = os.path.abspath(path)
... def get_path():
... return new_path
... return get_path
...
>>> foo = custom_path('test')
>>> foo
<function custom_path.<locals>.get_path at 0x7f7c123f8620>
>>> path = foo()
>>> path
'/home/pashawnn/test'
在您的情况下,您必须在 f-string 中添加大括号:
return f'{file_path()}/{new_file}/{final_}'
推荐阅读
- uninstallation - redmine插件无法卸载
- javascript - 将数据“以编程方式”加载到 html 输入类型文件
- mongodb - 如何知道我所在的月份是否与某个日期重合
- android - 从工作表对话框中选择选项后选择图像时,Android Studio Kotlin webview 应用程序崩溃
- reactjs - 反应导航 5.x 中的自定义抽屉组件无法正常工作
- swift - 如何在 macOS 上使用 AppKit 使鼠标滚轮水平滚动
- amazon-s3 - Aws S3 Select ScanRange 未按预期工作并提供整个文件结果
- firebase - Flutter:未处理的异常:错误状态:该批次已提交,无法再更改
- python - 使用硒时如何防止出现异常
- angular - 相互依赖的 Angular 库辅助入口点