我有一个要在index.html
上显示的模板(GET
),并且是一个在POST
上添加了变量的模板。
app.py:
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def hello():
return render_template("index.html")
@app.route("/", methods=["POST"])
def hello_():
return render_template("index.html", string_="Success!")
if __name__ == "__main__":
app.run(host='0.0.0.0', port=4567)
index.html:
<html>
<head>
<script type="text/javascript" src="/static/jquery.js"></script>
</head>
<body>
<button onclick="signIn();">Sign In</button>
<h1>{{ string_ }}</h1>
<script>
function signIn() {
var data = "data";
$.ajax({
type : "POST",
data: JSON.stringify(data, null, '\t'),
contentType: 'application/json',
success: function(result) {
console.log(result);
}
});
}
</script>
</body>
</html>
追溯:
* Running on http://0.0.0.0:4567/ (Press CTRL+C to quit)
127.0.0.1 - - [11/Dec/2015 11:16:17] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [11/Dec/2015 11:16:17] "GET /static/jquery.js HTTP/1.1" 304 -
127.0.0.1 - - [11/Dec/2015 11:16:21] "POST / HTTP/1.1" 200 -
我没有收到错误,但是变量string_
没有出现在POST
的模板中(单击按钮后)。我设置为在POST
上渲染的模板似乎无法正常工作。
是否可以基于request.method
在Flask中渲染其他模板?
参考方案
将它分为两条截然不同的路径是最有意义的,一条为GET
服务,另一条为POST
服务。
@app.route('/')
def index_as_get():
return render_template('index.html', name="")
@app.route('/', methods=["POST"])
def index_as_post():
r = request.get_json()
name = r['name']
return render_template('index.html', name=name)
请注意,您实际上必须通过REST客户端来调用此行为,该客户端可以在您注意到任何内容之前对根页面调用POST请求。
flask:异常后停止服务器 - python我想在发生未处理的异常时立即停止我的Flask服务器。这是一个例子:from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): 1/0 # argh, exception return 'Hello World!' i…
Python / Flask-如何在响应中返回有效的JSON而不是字符串? - python我正在使用Flask Restful创建一个简单的API,该API在get Response中返回JSON。我所有的方法都很好,我的问题是响应结果中的细节,因为JSON实际上是以字符串形式出现的,我不知道该怎么做。当我用json.dumps()转换python dict时会发生问题我尝试不使用json.dumps()方法来执行此操作,并且我的结果采用所需的格…
Flask模板中的全局变量 - python可能不是准确的标题,因为我是flask / python的新手。我正在开发一种内部工具,供不同团队使用。每个团队都有不同的部署阶段,例如alpha,beta|test,prod,并且它们还具有多个区域,例如NA,EU,AP等。现在,当我使用redirect_template时,我将发送stage和region作为变量,然后在模板中使用它们。但是,对每个red…
Flask-RESTful-返回自定义响应格式 - python我已经按照以下Flask-RESTful文档定义了自定义响应格式。app = Flask(__name__) api = restful.Api(app) @api.representation('application/octet-stream') def binary(data, code, headers=None): resp =…
如何在Flask中生成临时下载? - python我有一个Flask应用,可让用户下载MP3文件。如何使下载的URL仅在特定时间段内有效?例如,我不想让任何人简单地转到example.com/static/sound.mp3并访问文件,而是希望验证每个请求以防止不必要的带宽。我正在使用Apache服务器,但是如果更容易实现,我可能会考虑切换到另一个服务器。另外,我不想使用Flask来提供文件,因为这会通过迫…