【问题标题】:Loading css in python web app using jinja2使用 jinja2 在 python web 应用程序中加载 css
【发布时间】:2017-01-01 10:14:13
【问题描述】:

我正在尝试制作一个小的生物信息学网络应用程序。我让它与 CGI 一起工作,我正在尝试调整它,以便我可以在 pythonanywhere 或 heroku 上提供它。

我遇到的问题是样式表和 javascript 没有加载。我对编程很陌生,但在发布之前我已经进行了广泛的搜索。我从应用程序中删除了很多内容以隔离问题。应用程序的目录现在看起来像:

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

WSGI_app.py 中的代码如下:

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()

main.html 的顶部看起来像:

<!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>

我尝试将“./main.css”替换为“/main.css”和“main.css”。

我的浏览器控制台显示:

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

有人在这里看到什么吗?我完全没有想法。

【问题讨论】:

    标签: python html css jinja2 wsgi


    【解决方案1】:

    如果您没有使用同样支持托管静态文件的 WSGI 服务器,例如带有 Apache 的 mod_wsgi,最好的办法是使用 WSGI 中间件来处理静态文件的服务。人们使用的主要此类 WSGI 中间件称为 Whitenoise。

    【讨论】:

    • 非常感谢格雷厄姆!那成功了。我有很多东西要学,尤其是关于服务器端的东西。我正在朝着 Apache 之类的方向努力,此时我只是想启动一个小开发服务器来解决这个应用程序的问题。此外,在尝试了解 mod_wsgi/Apache 如何以不同方式处理此问题时,我偶然发现了您的名字。很高兴见到你。看来我来对地方了!
    • 顺便说一句,在 pythonanywhere 上,您实际上不需要使用 whitenoise 来提供静态文件。只需在 webapps 仪表板下设置一个静态文件映射,它们就会自动将静态文件卸载到一个单独的线程,该线程从指定的位置提供文件(而不是捆绑你自己的工作人员来提供文件)。
    • 感谢康拉德!很高兴知道。看来我需要在其他地方提供这个特定的应用程序,可能是 Heroku,因为 pythonanywhere 不会让我跑一个 java 程序,但我很感激这个提示。
    猜你喜欢
    • 1970-01-01
    • 2020-03-09
    • 2012-01-15
    • 2012-09-06
    • 2019-04-26
    • 2020-08-12
    • 1970-01-01
    • 2018-02-05
    • 2019-05-16
    相关资源
    最近更新 更多