Issue a POST request with url_for in Flask

寵の児 提交于 2019-12-08 16:10:15

问题


I'm trying to issue a POST request within a Jinja template in Flask. However, parameters are passed in via GET by default, and this particular method only accepts POST requests.

I tried specifying _method, as below, but it still passes the parameter with GET instead of POST.

<li><a href = "{{ url_for('save_info', _method='POST', filepath=s.name ) }}"><div class="nodes">{{ s.title}} - {{ song.owner }}</div></a></li>

(The error message is the same whether or not I specify _method).


回答1:


All links are GET requests. You can't force a POST.

An alternative would be this:

@app.route('/save_info/<filepath>', methods=['GET', 'POST'])
def save_info(filepath):
  if request.method == 'POST' or filepath:
    ...

You'll have to find a nice way to force your code to ignore that you sent a GET request.




回答2:


You could either make a form that contains only a submit button, or send the POST using AJAX or some other client side scripting. As far as I know, you can't make a link send a POST, though.




回答3:


You can add a Middelway which search for a GET argument which overwrite the http method. Look there: http://flask.pocoo.org/snippets/38/

Your new link will look like this:

<li><a href = "{{ url_for('save_info', __METHOD_OVERRIDE__='POST', filepath=s.name ) }}"><div class="nodes">{{ s.title}} - {{ song.owner }}</div></a></li>


来源:https://stackoverflow.com/questions/9246889/issue-a-post-request-with-url-for-in-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!