Question

Long time listener, first time caller.

I'm having some frustrating, seemingly inexplicable issues with Google App Engine, Jinja2, and CSS.

My templates are working, the functionality of my app works (users, blog posts, etc.), but the CSS file shows a big, fat 404 in my Chrome debugging tools and in my Google App Engine logs. Why isn't my /stylesheets/main.css loading?

Dear internet, I'd love to hear that this is just a typo. I'm sure that I'm just an idiot.

Here's my file directory:

stylesheets  
  main.css
templates
  base.html
  blog.html
  front.html
  login.html
  newpost.html
  signup.html
  welcome.html
app.yaml
blogs.py
favicon.ico
index.yaml
main.py
users.py
utilities.py

Here's my YAML file:

application: hello-udacity-5681
version: 1
runtime: python27
api_version: 1
threadsafe: yes

handlers:
- url: /favicon\.ico
  static_files: favicon.ico
  upload: favicon\.ico

- url: /.*
  script: main.app

- url: /stylesheets
  static_dir: stylesheets

libraries:
- name: webapp2
  version: "2.5.2"

- name: jinja2
  version: latest

Here's my main.py:

import webapp2
import os
import jinja2

from google.appengine.ext import db    

template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = True)

class Handler(webapp2.RequestHandler):
    def write(self, *a, **kw):
        self.response.out.write(*a, **kw)

    def render_str(self, template, **params):
        t = jinja_env.get_template(template)
        return t.render(params)

    def render(self, template, **kw):
        self.write(self.render_str(template, **kw))

class MainHandler(Handler):
    def render_front(self):
        self.render("base.html")

    def get(self):
        self.render_front()

Here's my base.html:

<!DOCTYPE html>

<html>
<head>
  <link type="text/css" rel="stylesheet" href="/stylesheets/main.css"/>

  <title>Blog</title>

</head>

<body>
  <a href="/" class="main-title">Blog</a>

</body>
</html>

I ran my main.css through http://jigsaw.w3.org/css-validator/ without any issues, so I won't bore you with that.

Why am I still getting a 404 for my /stylesheets/main.css ?

Was it helpful?

Solution

Your app.yaml handler section should be like this

handlers:
- url: /favicon\.ico
  static_files: favicon.ico
  upload: favicon\.ico

- url: /stylesheets
  static_dir: stylesheets

- url: /.*
  script: main.app

In this case, the /stylesheets pattern will match before the /.* pattern will for the appropriate paths. For more information on URL mapping and other options you can specify in app.yaml, see the app.yaml reference.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top