Reputation: 4558
I have a legacy minimalistic api in a single python file:
#!C:/Python26/python.exe
# -*- coding: UTF-8 -*-
import json
# code ...
print "Content-Type: application/json"
print
print json.dumps(features)
Is there a way to set headers in the same way as the content type? Looking for something like:
print "Header: Access-Control-Allow-Origin *"
I want to allow all cross domains incoming requests, or limit it to specific hosts.
Upvotes: 1
Views: 3837
Reputation: 193
The answer is you need to create a HTTP header that includes the mentioned "Header: Access-Control-Allow-Origin *".
The previously suggested solution of just placing
print "Access-Control-Allow-Origin: *"
in your script fails because it doesn't create the required CR-LF line endings and the two consecutive CR-LF to end the header. Also beware the automatic linefeed of the print command. This works for me:
print("Access-Control-Allow-Origin: *\r\n"),
print('Content-Type: text/plain; charset=ISO-8859-1\r\n\r\n'),
Upvotes: 2
Reputation: 88076
Yes, but the format is simpler than what you imagine; you just need to do this:
print "Content-Type: application/json"
print "Access-Control-Allow-Origin: *"
print
print json.dumps(features)
Basically, no further magic happens on what you put inside the quotations marks there—it’s just a literal string that’ll get sent as-is as part of the response.
In other words, the headers of an HTTP response are plain text, just like the JSON data that json.dumps(features)
is putting into the response body.
The only magic is pretty simple: The way you know which part of the response is the headers and which part is the body is that there’s an empty line (extra newline) before the start of the body; everything before that newline is treated as headers by browsers and other web clients—so you can put whatever you want there, and the web server will just send it literally as-is.
Upvotes: 2