0

I am not a Python programmer, but the I have used SimpleHTTPServer as it is so simple to start a web server serving from one folder.

Now I need to serve a json file. I have the following python:

update: I should mention that the file should be served from a different route. That is that I need both the "localhost" folder serving an index.html and a folder serving the json file.

import BaseHTTPServer, SimpleHTTPServer
import ssl

httpd = BaseHTTPServer.HTTPServer(('localhost', 4443), SimpleHTTPServer.update: I should mention that the )
httpd.socket = ssl.wrap_socket (httpd.socket, certfile='Certificates.pem', server_side=True)
httpd.serve_forever()

I know that I need to add one more handler serving the file, but how can you have multiple handlers.

The requirement for serving the file is:
1. It must be sent with the header ‘application/pkcs7-mime’
2. It must return a 200 http code

The question is how to server multiple handlers. Thanks in advance. Regards

1
  • I recommend using Flask, it's probably easier to use. Commented May 11, 2016 at 12:42

2 Answers 2

1

You don't need multiple handlers. SimpleHTTPRequestHandler uses the the file's extension to guess an appropriate mime type for the Content-type header.

In this case extension .p7m maps to application/pkcs7-mime

So if you name your json files with extension .p7m, the desired mime type will be used.

If that is not feasible, then you can modify SimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map and add your own extension to map to application/pkcs7-mime:

import BaseHTTPServer, SimpleHTTPServer
import ssl

SimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map['.my_ext'] = 'application/pkcs7-mime'
httpd = BaseHTTPServer.HTTPServer(('localhost', 4443), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket (httpd.socket, certfile='Certificates.pem', server_side=True)
httpd.serve_forever()

Now files with extension .my_ext will be served with the required mime type.

If that doesn't work for you, then you can subclass SimpleHTTPServer.SimpleHTTPRequestHandler and override its guess_type() method to add some custom way to determine the mime type, possibly by inspecting the file contents.

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

Comments

0

You can use your operating system’s symlink (symbolic link) feature to link both the index.html and the JSON file into one directory.

On a Unix system, it goes like this:

$ ln -s /path/to/index.html

$ ln -s /another/path/to/file.json

$ ls
file.json  index.html

$ python /your/script.py

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.