本文介绍了GAE Python:静态文件不在localhost中加载,但当应用程序部署到appspot时加载完全正常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个奇怪的问题,寻找解决方案,但到目前为止,它似乎是独一无二的。



我的问题是,当我在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 
版本:1
运行时:python27
api_version:1
线程安全:true

处理程序:
- url:/样式表
static_dir:样式表

- url:/.*
script:guestbook.application

库:
- name:webapp2
版本:最新
- 名称:jinja2
版本:最新

guestbook.py

  import os 
从google.appengine.api导入urllib

导入用户
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 =\
< div>< textarea name =contentrows =3cols =60>< / textarea>< / div>
< div>< input type =submitvalue =Sign Guestbook>< / div>
< / form>
< hr>
< form>留言簿名称:
< input value =%sname =guestbook_name>
< input type =submitvalue =switch>
< / form>
< a href =%s>%s< / a>
< / body>
< / html>


DEFAULT_GUESTBOOK_NAME ='default_guestbook'

#我们在'Greetings'上设置了一个父键,以确保它们全部在同一个
$实体组,单个实体组的查询将是一致的
#然而,写入速率应该限制在〜1 /秒

def guestbook_key(guestbook_name = DEFAULT_GUESTBOOK_NAME) :
使用guestbook_name构造一个留言实体的数据存储键。
返回ndb.Key('留言',留言名称)

类问候语(ndb。 )
author = ndb.UserProperty()
content = ndb.StringProperty(indexed = False)
date = ndb.DateTimeProperty(auto_now_add = True)
$ b $ class MainPage(webapp2.RequestHandler):

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

如果users.get_current_user( ):
url = users.create_logout_url(self.request.uri)
url_linktext ='注销'
其他:
url = users.create_login_url(self.request.uri)
url_linktext ='登录'

template_values = {
'问候':问候,
'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):
#我们在'Greeting'上设置了相同的父键,以确保每个G Reeting
#位于同一个实体组中。单个实体组
#中的查询将保持一致。但是,对单个实体组
#的写入速率应限制为〜1 /秒。
guestbook_name = self.request.get('guestbook_name',
DEFAULT_GUESTBOOK_NAME)
greeting = Greeting(parent = guestbook_key(guestbook_name))

如果users.get_current_user( ):
greeting.author = users.get_current_user()
$ b $ 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 =stylesheethref =/ stylesheets / main.css/>
< / head>
< body>
{%for greeting in greetings%}
{%if greeting.author%}
< b> {{greeting.author.nickname()}}< / b>写道:
{%else%}
匿名人士写道:
{%endif%}
< blockquote> {{greeting.content}}< / blockquote>
{%endfor%}

< div>< textarea name =contentrows =3cols =60>< / textarea>< / div>
< div>< input type =submitvalue =Sign Guestbook>< / div>
< / form>

< hr>

< form>留言簿名称:
< input value ={{guestbook_name}}name =guestbook_name>
< input type =submitvalue =switch>
< / form>

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

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

index.yaml



索引:

 #AUTOGENERATED 

#这个index.yaml自动更新每当dev_appserver
#检测到新类型的查询运行时。如果您想手动管理
#index.yaml文件,请删除上面的标记行(行
#说#AUTOGENERATED)。如果您想手动管理某些索引
#,请将它们移动到标记行上方。当您下次使用appcfg.py部署
#您的应用程序时,index.yaml文件是
#自动上传到管理控制台。

- kind:问候
祖先:是
属性:
- 名称:日期
方向:desc

在子文件夹样式表中,main.css

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

谢谢!

   -  url:/ stylesheets 
static_dir:
$ / code>

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

希望它适合您喜欢它为我工作


I'm experiencing a weird problem, searched for a solution but so far, it appears unique.

My problem is, my static files (css, templates, javascript, etc) do not load when I run the app using localhost in GAE. However, when I deploy the app onto GAE servers (appspot), these static files run perfectly fine!

This even occurs for the default Guestbook app found in the GAE documentation.

I'm using GAE launcher (Python) 1.9.6 on Windows. Python is the 64 bit version, 2.7.7. Already made sure GAE is pointing to the right location for python.

I'm experiencing this problem with every app so far, so I doubt it is a problem with the code. However, here's the code for your reference:

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

indexes:

# 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

Inside the subfolder "stylesheets", main.css

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

Thank you!

解决方案

Please replace:

- url: /stylesheets
  static_dir: stylesheets

with:

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

Hope it works for you like it work for me

这篇关于GAE Python:静态文件不在localhost中加载,但当应用程序部署到appspot时加载完全正常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 11:36