Using flask/blueprint for some static pages


So I am just a little confused on how to build pages with flask without having to state each view.

How would I make a blue print that would pickup on the pages i want to load?

say these are my example pages


I would liked to assume if i went to it would know to look for its corresponding page without having to specifically stating it. The documentation gets very close to explaining this, but i am still a little lost.

from flask import Flask
from yourapplication.simple_page import simple_page

app = Flask(__name__)

also, not sure where this was supposed to go? this looks like it would go in the, but asks to import from "yourapplication"

Very new to flask and not a python expert either. Really just need some dumbing down :)

4/9/2012 6:13:05 PM

Accepted Answer

If you'd like to see an example of Blueprint usage, you can have a look at this answer.

About the "template auto-find" part of your question: like the documentation explains, blueprints allows to specify a folder where static files and/or templates will be looked for, this way you don't have to specify the full path to the template file in your render_template() call, but only the file name.

If you wanted your views to "magically" know which file they should pick, you have to do a bit of hack. A solution, for example, could be to apply a decorator on your view that would make it pick the template file based on the function name, such a decorator would look like this:

from functools import wraps
from flask import render_template

def autorender(func):
    def wrapper(*args, **kwargs):
        context = func(*args, **kwargs)
        return render_template('%s.html' % func.func_name, **context)
    return wrapper

Then you would just have to return the context in your view as a dict (or an empty dict if there is no context):

def index():
    return {'name': 'John'} # or whatever your context is

And it would automatically pick the template named index.html.

5/23/2017 12:11:56 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow