Cant generate all.css file from sass files with flask-assets - flask

I became tired of using css in my flask app so I decided to move to scss with flask assets https://github.com/miracle2k/flask-assets.
I added this in my app.py file:
from flask_assets import Environment, Bundle
assets = Environment(app)
assets.debug = True
assets.url = app.static_url_path
scss = Bundle('sass/foo.scss', 'sass/bar.scss', filters='pyscss', output='gen/all.css')
assets.register('scss_all', scss)
If I understand correctly, these lines are supposed to go check my static/sass folder and generate a gen folder with a single all.css minified file right ?
I also created a sass folder inside my static assets folder and foo.scss file inside it with some code to test it out.
However when I launch the app, nothing is generated and I get no error. What am I doing wrong here ?

Here is how I got it to work.
Here is a screen shot of my project directory before it generates anything:
Next, I made sure I had the following installed:
pip install flask-assets
pip install pyscss (this is your filter in the filters='pyscss' section)
Here is how I have the code setup:
from flask import Flask, render_template
from flask_assets import Environment, Bundle
app = Flask(__name__)
assets = Environment(app)
assets.url = app.static_url_path
assets.debug = True
scss = Bundle('sass/foo.scss', 'sass/bar.scss', filters='pyscss', output='gen/all.css')
assets.register('scss_all', scss)
#app.route('/')
def hello_world():
return render_template('index.html')
if __name__ == '__main__':
app.run()
And the index.html:
{% assets "scss_all" %}
<link rel="stylesheet" href="/static/gen/all.css">
{% endassets %}
<ul>
<li>
Test Flask Assets
</li>
</ul>
Now, when I ran the application it took a sec for it to generate the css, but it did generate. Once it does, here is the directory structure after running:
And you can see in the chrome debugger that it indeed does load:
It's important to note that the folder has to be gen in the configuration output='gen/all.css' otherwise it won't work.
EDIT
Also per #David's comment, it's important that you have all the required scss files created to generate the output.

Related

Static method returning empty list in Django

I am trying to run a Django app on local server. It works fine on mu Ubuntu machine but in mac, I can't get the CSS for
localhost:8000/admin
and
localhost:8000/docs to load.
On digging further, I found out that the static URL in main "urls.py" file
return an empty list instead of a URL pattern.
Does anyone have an idea why it is like that on the new mac system?
I have had the same issue. I was able to fix it manually by adding the following snippet to my urls.py file in the project (the urls.py file next to settings.py)...
from django.conf import settings
from django.conf.urls.static import static
from django.views.static import serve
. . .
if settings.TESTING_PRODUCTION:
urlpatterns += [
re_path(r'^static/(?P<path>.*)$', serve, {
'document_root': settings.STATIC_ROOT,
}),
]
I pulled this together from the Django Docs here.
I needed to do this so that I could test the "production" environment with manage.py runserver by manually setting DEBUG = False in settings.py which changes a few other URLs and also turns off trace printing in my code.
In my settings.py file, I have some code to set TESTING_PRODUCTION to True as well. But in actual production with a real web server, the code should set TESTING_PRODUCTION to False so that the static files can be served by the webserver directly and not through Django.

Internationalization of static JS in Django

I want to translate a part of the JS in Django.
I've try the command python manage.py makemessages -d djangojs but it take only file in TEMPLATE_DIRS in the settings.py
I've try to set a JS in a template directory, and it work perfectly.
I've the djangojs.po and i can generate the .mo when i compile.
So the question is : How make message in static file?
I've found the same problem
Here
and
Here but no one answer who keep a good architecture.
Please, save me!
My architecture:
myapp
locale
static
myapp
js
try.js
template
myapp
try.html
views.py
urls.py
[...]
PS: Sorry for my english, i'm not native ;)
My error is when i set the STATIC_ROOT in settings.py. In fact this variable say at Django where stock Static when it do a CollectStatic on the server, i used her for say where found my static (Django can find all static whitout informations, it find static on a folder static on the project folder or on the app folder)
Finally :
set this in the urls.py of the pro
js_info_dict = {
'domain': 'djangojs',
'packages': ('app.kanboard',),
}
urlpatterns = patterns('',
[...]
#Internationalization Javascript
url(r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict),
)
In the template
<script type="text/javascript" src="{% url 'django.views.i18n.javascript_catalog' %}"></script>
In the JS in static/my_app/my_file.js
document.write(gettext('Ma chaine de caractère a traduire'))
After, we rule this command-line
python manage.py makemessages -d djangojs
Here, djangojs is the domain set in urls.py at the begin (It's a pseudo-convention)
At this time, we have a djangojs.po in the folder locale what we can compile as a standard .po.
Link of the doc : Here
Lik of my ticket where you can find a sample project and explication in english : The ticket
Good luck !

How to customize TRAC plugin template python file

I am currently modifying our TRAC instance to Bootstrap 3.1. However, some templating needs to be done on the .py files. I only know how to customize .html files... just add classes, customize DOM structure a little bit then put it in templates folder of our TRAC instance.
NOW WHAT ABOUT customizing .py files from plugins? I tried putting them in templates folder but nothing happened.
I had no experience with Python, but it's easy just to hack around and add a bootstrap class e.g adding "col-sm-2 control-label" in a label in milestone.py
def __edit_project(self, data, req):
milestone = data.get('milestone').name
all_projects = self.__SmpModel.get_all_projects_filtered_by_conditions(req)
id_project_milestone = self.__SmpModel.get_id_project_milestone(milestone)
if id_project_milestone != None:
id_project_selected = id_project_milestone[0]
else:
id_project_selected = None
return tag.div(
tag.label(
class_="col-sm-2 control-label",
'Project',
tag.br(),
tag.select(
tag.option(),
[tag.option(row[1], selected=(id_project_selected == row[0] or None), value=row[0]) for row in sorted(all_projects, key=itemgetter(1))],
name="project")
),
class_="field")
Compiling the plugin again worked for me. After adding bootstrap classes on specific .py files, here are the steps/commands I did:
In our TRAC environment plugins directory where specific setup.py of the plugin I'm editing is located, build the .egg file e.g
tracproject/plugins_source/sampleplugin: python setup.py bdist_egg
Then I renamed the plugin's original .egg file in the plugins directory e.g
tracproject/plugins/sampleplugin/: mv sampleplugin.egg sampleplugin.egg.old
After that, I copied the newly .egg file generated to the plugins directory e.g
tracproject/plugins_source/sampleplugin/dist: mv sampleplugin.egg ../../../plugins/
Lastly, I restarted our server e.g (however, there were cases, no restart was needed since changes were instantly reflected)
sudo service apache2 restart
Thanks #falkb! I see that you're the author of SimpleMultiProject plugin I was trying to put bootstrap classes. :)
Here's a snippet of simplemultiprojectplugin milestone.py where I added styling
def __edit_project(self, data, req):
milestone = data.get('milestone').name
all_projects = self.__SmpModel.get_all_projects_filtered_by_conditions(req)
id_project_milestone = self.__SmpModel.get_id_project_milestone(milestone)
if id_project_milestone != None:
id_project_selected = id_project_milestone[0]
else:
id_project_selected = None
return tag.div(
tag.label('Project', class_="control-label col-sm-2"),
tag.div(
tag.select(
tag.option(),
[tag.option(row[1], selected=(id_project_selected == row[0] or None), value=row[0]) for row in sorted(all_projects, key=itemgetter(1))],
name="project",
class_="form-control"),
class_="col-sm-5"),
class_="form-group")

Flask: render_template with path

I have several different templates that I'm trying to use for my flask app.
I have tried the following but it seems to only look directly inside /templates and not /templates/folder1, templates/folder2 etc.
return render_template('index.html', template_folder='folder1')
return render_template('folder1/index.html')
both do not work as expected, how can I specify the sub folder of different templates.
The template folder can be specified when creating the Flask app (or Blueprint):
from flask import Flask
app = Flask(__name__, template_folder='folder1')
Source: http://flask.pocoo.org/docs/0.12/api/#application-object
from flask import Blueprint
auth_blueprint = Blueprint('auth', __name__, template_folder='folder1')
Source: http://flask.pocoo.org/docs/0.12/blueprints/#templates
The template_folder is relative to where the app/blueprint is located.
Use the os library to create paths to template folders outside of the app/blueprint directory.
eg.
import os
APP_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_PATH = os.path.join(APP_PATH, 'templates/')
run from subdirectory of app root
APP_PATH retrieves parent directory path (app root)
Be sure the Python file and Template folder are all under the same working directory folder.
I think Sean is right, but also: have you tried double quotes? I'm using Blueprint, so it may be different, but this is what mine looks like:
return render_template("users/register.html")
so yours may be:
return render_template("folder1/index.html")

How to use django-compressor with apache?

I'm been using Django Compressor to manage my coffee/less files and its great for development, but I've had some issues to make it work for my production deployment.
My idea is to have apache to host the static files, possibly in another server. I'm setting COMPRESS_OFFLINE = True on the settings.py file.
Then I do the following
python manage.py compress - This populates the CACHE directory in my static directory, where all static files will be collected.
python manage.py collectstatic - This collects static files from all the apps on my project (some of which don't use compressor) into my static directory.
Copy the static directory somewhere to be hosted with apache. And setup apache to serve the files.
Modify the static_url variable in the settings.py file to point to the static server.
If I open any page, I get the following error on my server, this only seems to happen when I have DEBUG = False and COMPRESS_OFFLINE = True on my settings.py file:
TemplateSyntaxError: Caught OfflineGenerationError while rendering:
You have offline compression enabled but key
"777ba26736d046ab043dc151e7e9a060" is missing from offline manifest.
You may need to run "python manage.py compress".
When I check the static/CACHE directory, I confirm what the error says, this is my manifest.json file:
{
"6189b8598993d1cbdbd35d4dfd1a6711": "<script type=\"text/javascript\" src=\"http://192.168.1.123/CACHE/js/2f6ca6616bd6.js\"></script>",
"5c66dbed0e5b766c6e32773cd8585f3c": "<link rel=\"stylesheet\" href=\"http://192.168.1.123/CACHE/css/154d95903951.css\" type=\"text/css\" />"
}
If I delete the CACHE directory and rerun python manage.py compress, I get a new set of ID's both on the error message and the manifest file, but the ID on the error is still missing on the manifest.
So, I guess there are two questions here. Why is it not working? What is the proper way to achieve this?
Thanks.
If you've run compress, and you still get the message
OfflineGenerationError: You have offline compression enabled but key "4971a40e3b459a8cda8287a7f7caa96d" is missing from offline manifest. You may need to run "python manage.py compress"
then it's likely you have dynamic content inside compress tags. Make sure that compress is always the innermost block, and that there are no tags inside the compress block.
I guess you're using django-compressor 1.1.2 which doesn't support static template tag {% static "..." %}.
Try installing the dev version of django-compressor with:
pip install django_compressor==dev
It should solve the problem.
David Wolfe is absolutely right: had to dig throught all the code of mine to get rid of {% trans... etc.
I make it like this:
<script>
window.__enter_email = "{% trans "Enter correct email" %}"
window.__url = "{% url "shop:go" %}"
</script>
{% compress js %}
<script>
$("#bla")..... window.__enter_email ...
</script>
{% endcompress %}
Hope, helps someone!