Issue
Consider this web service:
from flask import Flask, jsonify, Blueprint
app = Flask(__name__)
@app.route("/<int:d>")
@app.route("/", defaults={"d": 1})
def a(d):
return jsonify({"d": d})
If I use call it with a parameter other than the default, it returns the correct result:
$ curl http://localhost:5000/2
{
"d": 2
}
But if I call it with the default parameter value, it gives me a redirect to the version without the parameter:
$ curl http://localhost:5000/1
<!doctype html>
<html lang=en>
<title>Redirecting...</title>
<h1>Redirecting...</h1>
<p>You should be redirected automatically to the target URL: <a href="http://localhost:5000/">http://localhost:5000/</a>. If not, click the link.
Is there a good way to avoid this behaviour?
The service is being accessed by an automated client that is too stupid to understand the redirect and which dies horribly on what should be a straightforward RPC.
Solution
Putting the default value as a default for the function argument rather than the route/endpoint param avoids that redirect:
@app.route("/<int:d>")
@app.route("/")
def a(d=1): # `d` is defaulted here
return jsonify({"d": d})
With curl
, we can see that no redirection occurs.
$ curl localhost:5000/1
{"d":1}
$ curl localhost:5000/
{"d":1}
$ curl localhost:5000
{"d":1}
$ curl localhost:5000/2
{"d":2}
Also with requests
:
r = requests.get("http://localhost:5000/1")
assert r.history == [] # no redirects
Answered By - aneroid
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.