Python:使用Flask构建主题可写站点

时间:2013-02-25 21:48:39

标签: python flask jinja2

我正在使用python-flask写一个网站,我遇到了一些问题。我的目的是每个用户都可以写一个主题。我已经解决了主题引擎部分。我的问题从目录开始。

我们所知道的烧瓶中有两个名为templatesstatic的目录。当用户上传他/她的主题时,我应该将其放入templatesstatic吗?

在上传的主题用户中,有assets(js etc.)html个文件。如果我将它们放入templates目录,我将无法访问css,js etc.个文件。

否则,如果我将它们放入static文件夹,jinja2找不到html文件,有些人说不要将html文件放入静态文件夹。

现在该怎么办?我应该添加另一个名为userthemes etc.的文件夹吗?

现在,我的目录是:

/python
   /static
   /templates
     login.html
     admin_page.html
   app.py

当用户上传他/她的主题时,会出现index.html。如果您能提供帮助,我会很高兴。谢谢。

1 个答案:

答案 0 :(得分:2)

我确实承认这个问题是在一年前提出的,但问题仍然存在。 Flask-Themes到目前为止还不起作用。因此我必须找到一种方法自己做。

实际上这是一个微不足道的过程。

一个干净的结构必须用于以后的维护(即使它是一个作者项目)。

因此,尝试调整Özcan的结构,进行多模板配置,我们可以有这样的结构:

/python
_ _ _ _app.py
_ _ _ _config.py
______/templates
________________/default
_ _ _ _ _ _ _ _ _ _ _ _index.html
________________/custom
_ _ _ _ _ _ _ _ _ _ _ _index.html

我不知道他的app文件中有什么代码/但是我认为在 app.py 中有这样的代码:

from flask import Flask, render_template

import config
app = Flask(__name__, template_folder='/templates/' + config.Config.ACTIVE_THEME)

@app.route('/')
def main():
  return render_template('index.html')

if '__name__' == '__main__':
  app.run()

这样的config.py:

class Config(object):
    ACTIVE_THEME='default'

模板文件夹中的默认主题index.html可能如下所示:

<head>
  # We have the ability to include the css from the current path instead of having a separate static folder
  <style type='text/css'> {% include 'style.css' %} </style>
</head>
<body>
    <h1> This is the "default" theme </h1>
</body>

自定义主题index.html如下:

<head>
  <style type='text/css'> {% include 'style.css' %} </style>
</head>
<body>
    <h1> This is the "custom" theme </h1>
</body>

现在,访问127.0.0.1:5000将显示“这是”默认“主题”,因为实际上已加载默认主题。

要更改此设置,您必须按以下方式编辑配置文件:

class Config(object):
    # Set ACTIVE_THEME from default to custom
    ACTIVE_THEME='custom'

保存更改,重新加载页面,您应该看到“这是”自定义“主题”。

这是一个非常基本的“黑客攻击”,但如果你对你的应用程序认真考虑,我建议你使用蓝图,除此之外,不得不使用2个配置文件而不是一个配置文件。

为了避免这些问题,我正在使用蓝图和应用程序的良好结构。

例如,我在初始化应用程序后定义配置,因此不是这样:

import config
app = Flask(__name__, template_folder=/templates/' + config.Config.ACTIVE_THEME)

就像这样:

app = Flask(__name__)
app.config.from_object('config.Config')

在包含所有视图的单独文件中,顶部显示以下行:

# doing an "import app" would raise an error because of it being a circular import
import config
active_theme = config.Config.ACTIVE_THEME

# Watch out for the second argument as it seems to add a prefix to successive defined arguments. In fact you could swap the "themes" part to it and remove it from the third argument, but I prefer to leave it like this to avoid future headaches.
posts = Blueprint('posts', '', template_folder='templates/' + active_theme + '/post')

它也可以通过其他方式扩展,如用户会话,数据库配置等。

希望这有助于某人。