How to use variables from backend in .scss files - python

I have a site built with Django, Python and Wagtail.
What I want is to be able to add some styles in the backend and then use it in my frontent's .scss files.
For example I want to be able to set a primary color to #fff via backend and then use it in my .scss file as:
$g-color-primary: primary_color_from_backend;
$g-font-size-default: primary_font_size_from_backend;
I do not have any idea how I can do that and if it's possible at all?
Thanks for the help.

Unfortunately, it is not possible. You can instead define different classes in the CSS file, then use them in your HTML template dependent on the Django template variables there.

This would require to write out the sass color variables content (with scss syntax) in a physical .scss file, which depends on your development environment. And then import it into other .scss file to get compiled and output through a frontend build process tool like Gulp, Webpack.
For example, Webpack's sass-loader plugin provides option to prepend sass code at Frontend build/compile time.
https://github.com/webpack-contrib/sass-loader
module.exports = {
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
'style-loader',
'css-loader',
{
loader: 'sass-loader',
options: {
prependData: '$env: ' + process.env.NODE_ENV + ';',
},
},
],
},
],
},
};

Related

Changing cursor type from python

I am making a text based video game with python, and I need a way to change the cursor type from inside python. Here is my code:
from os import system,getenv
from json import loads,dumps
import uuid
apd = getenv("LOCALAPPDATA")
pf = loads(open(rf"{apd}\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json").read())
pf['profiles']['list'].append({"guid":str(uuid.uuid4()),'name':"Game","commandline": "C:\\Windows\\System32\\cmd.exe","cursorShape": "vintage","font": {"face": "Consolas"},})
open(rf"{apd}\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json",'w').write(dumps(pf))
system('wt -F -d {{PATH TO FILE}} -p "Game" --title Game python game.py')
I'm not sure it's a great idea to place a dependency on Windows Terminal, but if you do go that route, the right way to do this is via the JSON fragment extension feature.
Don't risk modifying the user's Windows Terminal settings file directly via Python. Users will be quite (rightly) upset if you muck up their settings if something goes wrong.
JSON fragment extensions give you the ability to create a separate settings fragment that only applies to your application/profile.
For example, create a fragment:
{
"profiles": [
{
"name": "My Game",
"commandline": "python.exe /path/to/game.py",
"cursorShape": "vintage",
"font": {"face": "Consolas"}
}
]
}
Place this file in either:
C:\ProgramData\Microsoft\Windows Terminal\Fragments\{app-name}\{file-name}.json: For all users on the system
C:\Users\<user>\AppData\Local\Microsoft\Windows Terminal\Fragments\{app-name}\{file-name}.json: For only the current user

How to customize docstring color for Python in VSCode's default theme?

Could some one explain to me please how to customize docstring color for Python in VSCode's default theme? I want to do it thru User Settings because want to be able to save my config file.
I tried to use "editor.tokenColorCustomizations": {} but it affects all strings.
Add this to your setting file:
<!-- language: json -->
"editor.tokenColorCustomizations": {
"textMateRules": [
{
"scope":"string.quoted.docstring.multi.python",
"settings": {
"foreground": "#69676c" //change to your preference
}
}
]
}
additional info:
for finding out the scope of other element, you use the command Developer: Inspect TM Scopes , as described here https://github.com/Microsoft/vscode/pull/29393
more detail:
https://code.visualstudio.com/docs/getstarted/themes#_customize-a-color-theme
Adding to Leonard's answer, if you want to change the triple quotes and escapes too, use the below:
"editor.tokenColorCustomizations": {
"textMateRules": [
{
"scope": [
"string.quoted.docstring.multi.python",
"string.quoted.docstring.multi.python punctuation.definition.string.begin.python",
"string.quoted.docstring.multi.python punctuation.definition.string.end.python",
"string.quoted.docstring.multi.python constant.character.escape.python"
],
"settings": {
"foreground": "#aab5da" //change to your preference
}
}
]
},
Also, I had a hard time finding the user settings file in json format. You can find that by:
CTRL + SHIFT + P > User Settings > On the open tab level extreme right hand side > Open Settings (JSON) icon (Hover to know which icon)
Leonard's answer above is perfect.
Just for the googlers in 2020, I would add that the command in Command Palette: Developer: Inspect TM Scopes seems to have changed to: Developer: Inspect Editor Tokens and Scopes.
This option shows both the standard token types, as well as TextMate scopes.

Serving static directories in CherryPy

I am trying to serve static files using CherryPy but I am unable to. I have looked in the tutorials but setting it up like that is also not working properly.
All this is using Python 3.4
Config
config = {
'/ws': {
'tools.websocket.on': True,
'tools.websocket.handler_cls': ChatWebSocketHandler,
'tools.websocket.protocols': ['toto', 'mytest', 'hithere']
},
'/assets': {
'tools.staticdir.on': True,
'tools.staticdir.dir': constants.TEMPLATE_PATH
},
}
I am starting up cherryPy like this
app_root = Root(args.host, args.port, args.ssl, ssl_port=args.ssl_port)
cherrypy.quickstart(app_root, '', config=config)
Constant Path is
TEMPLATE_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)),"assets/")
I have tried using paths like assets/, /assets/ as well instead of the above constant.
The thing is it does not recognize anyone of them and always gives a 404 error.
I too have had difficulty setting this up. I have a rather complicated setup complete with multiple subdomains that has evolve through several early versions of CherryPy which may no longer be valid, and I've not verified this will work in the simpler quickstart configuration you have here. However the key lines in a setup that actually works for me is to put the config lines below in the webservice object that you mount. I put the config dict that defines the static dir in the class definition before any resources. It looks to me like you've defined your static dir in the configuration dict rather of a specific resource rather than the object. So perhaps try in your hosted service object:
class WebService(object):
_cp_config = {
'tools.staticdir.on': True,
'tools.staticdir.dir': '/path/to/serve/static/files/from'
}
#cherrypy.expose
def index(self):
[ ...additional resource definitions, etc ...]
Then later on:
my_cp_app =
cherrypy.tree.mount(subDomain.WebService(),
'/subdomainFileLocation',
subdomainConfigDict)
cherrypy.quickstart(config=domainConfig)
I know you're working on Python 3. This above works for me on Python 2.7 + cherrypy-8.1.2. I hope this is helpful.

React - Django webpack config with dynamic 'output'

Have:
I have a Django app. It has react for front-end. I have 2 django apps. movies_list and series_list. I have all my .jsx files inside baseapplication/movies_list/interfaces/ and baseapplication/series_list/interfaces/. The entry point of 2 apps is given ...../index as given in entry object of web-pack.config.js .
Need:
I need to put my compiled .js files inside baseapplication/movies_list/static/movies_list and baseapplication/series_list/static/series_list. So I need to find each entry in entry and get the abs path and construct my output path dynamically for the future apps. This will help my python manage.py collectstatic to get static files from each directory.
How to configure the output to make it dynamic?
module.exports = {
//The base directory (absolute path) for resolving the entry option
context: __dirname,
entry: {
movies: '../movies_list/interfaces/index',
series: '../series_list/interfaces/index',
},
output: {
// I need help here.
path: path.join('<', "static"),
//path: path.resolve('../[entry]/static/react_bundles/'),
filename: "[name].js",
},
}
https://github.com/webpack/docs/wiki/configuration
You can set entry points to a full path of the resulting file. Something like this should work:
module.exports = {
context: __dirname,
entry: {
'baseapplication/movies_list/static/movies_list/index': '../movies_list/interfaces/index',
'baseapplication/series_list/static/series_list/index': '../series_list/interfaces/index',
},
output: {
path: './',
filename: "[name].js",
},
}

Dynamically compressing static files with django-pipeline

I am getting started with django-pipeline. If I understand it correctly, I need to specify the directories with my CSS/JS files to compress them. However, this is a tedious task as my project is quite big and has static files here and there (not only under /static/ directory).
I saw that it has collectstatic integration but it is not what I thought: it just runs the compressor after collecting the static files, and will only compress the files you manually specified in the settings and not all the static files.
Is there any way I could tell django-pipeline to just compress every static file I have?
You can use glob syntax to select multiples files. Like this way,
You don't want to use collectstatic right ?
then use this way,
from django.contrib.staticfiles import finders
all_js = ["{0}/{1}".format(st,"*.js") for st in finders.find("", all=True)]
all_css = ["{0}/{1}".format(st,"*.css") for st in finders.find("", all=True)]
PIPELINE_CSS = {
'colors': {
'source_filenames': tuple(all_css),
'output_filename': 'css/colors.css',
'extra_context': {
'media': 'screen,projection',
},
},
}
PIPELINE_JS = {
'stats': {
'source_filenames': tuple(all_js),
'output_filename': 'js/stats.js',
}
}

Categories

Resources