1

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

print 'HTTP/1.0 200 OK' and add a size definition for dont check whole answer for is correct ?
@dsgdfg yeah I wasn’t sure the snippet in the question was complete, or maybe getting called by something else? The only part I meant to address was just the specific question of how to add that one header
2

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'),

1 Comment

Thank you. Your answer saved me hours of frustration. I wish all the people answering questions here would be as conscientious about providing answers that actually solve the problem, as opposed answers that "almost" solve the problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.