GAE Python:静态文件未在localhost中加载,但在将app部署到appspot时加载完全正常

时间:2014-06-10 16:46:21

标签: python google-app-engine static localhost

我遇到了一个奇怪的问题,寻找解决方案,但到目前为止,它看起来很独特。

我的问题是,当我在GAE中使用localhost运行应用程序时,我的静态文件(css,templates,javascript等)无法加载。但是,当我将应用程序部署到GAE服务器(appspot)时,这些静态文件运行得非常好!

这甚至适用于GAE文档中的默认留言簿应用。

我在Windows上使用GAE启动程序(Python)1.9.6。 Python是64位版本,2.7.7。已经确定GAE指向python的正确位置。

到目前为止,我遇到了每个应用程序的这个问题,所以我怀疑这是代码的问题。但是,这是您的参考代码:

的app.yaml

application: ipeech
version: 1
runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /stylesheets
  static_dir: stylesheets

- url: /.*
  script: guestbook.application

libraries:
- name: webapp2
  version: latest
- name: jinja2
  version: latest

guestbook.py

import os
import urllib

from google.appengine.api import users
from google.appengine.ext import ndb

import jinja2
import webapp2


JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True)


MAIN_PAGE_FOOTER_TEMPLATE = """\
    <form action="/sign?%s" method="post">
      <div><textarea name="content" rows="3" cols="60"></textarea></div>
      <div><input type="submit" value="Sign Guestbook"></div>
    </form>
    <hr>
    <form>Guestbook name:
      <input value="%s" name="guestbook_name">
      <input type="submit" value="switch">
    </form>
    <a href="%s">%s</a>
  </body>
</html>
"""

DEFAULT_GUESTBOOK_NAME = 'default_guestbook'

# We set a parent key on the 'Greetings' to ensure that they are all in the same
# entity group. Queries across the single entity group will be consistent.
# However, the write rate should be limited to ~1/second.

def guestbook_key(guestbook_name=DEFAULT_GUESTBOOK_NAME):
    """Constructs a Datastore key for a Guestbook entity with guestbook_name."""
    return ndb.Key('Guestbook', guestbook_name)

class Greeting(ndb.Model):
    """Models an individual Guestbook entry."""
    author = ndb.UserProperty()
    content = ndb.StringProperty(indexed=False)
    date = ndb.DateTimeProperty(auto_now_add=True)

class MainPage(webapp2.RequestHandler):

    def get(self):
        guestbook_name = self.request.get('guestbook_name',
                                          DEFAULT_GUESTBOOK_NAME)
        greetings_query = Greeting.query(
            ancestor=guestbook_key(guestbook_name)).order(-Greeting.date)
        greetings = greetings_query.fetch(10)

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'

        template_values = {
            'greetings': greetings,
            'guestbook_name': urllib.quote_plus(guestbook_name),
            'url': url,
            'url_linktext': url_linktext,
        }

        template = JINJA_ENVIRONMENT.get_template('index.html')
        self.response.write(template.render(template_values))

class Guestbook(webapp2.RequestHandler):
    def post(self):
        # We set the same parent key on the 'Greeting' to ensure each Greeting
        # is in the same entity group. Queries across the single entity group
        # will be consistent. However, the write rate to a single entity group
        # should be limited to ~1/second.
        guestbook_name = self.request.get('guestbook_name',
                                          DEFAULT_GUESTBOOK_NAME)
        greeting = Greeting(parent=guestbook_key(guestbook_name))

        if users.get_current_user():
            greeting.author = users.get_current_user()

        greeting.content = self.request.get('content')
        greeting.put()

        query_params = {'guestbook_name': guestbook_name}
        self.redirect('/?' + urllib.urlencode(query_params))

application = webapp2.WSGIApplication([
    ('/', MainPage),
    ('/sign', Guestbook),
], debug=True)

的index.html

<!DOCTYPE html>
{% autoescape true %}
<html>
<head>
  <link type="text/css" rel="stylesheet" href="/stylesheets/main.css" />
</head>
  <body>
    {% for greeting in greetings %}
      {% if greeting.author %}
        <b>{{ greeting.author.nickname() }}</b> wrote:
      {% else %}
       An anonymous person wrote:
      {% endif %}
      <blockquote>{{ greeting.content }}</blockquote>
    {% endfor %}

    <form action="/sign?guestbook_name={{ guestbook_name }}" method="post">
      <div><textarea name="content" rows="3" cols="60"></textarea></div>
      <div><input type="submit" value="Sign Guestbook"></div>
    </form>

    <hr>

    <form>Guestbook name:
      <input value="{{ guestbook_name }}" name="guestbook_name">
      <input type="submit" value="switch">
    </form>

    <a href="{{ url|safe }}">{{ url_linktext }}</a>

  </body>
</html>
{% endautoescape %}

index.yaml中

索引:

# AUTOGENERATED

# This index.yaml is automatically updated whenever the dev_appserver
# detects that a new type of query is run.  If you want to manage the
# index.yaml file manually, remove the above marker line (the line
# saying "# AUTOGENERATED").  If you want to manage some indexes
# manually, move them above the marker line.  The index.yaml file is
# automatically uploaded to the admin console when you next deploy
# your application using appcfg.py.

- kind: Greeting
  ancestor: yes
  properties:
  - name: date
    direction: desc

在子文件夹“stylesheets”中,main.css

body {
  font-family: Verdana, Helvetica, sans-serif;
  background-color: #DDDDDD;
}

谢谢!

3 个答案:

答案 0 :(得分:1)

请替换:

- url: /stylesheets
  static_dir: stylesheets

使用:

- url: /(.*\.css)
  static_files: static/\1
  upload: static/.*\.css

希望它对你有用,就像它适合我一样

答案 1 :(得分:0)

我认为这是GAE for Windows中的一个错误,在猜测静态文件的mimetype时,会将标头中的mimetype设置为python unicode字符串,在静态文件处理程序中抛出500错误。 / p>

请参阅以下最近的问题:

Google App Engine: Won't serve static assets with below error:

CSS Files not working on localhost

请在GAE错误跟踪器中报告。

答案 2 :(得分:0)

如果您的static文件夹不在根目录中,而是在另一个文件夹中,例如app(以我为例),您需要将其包括在app.yaml中:

- url: /app/static
  static_dir: static
  secure: always