python - 使用 Flask 将值传递给函数
问题描述
我有一个包含很多列表的 base.py 文件(超过 50 个)
model1 = [
'https://',
'https://',
'https://',
'https://',
'https://',
'https://',
'https://'
]
model2 = [
'https://',
'https://',
'https://',
'https://',
'https://',
'https://',
'https://'
]
此外,另一个 func.py 文件包含用于处理来自 base.py 文件的 url 的函数
我需要从 HTML 模板中的 base.py 文件和 func.py 文件中导出函数的结果
使用 Flask,我输出链接如下
import base
def index():
return render_template("index.html",
url = base)
问题:如何将特定模型的所需url从base.py文件中的特定列表传输到func.py文件函数,并使用Flask在HTML模板中显示该函数的结果?
HTML 模板
<tr>
<td>Model</td>
<td><a href="{{ url.model1[0] }}" target="_blank">{{ price0 of func.py }}</a></td>
<td><a href="{{ url.model1[1] }}" target="_blank">{{ price1 of func.py }}</a></td>
<td><a href="{{ url.model1[2] }}" target="_blank">{{ price2 of func.py }}</a></td>
<td><a href="{{ url.model1[3] }}" target="_blank">{{ price3 of func.py }}</a></td>
<td><a href="{{ url.model1[4] }}" target="_blank">{{ price4 of func.py }}</a></td>
<td><a href="{{ url.model1[5] }}" target="_blank">{{ price5 of func.py }}</a></td>
<td><a href="{{ url.model1[6] }}" target="_blank">{{ price6 of func.py }}</a></td>
</tr>
func.py 文件包含 6 个函数,用于 base.py 文件列表中的每个函数
函数.py
def url1 (murl):
#####################
print(price)
def url2 (murl):
#####################
print(price)
解决方案
所以你需要在你的视图函数中做逻辑。
创建一个新的模型列表,其中每个模型的 url 和价格关联在一起 - 在字典中
然后,一旦您创建了新数据,您就可以将其传递给您的模板,您可以在其中循环访问它并访问值
如果每个 url 都有自己的函数,您可以将函数存储在列表中,并通过您正在循环的 url 的索引访问相关函数
请参阅这个问题 - Calling functions by array index in Python
函数.py
my_fn = [func1, func2, func3, etc]
import base
import func
def index():
models_with_links = []
for model in base:
# creating a new dict with the associate link and price with list comprehension
new_model = [{"url": link, "price": my_fn[idx](link)} for idx, link in enumerate(model)]
models_with_links.append(new_model)
return render_template("index.html", models=models_with_links)
然后你可以在 Jinja 中使用循环所以你可以遍历包含多个模型的 url,然后遍历这些模型的 url:
<tr>
<td>Model</td>
{% for model_list in models %}
{% for model in model_list %}
<td>
<a href="{{ model.url }}" target="_blank">
{{ model.price }}
</a>
</td>
{% endfor %}
{% endfor %}
</tr>
推荐阅读
- html - 如何删除一个唯一标识符是没有标签的 html 文本的元素
- neo4j - Neo4j 服务器激活错误,java.lang.IllegalStateException: ManagerFactory,java.io.FileNotFoundException
- java - 使用 MessageFormat,分组小数位
- javascript - 调整 html/css 中按钮的大小
- kotlin - 将功能委托给所有其他接口
- azure-devops - 如何通过 azure release 部署到 VM?
- jquery - FullCalendar - 引导模式加载 url 并填充输入字段
- ruby-on-rails - 在rails6上使用'data-confirm-modal'
- dockerfile - 如何从 docker 容器中验证 gcloud 服务帐户
- ios - 观看 Singleton Class 的变化