为何url_for()以“ static”作为第一个参数?没有static()
作者:互联网
无法理解它为什么起作用,所以我无法更改它:
我在表单中使用Flask-Admin的ImageUploadField,该字段是这样的:
image = ImageUploadField(label='Optional image',
base_path=app.config['UPLOAD_FOLDER'],
relative_path=op.relpath(app.config['UPLOAD_FOLDER']),
endpoint='static'
)
endpoint =’static’是默认值.
以这种方式在flask_admin.ext.form.upload中使用端点:
def get_url(self, field):
if field.thumbnail_size:
filename = field.thumbnail_fn(field.data)
else:
filename = field.data
if field.url_relative_path:
filename = urljoin(field.url_relative_path, filename)
return url_for(field.endpoint, filename=filename)
因此它正在传递给url_for()函数…
url_for()的结果只是在文件名前加上“ static /”.如果我尝试设定
endpoint='some_string'
当然会引发BuildError,但如果我尝试这样做:
#admin.py
class ProductForm(Form):
order = IntegerField('order')
name = TextField('name')
category = SelectField('category', choices=[])
image = ImageUploadField(label='Optional image',
base_path=app.config['UPLOAD_FOLDER'],
relative_path=op.relpath(app.config['UPLOAD_FOLDER']),
endpoint='dumb_f'
)
def dumb_f(str=''):
return str
我猜也是因为它会引发BuildError,因为dumb_f()在upload.py中不可见.
为什么url_for()甚至可以工作?第一个参数不应该是函数的名称吗?我没有静态命名方法,upload.py也没有.
解决方法:
Flask为您提供了静态端点.
请注意,我在那里使用了终结点一词; url_for()函数采用端点名称,而@ app.route()装饰器默认使用函数名称作为端点名称,但是您绝不需要使用函数名称.
您的代码不是唯一可以注册的路由和端点.在创建Flask应用程序时,它只是基于默认配置静态注册.
参见Flask
class definition source code:
# register the static folder for the application. Do that even
# if the folder does not exist. First of all it might be created
# while the server is running (usually happens during development)
# but also because google appengine stores static files somewhere
# else when mapped with the .yml file.
if self.has_static_folder:
self.add_url_rule(self.static_url_path + '/<path:filename>',
endpoint='static',
view_func=self.send_static_file)
app.add_url_rule()
method也注册了一条路由,并且Flask在此处明确指定了端点参数.
如果要从其他端点提供上传的图像,则必须自己注册.
标签:url-for,flask,flask-admin,python 来源: https://codeday.me/bug/20191028/1953620.html