Joefaa
Joefaa

Reputation: 51

Loading css in python web app using jinja2

I'm trying to make a little bioinformatics web app. I had it working with CGI, I am trying to tweak it so I can serve it on pythonanywhere or heroku.

The problem I am having is that the stylesheet and javascript aren't loading. I'm pretty new to programming, but I have searched extensively before posting. I removed a lot of the heft from the app to isolate the problem. The app's directory now looks like:

/app
 main.html
 main.css
 main.js
 WSGI_app.py

The code in WSGI_app.py looks like:

from wsgiref.simple_server import make_server
import jinja2

def application( environ, start_response ):
    templateLoader = jinja2.FileSystemLoader( searchpath="./" )
    env = jinja2.Environment( loader=templateLoader )
    template = env.get_template( 'main.html' )
    template = template.render()
    start_response("200 OK", [( "Content-Type", "text/html" )])
    yield(template.encode( "utf8" ))

httpd = make_server('localhost', 8051, application)
httpd.serve_forever()

The top of main.html looks like:

<!doctype html>
<html lang="en">
 <head>
    <meta charset="utf-8" />
    <title>Chimera Quest</title>
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <link type="text/css" rel="stylesheet" href="./main.css" />
    <script type="text/javascript" src="./main.js"></script>
</head>

I've tried replacing "./main.css" with "/main.css" and "main.css".

My browser's console reads:

Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://localhost:8051/main.css".

Does anyone have see anything here? I'm totally out of ideas.

Upvotes: 4

Views: 793

Answers (1)

Graham Dumpleton
Graham Dumpleton

Reputation: 58523

If you are not using a WSGI server that also provides support for hosting static files, such as mod_wsgi with Apache, the best thing to do is to use a WSGI middleware to handle serving up static files. The main such WSGI middleware people use is called Whitenoise.

Upvotes: 2

Related Questions