2013-05-12 115 views
0

我想使用webapp2创建一个简单的应用程序。因为我已经安装了Google App Engine,并且我想在GAE之外使用它,所以我按照此页面上的说明操作:http://webapp-improved.appspot.com/tutorials/quickstart.nogae.html无法使用virtualenv和webapp2访问网络服务器资源

这一切都很顺利,我的main.py正在运行,它正在正确处理请求。但是,我无法直接访问资源。

http://localhost:8080/myimage.jpghttp://localhost:8080/mydata.json

总是返回404资源找不到网页。 如果将资源放在WebServer/Documents /或virtualenv处于活动状态的文件夹中,则无关紧要。

请帮忙! :-)

(我在Mac上10.6与Python 2.7)

+0

[This](http://webapp-improved.appspot.com/tutorials/gettingstarted/staticfiles.html)可能是你要找的。 – 2013-05-12 09:08:42

+0

是的,欢呼声。我也在研究这个问题,但到目前为止它并不工作。我将编辑该问题。 – devboell 2013-05-12 09:16:40

+1

您链接到的文档是用于不使用GAE的webapp2 - 您使用它还是不使用?如果没有,那么app.yaml不适用... – Greg 2013-05-12 11:04:47

回答

2

(从this question改编)

看起来webapp2的没有一个静态文件处理程序;你将不得不推出自己的。这里有一个简单的一个:

import mimetypes 

class StaticFileHandler(webapp2.RequestHandler): 
    def get(self, path): 
     # edit the next line to change the static files directory 
     abs_path = os.path.join(os.path.dirname(__file__), path) 
     try: 
      f = open(abs_path, 'r') 
      self.response.headers.add_header('Content-Type', mimetypes.guess_type(abs_path)[0]) 
      self.response.out.write(f.read()) 
      f.close() 
     except IOError: # file doesn't exist 
      self.response.set_status(404) 

而在你app对象,添加一个路线StaticFileHandler

app = webapp2.WSGIApplication([('/', MainHandler), # or whatever it's called 
           (r'/static/(.+)', StaticFileHandler), # add this 
           # other routes 
           ]) 

现在http://localhost:8080/static/mydata.json(比方说)将加载mydata.json

请记住,此代码是潜在的安全风险:它允许您的网站的任何访问者读取静态目录中的所有内容。因此,您应该将所有静态文件保存到不包含任何您想要限制访问权限的目录(例如源代码)。

+0

感谢您回复此问题。我想我现在明白了。因此,webapp2实际上也是一个web服务器,它捕获端口8080上的所有请求,绕过标准(apache)请求处理,并将其留给程序员以提供处理http请求的实现。因此,即使由触发的基本GET请求在webapp2中也没有默认实现。这取决于程序员提供它。我总结正确吗? – devboell 2013-05-13 07:37:00

+0

就webapp2而言,这是正确的。不知道Apache的默认处理,所以不能评论。 – 2013-05-13 07:38:33