Skip to content

Commit 6a0b6ed

Browse files
georges-armTamarChristinaArm
authored andcommitted
Automatically give JSON response for /machine/<id>/ when using curl.
The view already accepts ?json=1 as a request parameter to force a JSON response. This commit extends that behaviour to additionally check the HTML Accept header, such that text-only requests (curl) give a JSON result automatically.. Finally, we use the machine __json__ method rather than adding name/id manually, which gives us the full machine fields in the result. Change-Id: I0214d23996b68ee1cb23dae55b6929b40f52ea0b
1 parent 8c908db commit 6a0b6ed

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

lnt/server/ui/views.py

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,21 @@ def get_redirect_target():
6666
if is_safe_url(target):
6767
return target
6868

69+
70+
def prefer_json_response(request):
71+
# most browsers will accept both html and json (or just */*), but with json
72+
# weighted lower.
73+
# e.g. firefox: text/html: 1.0, application/json (implicit in */*): 0.8
74+
# chrome: text/html: 1.0, application/json (implicit in */*): 0.8
75+
# lynx: text/html: 1.0, application/json (implicit in */*): 0.01
76+
# curl: */* (both implicitly 1.0)
77+
# since we want curl to return json if possible by default, break ties such
78+
# that we prefer json
79+
json_weight = request.accept_mimetypes['application/json']
80+
html_weight = request.accept_mimetypes['text/html']
81+
return json_weight >= html_weight or request.args.get('json')
82+
83+
6984
###
7085
# Root-Only Routes
7186

@@ -317,10 +332,8 @@ def v4_machine(id):
317332
except NoResultFound:
318333
abort(404, "Invalid machine id {}".format(id))
319334

320-
if request.args.get('json'):
321-
json_obj = dict()
322-
json_obj['name'] = machine.name
323-
json_obj['id'] = machine.id
335+
if prefer_json_response(request):
336+
json_obj = machine.__json__()
324337
json_obj['runs'] = []
325338
for order in associated_runs:
326339
rev = order[0].llvm_project_revision

0 commit comments

Comments
 (0)