python - 为什么这个默认路由会重定向?

标签 python api redirect curl flask

在使用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/

相关文章:

python - 如何在 Python 中解析 JSON 文件中的值

python - 没有模块名称 'sklearn.forest.ensemble'

javascript - 从 HTML5 视频中获取音频

.htaccess - Htaccess 从 example.com/en/app 重定向到 example.com/app?lang=en

.htaccess 将子域重定向到外部 URL

python - 如何在本地主机上正确安装 django 注册?

python - numba jitclass - 属性 a.x 是 a.x 返回 False

api - REST API 最佳实践 : Where to put parameters?

c - 使用 winHttpApi 或套接字发送大文件是否明智?

c - 我怎么能拦截 linux 系统调用?