从Google App Engine迁移到Heroku(缺少YAML)
昨晚我在搞一个小项目,想创建一个环境,让使用Python库的GAE代码能轻松转移到Heroku上,尽量少改动。
编辑
问:YAML只需要三行代码就能实现静态文件共享,我在想怎么用最少的修改来实现这个文件共享(关键词是“最少修改”)。
比如说,想分享“static/”文件夹。有一个解决办法是实现一些在http://docs.webob.org/en/latest/file-example.html中找到的类——但这个答案并不优雅。
大致的想法是让开发者有自由选择的权利,选择一个(希望是更好/更便宜的)云服务提供商,按照步骤1、2、3……这样应用就能顺利运行,尽量减少麻烦。希望这样能消除一些困惑。
如果有人想问,我的代码如下……
“main.py”文件:
import jinja2
import webapp2
import os
jinja_environment = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(os.path.dirname(__file__), 'templates')))
class HelloWebapp2(webapp2.RequestHandler):
def get(self):
template_values = { 'test': 'Hello World!!'}
template = jinja_environment.get_template('jinja2_test.html')
return self.response.out.write(template.render(template_values))
app2 = webapp2.WSGIApplication([
('/', HelloWebapp2)
], debug=True)
def main():
from paste import httpserver
port = int(os.environ.get("PORT", 5000))
httpserver.serve(app2, host='0.0.0.0', port=port)
if __name__ == '__main__':
main()
在“requirements.txt”文件中:
Jinja2==2.6
webapp2==2.3
paste==1.7.5.1
webob==1.1.1
输出文件“templates/jinja2_test.html”:
{{test}}
默认的“procfile”:
web: python main.py
2 个回答
在Heroku平台上,如果你的应用访问量很大,建议使用亚马逊的S3来存储静态资源:https://devcenter.heroku.com/articles/s3
为了开发方便,我创建了一个简单的“捕获所有”处理程序(它应该是处理程序列表中的最后一个),可以从项目目录中提供以特定后缀结尾的静态文件。添加这个处理程序非常简单。但要记住,这样做效果不太好,而且会浪费网络资源。
import webapp2
import re
import os
class FileHandler(webapp2.RequestHandler):
def get(self,path):
if re.search('html$',path):
self.response.headers['Content-Type'] = 'text/html'
elif re.search('css$',path):
self.response.headers['Content-Type'] = 'text/css'
elif re.search('js$',path):
self.response.headers['Content-Type'] = 'application/javascript'
elif re.search('gif$',path):
self.response.headers['Content-Type'] = 'image/gif'
elif re.search('png$',path):
self.response.headers['Content-Type'] = 'image/png'
else:
self.abort(403)
try:
f=open("./"+path,'r')
except IOError:
self.abort(404)
self.response.write(f.read())
f.close
app = webapp2.WSGIApplication([
(r'/(.*)', FileHandler),
], debug=True)
def main():
from paste import httpserver
port = int(os.environ.get('PORT', 8080))
httpserver.serve(app, host='0.0.0.0', port=port)
if __name__ == '__main__':
main()
听起来你想解决的问题是如何在Heroku上用Django提供静态页面。
对于这个问题,使用collectstatic是个不错的选择:
web: python my_django_app/manage.py collectstatic --noinput; bin/gunicorn_django --workers=4 --bind=0.0.0.0:$PORT my_django_app/settings.py
http://matthewphiong.com/managing-django-static-files-on-heroku