Search code examples
javascriptpythoncherrypy

Cherrypy and JS, can't find image


I have a simple Cherrypy script that for now just serves a page. I want the page to be able to display images dynamically. For this I wrote a simple JS script. However when I try to run the page, it can't find the image. The code is run from ~/image_player/test_app.py and the image is at ~/image_player/app/public. See the python code for the static path:

import cherrypy
import os
import sys


class image_player(object):
    @cherrypy.expose
    def index(self):
        return open('app/index.html')


if __name__ == '__main__':
    if len(sys.argv) == 2:
        port = int(sys.argv[1])
    else:
        port = 3030
    host = '0.0.0.0'
    conf = {
        '/': {
            'tools.sessions.on': True,
            'tools.staticdir.root': os.path.abspath(os.getcwd())
        },
        '/query': {
            'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
            'tools.response_headers.on': True,
            'tools.response_headers.headers': [('Content-Type', 'text/plain')],
        },
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'app/public'
        },
        '/js': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'app/js'
        }
    }

    webapp = image_player()
    # Configure server and port
    cherrypy.config.update({'server.socket_host': host,
                            'server.socket_port': port})
    cherrypy.quickstart(webapp, '/', conf)

And here's the index.html containing the js:

<!DOCTYPE html>
<html>
  <head>
    <link href="/static/css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body>
  hello
  <div id="imageDiv"></div>
  <script>
    var par = document.getElementById('imageDiv');
    var img = document.createElement('img');
    img.src = '/LPROFILE.jpg';
    par.appendChild(img);
  </script>
  </body>
</html>

The error I get is GET http://hostname/LPROFILE.jpg 404 (Not Found) I'm clearly missing something simple here but I'm not sure what.


Solution

  • Given the configuration that you showed, the static files are served under the /static path, which means all the files under app/public (relative to the initial directory from which you started the server) are going to be accessible from http://hostname/static/, in the case of LPROFILE.jpg, that should be available in: http://hostname/static/LPROFILE.jpg