[英]How to optimize text output in if/ else for Python 3.6?
def statistic():
if db.session.query(func.count(Exchange.exchange_id)).filter_by(user_id=g.user.user_id).scalar() == 0:
text_info = '(big test message 1)'
else:
text_info = '(big message 2)'
return render_template('console/statistic.html', text_info=text_info)
你好,我使用的是 Python 3.6 + Flask。 我从 5 页上的变量text_info
输出文本。 但是文本很大并且在代码中看起来很糟糕。 如何优化和最小化text_info
的输出? 从文件打开? 你能说什么? 谢谢
最简单的方法
您可能确实从文件中加载文本:
(...)
with open('file_one.txt') as file:
text_info = file.read()
(...)
但是请注意,您最终会为应用程序中的每条消息添加一个with
表达式的上下文管理器with
并且可能您必须N files for N messages
创建N files for N messages
......
正确的方法
您可以为应用程序准备一个简单的配置(在这个例子中,我将使用 TOML,假设文件名为config.toml
):
[strings]
first = "my first big string"
second = "my second big string"
然后您可以按如下方式使用它:
import pytoml # you can install it using pip
(...)
with open('config.toml', 'rb') as config:
cfg = pytoml.loads(config.read())
string1 = cfg['strings']['first']
string2 = cfg['strings']['second']
(...)
请记住,硬编码值通常不是一个好主意。 在实际应用中,您最终要么使用某种配置文件(yaml/toml/ini/properties/other),要么通过某些 API 调用获取这些值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.