代码之家  ›  专栏  ›  技术社区  ›  Dustin Ingram

如何在appengine中从Google云存储动态加载Jinja2模板?

  •  1
  • Dustin Ingram  · 技术社区  · 6 年前

    我在appengine上有一个应用程序,我想部署Jinja2模板,这样我就可以动态更新它们,而不需要重新部署整个应用程序。

    理想情况下,它们将存储在Google云存储中,这样我就可以替换bucket中的模板文件,并让它们立即被实时应用程序使用。然而,Flask似乎要求模板是应用程序的本地模板。

    这有可能吗?

    2 回复  |  直到 6 年前
        1
  •  2
  •   Dustin Ingram    6 年前

    这可以通过为每个请求直接从Google云存储加载每个模板,并使用 render_template_string

    例如,如果您的模板文件 hello.html

    <h1>Hello {{ name }}!</h1>
    

    将Google云存储资源添加到您的应用程序中,创建一个新的bucket(我们称之为 your-bucket ),并将此文件上载到bucket。

    在你的 requirements.txt

    flask
    google-cloud-storage
    

    在你的 main.py :

    from flask import Flask, render_template_string
    from google.cloud import storage
    
    app = Flask(__name__)
    
    # Initialize the bucket you created containing the templates
    bucket = storage.Client().bucket('your-bucket')
    
    @app.route('/')
    def hello():
        # Load the template string from Cloud Storage
        template_string = bucket.blob('hello.html').download_as_string().decode('ascii')
    
        # Now use render_template_string the same way you'd use render_template
        return render_template_string(template_string, name='World')
    

    Cloud Memorystore ),然后使用 Object Change Notification Google Cloud Function trigger )以确定文件在bucket中的更改时间,并更新缓存。

        2
  •  0
  •   Alexandre Ackermans    6 年前

    下面是Flask render_template()调用的一个很好的包装器

    • 1) 从URL加载静态文件,并传递参数
    • 2) 或者将文件名和参数传递给常规的模板方法。

    -

    from flask import Flask, render_template, render_template_string
    
    
    def renderTemplateLocalOrRemote(file, **kwargs): 
         if REMOTE_LOADING_ENABLED is defined: # Load the template file remotely
             r = requests.get('https://'+YOUR_BASE_URL+"/templates/"+file)
             template_string = r.content.decode('utf-8')
             return render_template_string(template_string, **kwargs)
         else: # Load the template file from local, pass on to standard method
             return render_template(file, **kwargs)
    

    你可以在任何地方使用这个包装器flask.render\u模板()

    @app.route('/')
    def hello():
        return renderTemplateLocalOrRemote('hello.html', name='lalala', another_param='lilili')
    
    @app.route('/another_route')
    def hello2():
        return renderTemplateLocalOrRemote('hello2.html', different_param='lilili')
    

    并使用

    REMOTE_LOADING_ENABLED