在使用curl测试API功能时,我尝试将发布数据发送到下面的路由。在观看调试时, View 会响应 301 重定向,从而阻止获取所需的数据。我做错了什么?
这是我目前的观点。
from flask import Flask, jsonify, render_template, request
from flask_cors import CORS
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route("/api/user/login/", methods=["GET", "POST"])
def login(*args, **kwargs):
print 'Got request for login'
print args
print kwargs
print request.args
print request.args.get("username")
print request.values.get("username")
print request.method
response = {'username': 'Erik'}
dict = request.args
for key in dict:
print 'form key ' + dict[key]
# return jsonify(response)
return response
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8080)
调用以下代码,
curl -d "username=Flash" http://0.0.0.0:8080/api/user/login
发起重定向
/home/user/fab/bin/python2.7 /home/user/PycharmProjects/myelm/server.py
* Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
127.0.0.1 - - [06/Sep/2017 23:04:25] "POST /api/user/login HTTP/1.1" 301 -
最佳答案
这是documentation关于此行为:
Unique URLs / Redirection Behavior Flask’s URL rules are based on Werkzeug’s routing module. The idea behind that module is to ensure beautiful and unique URLs based on precedents laid down by Apache and earlier HTTP servers.
Take these two rules:
@app.route('/projects/') def projects(): return 'The project page' @app.route('/about') def about(): return 'The about page'
Though they look rather similar, they differ in their use of the trailing slash in the URL definition. In the first case, the canonical URL for the projects endpoint has a trailing slash. In that sense, it is similar to a folder on a filesystem. Accessing it without a trailing slash will cause Flask to redirect to the canonical URL with the trailing slash.
In the second case, however, the URL is defined without a trailing slash, rather like the pathname of a file on UNIX-like systems. Accessing the URL with a trailing slash will produce a 404 “Not Found” error.
This behavior allows relative URLs to continue working even if the trailing slash is omitted, consistent with how Apache and other servers work. Also, the URLs will stay unique, which helps search engines avoid indexing the same page twice.
关于python - 为什么这个默认路由会重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46085562/