如何将图像放在localhost服务器上

时间:2015-07-19 20:56:22

标签: python python-2.7 web-scraping server host

我现在正在编写一个程序,它从互联网上抓取图像并使用它们来启动服务器并编写html。

这是我的代码:

import json 
import requests  
import urllib2
import webserver
import bottle
from bottle import run, route, request

#get images
r = requests.get("http://web.sfc.keio.ac.jp/~t14527jz/midterm/imagelist.json")
r.text
imageli = json.loads(r.text)
i = 1
for image in imageli:
    if i <= 5:
        fname = str(i)+".png"
        urllib.urlretrieve(image,fname)
        i += 1

#to start a server
@route('/')
#write a HTML, here is where the problem is,
#the content of html is <image src= "1.png"> but the picture is not on the server. 
#and I don't know how to do it
def index():   
    return "<html><head><title>Final exam</title></head><body> <img src=\"1.png\"/>\n <img src=\"2.png\"/>\n <img src=\"3.png\"/>\n<img src=\"4.png\"/>\n<img src=\"5.png\"/>\n</body></html>"
if __name__ == '__main__':        
    bottle.debug(True) 
    run(host='localhost', port=8080, reloader=True)

我遇到的问题是图片无法在网站上显示,控制台说图片无法找到。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

此处的问题是您尚未定义用于提供静态文件的路由。您可以通过添加此路由来设置根目录以提供静态文件:

# To serve static png files from root.
@bottle.get('/<filename:re:.*\.png>')
def images(filename):
    return bottle.static_file(filename, root='')

但你应该把它们移到一个子目录中,如:

import json
import requests
import urllib
import bottle
from bottle import run, route, request

#get images
r = requests.get("http://web.sfc.keio.ac.jp/~t14527jz/midterm/imagelist.json")
r.text
imageli = json.loads(r.text)
i = 1
for image in imageli:
    if i <= 5:
        fname = "static/{}.png".format(i)  # Note update here
        urllib.urlretrieve(image, fname)
        i += 1

#to start a server
@route('/')
def index():
    return "<html><head><title>Final exam</title></head><body> <img src=\"1.png\"/>\n <img src=\"2.png\"/>\n <img src=\"3.png\"/>\n<img src=\"4.png\"/>\n<img src=\"5.png\"/>\n</body></html>"

# To serve static image files from static directory
@bottle.get('/<filename:re:.*\.(jpg|png|gif|ico)>')
def images(filename):
    return bottle.static_file(filename, root='static')

if __name__ == '__main__':
    bottle.debug(True)
    run(host='localhost', port=8080, reloader=True)