Search code examples
pythonhtmlxmldreamhosttype-declaration

Using Python on Dreamhost, return XML document (not HTML)


The Dreamhost Python documentation specifies that a Python script must print the HTML type declaration as the first line of output. However, I need to produce an XML response for a third-party API. Here's what I've tried:

  • Set type declaration to XML. Dreamhost throws an error when I do this.

  • Set type declaration to HTML, followed by an XML type declaration. The third-party API couldn't parse this.

How can I work around this limitation?


Solution

  • The relevant sentence in the page you linked to is:

    If you want to view printed output from your Python code, you must print print "Content-type: text/html\n\n" as the first line of output.

    Note the first part - "if you want to view printed output." That's only a requirement is you expect a web browser to be able to display your output as HTML. You can also return image/gif, audio/mpeg, or any other valid MIME type.

    Dreamhost throws an error when I do this.

    Are you certain of that? Or does your browser display an error because it received a content-type it doesn't know what to do with? Try using cURL to hit your script instead of a browser.

    (Followup)

    I've verified that XML output does indeed work as advertised, by uploading the following simple Python CGI to my DreamHost account, at http://tests.shermpendley.com/person.py

    #!/usr/bin/python
    
    def main():
        print "Content-type: text/xml"
        print
        print '<?xml version="1.0" encoding="UTF-8" ?>'
        print '<person born="1912/06/23" died="1954/06/07">'
        print '    <name>Alan Turing</name>'
        print '</person>'
    
    if __name__ == "__main__":
        main()
    

    Testing it with cURL, I get:

    Macintosh:~ sherm$ curl -i http://tests.shermpendley.com/person.py
    HTTP/1.1 200 OK
    Date: Mon, 28 Mar 2011 00:14:50 GMT
    Server: Apache
    Vary: Accept-Encoding
    Content-Length: 124
    Content-Type: text/xml
    
    <?xml version="1.0" encoding="UTF-8" ?>
    <person born="1912/06/23" died="1954/06/07">
        <name>Alan Turing</name>
    </person>
    

    To diagnose a "500 Server Error", check your error logs. Connect (with SSH, SFTP, FTP - whatever you usually use to manage your files) to your account and look at "/home/{username}/logs/{sitename}/error.log" For example, when I introduce a deliberate syntax error in the above, then tried to fetch it with cURL, I found the following in error.log:

    [Sun Mar 27 17:18:10 2011] [error] [client 98.236.96.39]   File "person.py", line 3
    [Sun Mar 27 17:18:10 2011] [error] [client 98.236.96.39]     bogus!
    [Sun Mar 27 17:18:10 2011] [error] [client 98.236.96.39]          ^
    [Sun Mar 27 17:18:10 2011] [error] [client 98.236.96.39] SyntaxError: invalid syntax
    [Sun Mar 27 17:18:10 2011] [error] [client 98.236.96.39] Premature end of script headers: person.py