如何为Python中返回HTML文件的函数添加注解?遇‘html未定义’报错
Python返回HTML文件的函数类型注解方案
你遇到的问题很直接:直接写-> html会报错,是因为Python会把html当成一个变量去查找,但你根本没定义过这个变量,所以必须用引号把它包起来当作字符串——不过这种写法只是个注释性质的标记,没法做实际的类型校验。下面给你几种更规范的方案:
方案1:用str标注(最直接)
render_template本质上返回的是HTML格式的字符串,所以直接用str作为返回类型完全没问题,代码如下:
from flask import Flask, render_template app = Flask(__name__) @app.route('/entry') def entry_page() -> str: return render_template('entry.html', the_title='Welcome to searchtools on the web!') app.run()
方案2:用flask.Response标注(更贴合Flask逻辑)
Flask的视图函数最终会把返回的字符串自动包装成Response对象,所以用Response作为返回类型更准确,能体现Flask的处理流程:
from flask import Flask, render_template, Response app = Flask(__name__) @app.route('/entry') def entry_page() -> Response: return render_template('entry.html', the_title='Welcome to searchtools on the web!') app.run()
关于原写法的说明
你原来的-> 'html'写法其实是合法的(Python 3.7+支持字符串形式的类型注解,属于"前向引用"的一种延伸用法),但它只是个可读性标记,不会被类型检查工具(比如mypy)识别为有效类型,适合用来直观告诉其他开发者这个函数返回HTML内容,但没有实际的类型校验作用。
内容的提问来源于stack exchange,提问作者James Scott
相关产品推荐
相关产品推荐

