2017-04-24 62 views
0

我有一個簡單的Cherrypy腳本,現在只是提供一個頁面。我希望頁面能夠動態顯示圖像。爲此我寫了一個簡單的JS腳本。但是,當我嘗試運行該頁面時,它無法找到圖像。代碼從~/image_player/test_app.py運行,圖像在~/image_player/app/public。請參見Python代碼靜態路徑:Cherrypy和JS,找不到圖像

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) 

而這裏的index.html包含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> 

我得到的錯誤是GET http://hostname/LPROFILE.jpg 404 (Not Found)我清楚的簡單的東西在這裏,但我不肯定是什麼。

回答

2

既然你表明,靜態文件的/static路徑,這意味着app/public(相對於從中啓動服務器的初始目錄)下的所有文件下服務的配置將是訪問從http://hostname/static/,在LPROFILE.jpg的情況下,應該是可用的:http://hostname/static/LPROFILE.jpg

+0

這工作,謝謝! Cherrypy newb在這裏,所以我感謝幫助。 –