I am trying to build a simple gallery using python and Flask but I got stuck getting the path of the images IF the images are in a subfolder under the main folder static.
The folder structure I got is: 'static' >> 'images'
The following code is working IF the images are un the root of the folder 'static'.
app.py
#app.route("/")
def home():
image_names = os.listdir('./static/')
# print(image_names)
return render_template('index.html', image_names=image_names)
index.html
{% for image_name in image_names %}
<img src=" {{url_for('static', filename=image_name)}}"> {% endfor %}
But I can not figure out how I can add 'images' in the path of the url
{{url_for('static', filename=image_name)}}">
I have tried many different ways, watched tutorials, read the docs but I just got errors...
> I am learning Python and Flask so, please don't be mean in your comments...
use {{ url_for('static', filename='folder_name/file_name') }}
hope that will help you
You can use something like this:
#app.route('/static/images/<filename>')
def get_images_route(filename):
return './static/images/' + filename
in HTML
<img src=" {{url_for('get_images_route', filename=image_name)}}">
Related
I'm working in the Laravel web-app. My images are stored in "public/assets/dist/img"
What I'm using in my view is :
<img src="{{asset('dist/img/user1-128x128.jpg')}}" alt="User Avatar" class="img-size-50 mr-3 img-circle">
but when I try to execute my Laravel app using "php artisan serve" I see my images are broken, when I try to inspect and get image src that is: http://127.0.0.1:8000/dist/img/user1-128x128.jpg
It shows 404 | Not Found page.
I double checked that image with name "user1-128x128.jpg" exists in "public/assets/dist/img"
Why I'm not able to see the image?
Is there something I'm missing?
It would be :
{{ asset('/assets/dist/img/user1-128x128.jpg') }}
assuming that your /assets/dist/img/user1-128x128.jpg is under /public/
I am new in python, and even new in GCP Google Cloud App Engine.
I was testing this script for listing my storage bucket however script responds with no output, even no error, also when I changed bucketname to something not exist name, I got the same results, so its weird.
I am using local OS linux.
~/pit$ python main.py
(env) ~/pit$
Here is the script > copied from google https://cloud.google.com/storage/docs/listing-objects#storage-list-objects-python
main.py>
from google.cloud import storage
def list_blobs(bucket_name):
"""Lists all the blobs in the bucket."""
bucket_name = "pyton_test_bucket"
storage_client = storage.Client()
# Note: Client.list_blobs requires at least package version 1.17.0.
blobs = storage_client.list_blobs(bucket_name)
for blob in blobs:
print(blob.name)
Another question is how to implement this list command to my test flask render index template ?
My goal is to render list object in next line after this
h1>My Fav show is {{ show }}</
In flask example is showing only how to render 1 value, so I don't know how to proceed here with Flask.
main.py
app = Flask(__name__)
#app.route('/')
def hello():
tv_show="Test"
return render_template("index.html", show=tv_show)
if __name__ == '__main__':
# This is used when running locally only. When deploying to Google App
# Engine, a webserver process such as Gunicorn will serve the app. This
# can be configured by adding an `entrypoint` to app.yaml.
app.run(host='127.0.0.1', port=8080, debug=True)
# [END gae_python37_app]
index.html>
<!doctype html>
<html>
<head>
<title>Test</title>
</head>
<body>
<h1>My Fav show is {{ show }}</h1>
</body>
</html>
I reproduced your use case and deployed to Google App Engine Standard
app.yaml
runtime: python37
handlers:
- url: /static
static_dir: template
- url: /.*
secure: always
redirect_http_response_code: 301
script: auto
requirements.txt
Flask==1.1.1
google-cloud-storage
main.py
from flask import Flask
from flask import render_template
from google.cloud import storage
import os
# If `entrypoint` is not defined in app.yaml, App Engine will look for an app
# called `app` in `main.py`.
app = Flask(__name__)
def get_blobs(bucket_name):
"""Lists all the blobs in the bucket."""
storage_client = storage.Client()
# Note: Client.list_blobs requires at least package version 1.17.0.
blobs = storage_client.list_blobs(bucket_name)
b = list()
for blob in blobs:
b.append(blob.name)
return b
#app.route('/blobs/<bucket_name>')
def hello(bucket_name):
"""Return a friendly HTTP greeting."""
print ("Test {}".format(bucket_name))
return render_template('index.html', blobs=get_blobs(bucket_name))
if __name__ == '__main__':
# This is used when running locally only. When deploying to Google App
# Engine, a webserver process such as Gunicorn will serve the app. This
# can be configured by adding an `entrypoint` to app.yaml.
app.run(host='127.0.0.1', port=8080, debug=True)
# [END gae_python37_app]
templates/index.html
<!doctype html>
<html>
<head>
<title>Test</title>
</head>
<body>
<h1>All the blobs </h1>
{% for blob in blobs %}
<p>{{ blob }}</p>
{% endfor %}
</body>
</html>
To deploy to App Engine:
gcloud app deploy
gcloud app browse
#go to https://your_project.nw.r.appspot.com/blobs/your_bucket
To run this application locally you need to :
1.Create a service account with Storage Admin Role
2.Set the default credentials
I need to display related image in ngFor
Like
<div class="row" *ngFor="let name of cheaterNames">
<div class="col-4">
{{ name.name }}
<img src="{{name.path}}" class="rounded mx-auto d-block">
</div>
</div>
This is how the data look like in database
_id OgjectId("566666tyyhhhh")
name Laravel
path uploads\logo.png
This how my project folder looks like
Project
client
about
about.component.html // this the html i used to display images
about.component.ts
dist
e2e
node_modules
server //this is where express/nodejs
controllers
models
routes
app.ts
uploads // this is where the images is stored during file uploads
logo.png
other imgs...
Any ideas for this? The image does not show up and shows 404 error
Your paths will all be relative to the base content directory for your web server which is probably not your project's home directory. Basically, the uploads directory is not within your base content directory, so your image files will not be found by the server at runtime. You need to determine where your base content directory is (express server configuration) and ensure that your uploads directory is under that directory.
For example, if you're serving up a build from the dist directory, uploads should be under dist;
I have project on Symfony 3 with installed assetic. I am using it for merging all css together and minify.
Usage in twig template:
{% stylesheets filter='cssrewrite' filter='uglifycss'
'assets/font-awesome-4.6.3/css/font-awesome.css'
...
%}
<link rel="stylesheet" href="{{ asset_url }}">
{% endstylesheets %}
Config:
filters:
cssrewrite: ~
uglifyjs2:
bin: "%kernel.root_dir%/Resources/node_modules/uglify-js/bin/uglifyjs"
uglifycss:
bin: "%kernel.root_dir%/Resources/node_modules/uglifycss/uglifycss"
In prod mode all works as expected. Assetic loads css files from path /assets/someDir/some.css and generated minified file (css or js) is in default assetic path /css/allCss.css or /js/allJs.css.
But in develop mode assetic generate new files from /assets/someDir/some.css to /css/some.css (each file and not minified) and load css files from there.
QUESTION:
How i can load original files from /assets/someDir/some.css in dev mode?
Because in this situation i must after each change in any css or js run php bin/console assetic:dump --env=dev and it is unacceptable.
Since you don't want to run php bin/console assetic:dump each time you change a CSS or a JS file, use php bin/console assetic:watch instead, it will automatically regenerate the files on every change of CSS or JS.
I am using Assetic with Twig but not the symfony2 framework.
Here's how the project is set up
/site
/template
/css
/public_html
/css
The raw css is stored under /site/template/css and I want assetic to minify the css and output it to /public_html/css.
Here's how assetic is set up as a twig extension
$factory = new AssetFactory(//absolute path to `/site/template/`);
$factory->setDefaultOutput(//absolute path to `/public_html/`);
$factory->setDebug(false);
$twig->addExtension(new AsseticExtension($factory));
Then in my template:
{% stylesheets 'css/screen.css' output='css/*' %}
<link href="{{ asset_url }}" type="text/css" rel="stylesheet" />
{% endstylesheets %}
I can see that assetic has generated a unique url in the final output:
<link href="css/00da241.css" type="text/css" rel="stylesheet" />
However, if I look in /public_html/css, the files are never generated!
I am using a Windows 7 server with apache and PHP has no issues writing files anywhere.
What could be causing this?
What you've done here is asking assetic to generate URL's to assets (using twig).
But assets urls don't point to any file yet. You still have to generate them, using a dump script:
<?php
use Assetic\AssetWriter;
use Assetic\Extension\Twig\TwigFormulaLoader;
use Assetic\Extension\Twig\TwigResource;
use Assetic\Factory\LazyAssetManager;
$am = new LazyAssetManager($factory);
// enable loading assets from twig templates
$am->setLoader('twig', new TwigFormulaLoader($twig));
// loop through all your templates
foreach ($templates as $template) {
$resource = new TwigResource($twigLoader, $template);
$am->addResource($resource, 'twig');
}
$writer = new AssetWriter('/path/to/web');
$writer->writeManagerAssets($am);
This script uses twig templates to define which files to dump.
You will have to define the $templates variable and the $twig variables of course.