Skip to content

Instantly share code, notes, and snippets.

@Driptap
Created March 3, 2018 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Driptap/25ba392b00c8b0e0dfe88c7b8c180ca7 to your computer and use it in GitHub Desktop.
Save Driptap/25ba392b00c8b0e0dfe88c7b8c180ca7 to your computer and use it in GitHub Desktop.
Serving templates from static files
<html>
<head>
<script src="/rendered_statics/script.js"></script>
</head>
<body>
</body>
</html>
(function() {
console.log('{{color}}');
})();
import os
from flask import Flask, render_template_string, render_template, abort
app = Flask(__name__)
ALLOWED_FILES = ['.js']
app.config['STATIC_FOLDER'] = 'static/'
def allowed_file(filename):
filename, file_extension = os.path.splitext(filename)
return file_extension in ALLOWED_FILES
@app.route('/rendered_statics/<path:filename>')
def render_js(filename):
try:
if not allowed_file(filename):
raise FileNotFoundError
with open(os.path.join(app.config['STATIC_FOLDER'], filename)) as script:
return render_template_string(script.read(), color='blue')
except FileNotFoundError:
abort(404)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment