Rails - 4 Custom Asset Path added in application.rb without restart - css

Rails-4
For font face mentioned below,
#font-face {
font-family: "Verdana";src: url(/assets/Verdana.ttf) format("truetype");
}
Location of file is app/assets/fonts (loaded by rails itself)
Now if I have this file in app/assets/fonts/client_4 folder,
I had to add following in application.rb
config.assets.paths << Rails.root.join('app', 'assets', 'fonts', 'client_4')
or
Dir.glob("#{Rails.root}/app/assets/fonts/**/").each do |path|
config.assets.paths << path
end
It worked with font-face url provided as url(/assets/Verdana.ttf), but need to restart server to load application.rb
Query
Case is my font file is uploaded by user and stored in newly created client_x folder present in app/assets/fonts directory.
I want to add asset_path in this case for that client_x folder without restarting server. Please suggest.
Update
I added following in controller whenever directory is created,
MyApplication::Application.config.assets.paths << Rails.root.join('app', 'assets', 'fonts', "client_#{#client.id}/").to_s
And I checked following in page by erb tag,
= puts MyApplication::Application.config.assets.paths.inspect
And I got following output,
[
[ 0] "/home/..../app/assets/fonts",
[ 1] "/home/..../app/assets/images",
[ 2] "/home/..../app/assets/javascripts",
[ 3] "/home/..../app/assets/stylesheets",
[ 4] "/home/..../vendor/assets/javascripts",
.
.
[20] "/home/..../app/assets/fonts/client_164/",
[21] "/home/..../app/assets/fonts/client_163/"
]
20th path is added by application.rb & loaded when server started, I do get font file by asset_url in font-face
21st path is added by controller and & I do not get font file by asset_url in font-face.
I am not getting if I inspect I can see both path in assets , still I do not get asset url for font files inside client_163 added by controller. I want it without restarting server. Please suggest if eagerload or autoload can help.

I could not get exact what I wanted but I found alternative to work with.
I did not add asset path for sub-directories inside app/assets/fonts/.
I worked with complete url like "#{APP_URL}/assets/client_#{client_id}/#{self[file]}"
which produce url like 'http://localhost:3000/assets/client_163/GreatVibes-Regular.otf'
Here APP_URL for development is, 'http://localhost:3000' set in development.rb.
Similarly added for staging & production.
Better to keep variable APP_URL in application.yml (implementing figaro gem) & accessing as "#{ENV[APP_URL]}" (note: add application.yml in .gitignore)
Waiting for better approach.
Update
In staging & production I am getting font applied for not secure https url so, please help.

Related

#fontface custom font not loading in Gatsby

my custom font is not working, unless I install it manually in my computer.
//my css file//
#font-face {
font-family:'PROGRESS PERSONAL USE';
src: url('Progress.woff2')format('woff2'),
url('Progress.woff')format('woff'),
url('Progress.ttf') format('ttf');
}
Font family name is correct because, I opened the file font to check the correct spelling and also it shows correctly in the browser if I install the font and use it as:
h1{
font-family: "PROGRESS PERSONAL USE"
}
I thought that the problem was the path of the font files, so I placed them in the same folder and level as the CSS file. I also tried adding a / to the path like url('/Progress.woff2')format('woff2')... in front. Cleared caché, changed browser, and tried in mobile But not working.
Also in my browser inspector/Network shows that the fonts are found when refreshing the browser:
Request URL: http://localhost:8000/Progress.woff2
Request Method: GET
Status Code: 200 OK
Remote Address: 127.0.0.1:8000
Referrer Policy: strict-origin-when-cross-origin
Would be happy to get help with this!
The self-hosted fonts in Gatsby should be located in the static folder.
So I placed the files in the path:
--> static/fonts/Progress.woff2
-->static/fonts/Progress.woff
-->static/fonts/Progress.ttf
and then in my globalStyles.css which is in my src/ (not in the static folder) I place it like this:
#font-face {
font-family:"PROGRESS PERSONAL USE";
src: url('/fonts/Progress.woff2')format('woff2'),
url('/fonts/Progress.woff')format('woff'),
url('/fonts/Progress.ttf') format('ttf');
}
If you don't have a global css file you can define one for the fonts, and import it in your gatsby-browser.js.
Also there is the option of using the web fonts gatsby pluggin which is explained here

static-files 404 not found on hosted django app

im having a hard time to display my static files on my webpages, im hosting my website on digitalocean ubuntu 18 and my static files are stored on the digitalocean space. initially everything was okay and working correctly until i added 3 new images to the server and ran the collectstatic command afterwards, note this was for the second time cause i ran it the first time to store the files in the digitalocean space folder i created. The collectstatic command shown me a warning saying
UserWarning: The default behavior of S3Boto3Storage is insecure and will change in django-storages 2.0. By default files and new buckets are saved with an ACL of 'public-read' (globally publicly readable). Version 2.0 will default to using the bucket's ACL. To opt into the new behavior set AWS_DEFAULT_ACL = None, otherwise to silence this warning explicitly set AWS_DEFAULT_ACL. "The default behavior of S3Boto3Storage is insecure and will change "
after i continue by typing yes, the files are images are successfully stored in the digital-space, but ever since i ran the collect command for the second time all staticfile are not displayed. I did some further reading about this warning and used the solution from AWS S3 and Django returns "An error occurred (AccessDenied) when calling the PutObject operation" but still nothing changed the warning went away but the staticfiles are still not found.
heres the error message from the chrome browser: Failed to load resource: the server responded with a status of 404 (Not Found)
have you ensured your settings display this:
STATIC_ROOT = os.path.join('static')
STATIC_URL = '/static/'
Following this, your templates should show the following:
<link rel="stylesheet" type="text/css" href="{% static '/locationofstatics/css/style.css' %}">
<link rel="stylesheet" type="text/css" href="{% static '/locationofstatics/css/bootstrap.css' %}">
The best way to go about things in my opinion is to only collecstatic locally and then push all of the local files and directories up to the server. What do you currently use to transfer files to the server side?
The other thing you need to do is ensure that Nginx has the location of your static files set within the sites-available file. From your ssh terminal (server side terminal) you can type:
sudo nano /etc/nginx/sites-available/projectname
Within this you need to add the location of your statics, for example:
server {
ocation /static/ {
root /home/name/projectname;
}
}
The following documents are extremely useful:
https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04
https://www.digitalocean.com/community/tutorials/how-to-install-nginx-on-ubuntu-18-04
I was using nginx server in digitalocean for my django project.
front-end static files were working but admin not.
See my static files setting:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
front-end css in static folder and collectstatic target folder is staticfiles
So our main focus is STATIC_ROOT means staticfiles folder. In nginx settings put "staticfiles" instead of "static" to set static file location.
Your STATIC_ROOT folder name could be anything you need to use that same name in nginx.
See below code for nginx setting:
location /staticfiles/ {
root /home/[your_username]/[your_project_folder];
}
[your_username]: which you are using to host your project on digitalocean.
The whole thing is that, you need to use your STATIC_ROOT folder in nginx setting.
Command to create/edit nginx setting is:
sudo nano /etc/nginx/sites-available/[your_project_folder]

Correctly packaging CSS files for deployment to Azure CDN as part of Azure DevOps extension

I'm developing an Azure DevOps extension, which displays the a summary of work items for the current Sprint for printing.
I am failing to get static CSS files to publish correctly.
I have the following configured in the manifest.json in the files section:
{
"path": "css/print.css",
"contentType": "text/css",
"addressable": true
},
{
"path": "css/screen.css",
"contentType": "text/css",
"addressable": true
},
The structure of the project is:
css/screen.css
css/print.css
board-cards.html
vss-extension.json
Reading this documentation: https://learn.microsoft.com/en-us/azure/devops/extend/develop/static-content indicates that the static content should be published to: https://publisher.gallery.vsassets.io.
When debugging - the following two 404's appear in the network log:
https://publisher.gallerycdn.vsassets.io/css/print.css
https://publisher.gallerycdn.vsassets.io/css/screen.css
(I've changed my publisher account name to the generic "publisher" string for ease)
I've opened the .vsix in 7zip, and the folder and css files are in the package. After many hours of Googling and hunting through stackoverflow, I'm unable to find a solution.
I tried changing the entry in "files" to be simply:
{
"path": "css",
"addressable": true
}
However this had no effect.
Is anyone able to advise me on what I'm missing or doing wrong?
Through further debugging I've found that the files do exist under a URL specific the the version published.
e.g. https://publisher.gallerycdn.vsassets.io/extensions/publisher/board-cards/1.0.64/1545996658773/css/screen.css
And then I checked the mark-up, and I realised I'd made an absolute reference to the CSS files. E.g.
/css/screen.css
By removing the first slash - this made the reference to the CSS file relative, which solved the problem.
HTML 101.

Pyexcel, loading a file to create a book in memory

This is solved; thanks to #vmontco's solution: I was missing MEDIA_URL, now it works perfectly.
----------original question below-----------
I welcome suggestions from every angle; I am fairly new to Django and Python. I'm sure I am missing something simple.
Using a Model Form, with a FileField, I upload and save an Excel file to a folder structure under MEDIA_ROOT. This works.
I want to read that same file later to perform operations using Pyexcel. This is where I am stuck. I am attempting to upload the file using the FileField stored in the DB.
This is where I have problems, and I am not sure if am misunderstanding MEDIA_ROOT, or some other aspect of Django.
When I pass the pk to the 2nd view, I then instantiate an object based on the Model. It has the FileField 'docfile', which I am trying to use to access the file to do some operations using Pyexcel,
here is the FileField declaration from models.py:
docfile = models.FileField(
verbose_name="Choose file to upload:",
upload_to='Excel_CSV_Assets/%Y/%m/%d')
EDIT: If I hard-code the pth to the file like this, everything works, including operations afterwards:
thedocfile='site_static/site/original_assets/Excel_CSV_Assets/2016/04/23/Animals_oglc4DV.xlsx'
book=pyexcel.get_book(file_name=thedocfile)
:END OF EDIT
Here is the code from the 2nd view, where I attempt to read the file into memory, and make a 'book' class object using Pyexcel. I am stuck here:
asset = Excel_CSV_Asset.objects.get(id=assetid)
book=pyexcel.get_book(file_name=asset.docfile)
Here is my error description:
Here is the info right at where my code breaks:
Although it says "Wrong filename", I can see the file is in the folder:
I'm able to open the file by double-clicking; the file is not corrupted.
EDIT:
If I cast the 'asset.docfile' to str, like so:
asset = Excel_CSV_Asset.objects.get(id=assetid)
book=pyexcel.get_book(file_name=str(asset.docfile))
I get a different error:
[Errno 2] No such file or directory: 'Excel_CSV_Assets/2016/04/23/Animals_oglc4DV.xlsx'
...but this is the correct directory, located beneath the MEDIA_ROOT file structure.
Here is settings.py MEDIA_ROOT:
MEDIA_ROOT = 'site_static/site/original_assets/'
Here is urls.py:
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^e/', include('excel_to_mongo.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Here is the url.py of that app:
url(r'^efactory/(?P<assetid>\d+)/$', 'display_sheet_column_choices', {}),
I think your problem is that you don't fully understand the media files management with Django.
What are media files?
Media files are all the files that are user-uploaded (at running time).
You must not mistake them with Static files that are assets needed by your project to work and that you add at development time (CSS, background picture and JS files for instance).
You shouldn't mix them because they are managed differently by the server and that it could lead to security problems (cf. the warning here):
Static files management :
You put your static files as a part of the code either in one static subdirectory from the installed django applications, either in one of the locations you added to STATICFILES_DIRS.
Static files have to be gathered before starting the server by calling ./manage.py collectstatic, this command will collect (copy) the static files into the a directory (STATIC_ROOT's value).
You then have to set STATIC_URL to choose with wich url you should serve your static files. An usual choice would be /static/. To access the static file you should then try to reach /static/path/to/static/file/in/static_root/dir.
Media files management :
Your media files are added at running time. They are stored in the MEDIA_ROOT location that has to be an absolute path. Hence the fact I suggested you to join the BASE_DIR value (an absolute path) and the subdir you would choose with something like :
MEDIA_ROOT = os.path.join(BASE_DIR, "/media/subdir")
You then have to set an URL for your media files, by using the MEDIA_URL variable. To access your media files, the urls will start with the value you choose :
MEDIA_URL = '/media/'
Then, add this to your urls.py file :
if settings.DEBUG:
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
With the current example, your mymediafile.txt will be located at /path/to/your/project/media/subdir/path/in/media/root/mymediafile.txt and served at http://127.0.0.1:8000/media/path/in/media/root/mymediafile.txt.
But this is suitable only for a development use as told here. And this would work only for DEBUG == TRUE
For a production use, you should consider deploying your media files with your http server (apache for instance).
Conclusion :
Take the time to understand this. Because I suspect you don't really understood what you did and this lack of understanding could lead to future bugs and errors.

How to configure nginx to serve versioned css and javascript files

My css files named main.css?v=1.0.0 , site.css?=v.1.0 .
how to configure nginx to serve this kind of files(not extension with .css or .js but with a version number)
FYI:
all the files are in the right path and erro message in chrome dev tool console is file not found(404)
Thanks !
When you're trying to access main.css?v=1.0.0 or main.css?v=2.0.0 any webserver will point it to the same file, main.css
.
Well in your situation coud create a separate location for your versioned file, and then use the next code in the nginx config:
location = /main.css {
if ($arg_v) {
rewrite ([0-9]+) /where/maincss/versions/stored/main-$avg_v.css last;
}
// otherwise default main.css
}
The same thing'll be for the any other file

Resources