Generate pages with Flask without using separate template files - python

I'm trying to keep things minimal, so I don't want to create templates, directory structures, etc. I have a simple CSS file available on the web (via RawGit) and I want to use it to style the page generated by a view. How can I render a page without templates?
from flask import Flask
application = Flask(__name__)
# <insert magic here>
# application.get_and_use_my_super_cool_CSS_file(URL)
# <insert magic here>
#application.route("/")
def hello():
return "hello world"
if __name__ == "__main__":
application.run(host = "0.0.0.0")

If you don't want to write templates as separate files, you can use render_template_string instead. This is typically not a very useful feature, as it becomes difficult to maintain large templates written as Python strings. Flask's Jinja env also provides some extra help when rendering files it recognizes, such as turning on autoescape for HTML files, so you need to be more careful when rendering from strings directly.
return render_template_string('''<!doctype html>
<html>
<head>
<link rel="stylesheet" href="css url"/>
</head>
<body>
<p>Hello, World!</p>
</body>
</html>
'''

Related

How to run compiled vue project in django

Previously, I know how to run Vue and Django (jinja2 template) together.
by handling the custom delimiters, e.g delimiters: ['[[', ']]'].
But for some reason, my supervisor just need to run the compiled vue project inside my existing django project. As we can see, the vue has npm run serve or yarn run serve to run it.
Does django can handle this case? If yes, what I should do?
In this case, we doesn't use direct web server like nginx, apache, etc to run.
Charanjit Singh answer is correct and your 404 problem is not related to vueJs. Since you are not using a direct web server you are making it harder.
Also If your vue application implements vue-router in history mode that'll cause even more problems since you're not using neither nginx or apache.
My only approach for this is Haproxy that'll make your sub application handle those routes.
For example your app domain is myawesomedomain.com and your vue app is in myawesomedomain.com/myvueapp then you need to configure your Haproxy to let your vueapp handle all routes in myawesomedomain.com/myvueapp/*.
If you don't have a vue-router in your app then you need to place th vueapp folder in your deployed web folder and don't forget to add a routing rule for your html file (I don't know about Django but I did it with symfony and it is working)
Deployed
|
|_vueapp ===> your compiled folder
|
|_htmlFile ===> your html file
Finally, this is what I've been working on. I put the compiled index.html file from dist/index.html to templates/vueapp/index.html (django templates folder). The other files & folders is put inside static/ folder.
templates/vueapp/index.html => the compiled html file.
static/vueapp/ (includes: css, js, fonts, etc). => the compiled vue static files.
my views.py;
from django.views.generic import TemplateView
class VueAppView(TemplateView):
template_name = 'vueapp/index.html'
and my urls.py;
from django.contrib import admin
from django.urls import (path, include)
from my_app.views import (HomeTemplateView, VueAppView)
urlpatterns = [
path('admin/', admin.site.urls),
path('', HomeTemplateView.as_view()),
path('vueapp/', VueAppView.as_view()),
]
also inside the vueapp/index.html. As we can see, I modified the source of /static/vueapp/ and linked to the static folder.
<!DOCTYPE html>
<html lang=id>
<head>
<meta charset=utf-8>
<meta http-equiv=X-UA-Compatible content="IE=edge">
<meta name=viewport content="width=device-width,initial-scale=1">
<link rel=icon href=/static/vueapp/favicon.ico>
<title>siap-ums</title>
<link rel=stylesheet href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900">
<link rel=stylesheet href="https://fonts.googleapis.com/css?family=Material+Icons">
<link href=/static/vueapp/css/chunk-01c619b4.ff54e24d.css rel=prefetch>
<link href=/static/vueapp/css/chunk-308637dc.e4c5f763.css rel=prefetch>
<link href=/static/vueapp/css/chunk-616b136f.404f3685.css rel=prefetch>
<link href=/static/vueapp/js/app.876efdb8.js rel=preload as=script>
<link href=/static/vueapp/js/chunk-vendors.2b11f5ad.js rel=preload as=script>
<link href=/static/vueapp/css/chunk-vendors.a6a7bf01.css rel=stylesheet>
</head>
<body>
<noscript><strong>We're sorry but siap-ums doesn't work properly without JavaScript enabled. Please enable it to continue.</strong></noscript>
<div id=app></div>
<script src=/static/vueapp/js/chunk-vendors.2b11f5ad.js></script><script src=/static/vueapp/js/app.876efdb8.js></script>
</body>
</html>
Every times the vueapp have changes, I must compile it first and do the same step as above.

jinja2 template not found and internal server error

Python code:
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def hello():
return render_template('testing.html')
if __name__ == "__main__":
app.run()
Html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>My name is pk</h1>
</body>
</html>
Also how to enable jinja2 in pycharm community version. I am directly creating html file and .py file in the same project
flask file structure
|-app
|--templates // where your html files must be in
|--static // where your js and css files must be in
|--.py files
|--other packages
Also jinja is enabled in your system, if you have already downloaded flask package.
By default, Flask looks in the templates folder in the root level of your app.
http://flask.pocoo.org/docs/0.10/api/
template_folder – the folder that contains the templates that should
be used by the application. Defaults to 'templates' folder in the root
path of the application.
So you have some options,
rename template to templates
supply a template_folder param to have your template folder recognised by the flask app:
app = Flask(__name__, template_folder='template')
Flask expects the templates directory to be in the same folder as the module in which it is created;
You'll need to tell Flask to look elsewhere instead:
app = Flask(__name__, template_folder='../pages/templates')
This works as the path is resolved relative to the current module path.
You cannot have per-module template directories, not without using blueprints. A common pattern is to use subdirectories of the templates folder instead to partition your templates. You'd use templates/pages/index.html, loaded with render_template('pages/index.html'), etc.

Bottle web app not serving static css files

My bottle web application is not serving my main.css file despite the fact I am using the static_file method.
app.py
from bottle import *
from xml.dom import minidom
#route('/')
def index():
return template("index")
#route('/glossaryXML')
def glossary():
doc_def = minidom.parse("table_definitions.xml")
terms = doc_def.getElementsByTagName("str_term")
defins = doc_def.getElementsByTagName("str_definition")
return template("list", terms=terms, defins=defins)
#route('<filename>.css')
def stylesheets(filename):
return static_file(filename, root='static')
#error(404)
def fourofour(error):
return "Error"
run(host='localhost', port=8080, debug=True)
The page I am trying to access is the index page, in which index.tpl looks like
<!DOCTYPE HTML>
<html>
<head>
<title>ICT Applications Glossary</title>
<link type="text/css" href="main.css" rel="stylesheet">
</head>
<body>
It works
</body>
</html>
My CSS file is located in a folder named "static" which is in my root folder
Instead specify your static route like this
#route('/<filename:path>')
def send_static(filename):
return static_file(filename, root='static/')
This will serve any file in your static directory though not just css.
To make it stylesheet specific
#get('/<filename:re:.*\.css>')
def stylesheets(filename):
return static_file(filename, root='static/')
Note: for the latter option you could put stylesheets in their own directory 'static/css' or just 'css' and keep them separate from other static resources (scripts, images etc.) to do this just specify the root parameter to be that directory e.g. `root='static/css'.
There are 2 problems that I can see:
The route for the CSS files should begin with a slash, ie.
#route('/<filename>.css')
Only the matching part of the pattern is passed to stylesheets() in
the filename argument, e.g. instead of main.css, it will be
main. Change the code to this:
#route('/<filename>.css')
def stylesheets(filename):
return static_file('{}.css'.format(filename), root='static')
Alternatively... rename your main.css file to main.tpl, bookend with <style> and </style>, move it into the /views directory along with your other templates, then simply add to the beginning of your return line:
return (template ("main"), template ("list", terms=terms, defins=defins))

href attribute value not working in Python Flask app for target HTML pages

I have a basic flask application with the following structure:
app.py
templates/index.html
static/js/common.js
static/css/common.css
In the top navigation bar of my index.html file, I want to have menu buttons contain links to other HTML pages. However, when I tried various ways of specifying the target html files in href attribute of a tags, it doesn't work. On click, the page fails to load.
What is the correct and quick way of mentioning target HTML files/path in my index.html?
<body>
<div class="navbar-header">
<strong>My Website</strong>
</div>
</body>
The template (index.html) needs to be rendered by a route in your Flask application.
To render the index.html template with the URL /index.html:
#app.route('/index.html')
def index():
return render_template('index.html')
Refer to this section in the quickstart guide:
http://flask.pocoo.org/docs/0.10/quickstart/#rendering-templates
It's probably worth reading through the whole guide at the same time. As a side note, it's unconventional to include .html extensions in your URLs in Flask, but it's your call.

serve static files css and js via wheezy.template?

I have this master html template:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Start Bootstrap - SB Admin Version 2.0 Demo</title>
<!-- Core CSS - Include with every page -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="font-awesome/css/font-awesome.css" rel="stylesheet">
<!-- SB Admin CSS - Include with every page -->
<link href="css/sb-admin.css" rel="stylesheet">
<!-- Core Scripts - Include with every page -->
<script src="js/jquery-1.10.2.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/plugins/metisMenu/jquery.metisMenu.js"></script>
<!-- SB Admin Scripts - Include with every page -->
<script src="js/sb-admin.js"></script>
</head>
this is the test.py file:
from wheezy.template.engine import Engine
from wheezy.template.ext.core import CoreExtension
from wheezy.template.loader import FileLoader
T = ['where/project/folderbase/is']
engine = Engine(
loader=FileLoader(T),
extensions=[CoreExtension()]
)
master_template = engine.get_template(r'master.htm')
#route('/test')
def login_name():
return master_template.render({})
I'm a complete n00b at templating and web design.
lets say i run this via any of python web server like flask on localhost:port/test
Nothing shows up.
Why?
And what is this #path_for in wheezy.template?
Do I need to include #require(path_for) or anything else?
is that necessary to server static files in the html file to define all the files in a specific folder-> 'static'
or can they be accessed from where they are now, as in the code above?
You had lots of questions. I'll answer even though you may not care anymore...
If you have correctly configured Flask, and served that template on the route/url 'test', then nothing would appear as you have not defined a <body> with any content in the html.
In wheezy.templates, you access local variables/functions with the #my_variable syntax (ie you prefix it with an # symbol). If you want to access a variable that was passed to the template as part of the context, you need to require it first, #require(my_variable). Your example uses an empty dict as the context, so there would be no variables to access/require.
path_for is part of wheezy.routing, not wheezy.templates. It is used for getting the url of a named route (ie you could do #path_for('test'), and it would return localhost:1234/test. Using path_for would only make sense if you are using the complete wheezy.web framework (which uses wheezy.routing and wheezy.templates). Flask would have its own functions for doing this (I'm not sure what they are though, I don't use Flask). You would need to pass these functions into the template via the context, then #require them to use them though (or make some custom extension for wheezy.template).

Categories

Resources