Magnet loop to show in slideshow flask - python

I am trying to make a loop to show images in a slideshow in flask, but I want to take the images that put the name of the image, I am trying with glob but this gives the following error:TypeError: 'module' object is not callable
python code
from flask import Flask, render_template
import glob
import os.path
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def home():
ruta_imagenes = glob(os.path.join(app.static_folder, "img"))
render_template('index.html',ruta_imagenes=ruta_imagenes )
if __name__ == ('__main__'):
app.run(debug=True)
HTML
<div class="carousel-inner">
{% for _, ruta in enumerate(rutas_imagenes) %}
<div class="carousel-item ">
{% if _ == 0 %}active{% endif %}
<img src="{{ ruta }}" class="d-block w-100" alt="...">
</div>
{% endfor %}
</div>

You're importing glob and then just calling it. But glob is a module.
What you want is either
import glob
glob.glob(os.path.join(app.static_folder, "img"))
or
from glob import glob
glob(os.path.join(app.static_folder, "img"))

As #blueteeth mentioned you are importing glob module, which is not callable. You probably meant glob.glob() - a function, inside the glob module.
However, even then, glob is probably not what you are looking for. If you want to get a list of images you need to read files in the directory with something like:
ruta_imagenes = []
for root, dir, file in os.walk(path):
ruta_imagenes.append(file)
And, of course, don't forget to pass these images to your template

Related

Flask app to download Excel files from directory

I am building an app to download a bunch of Excel files from a file directory. This question/answer got me started, but the latest version of Flask doesn't appear to work quite the same way. I followed these instructions to build the app so far, but I'm not quite following how to link to files in a directory for download. Do you have any advice or can you point me in a different direction?
Thanks in advance.
#app.py:
from flask
import Flask, render_template
from waitress import serve
from flask import url_for
from config import directory_to_folder
filename = "static/Test1.xlsx"
#app.route("/")
def index():
return render_template('index.html')
def download_file(filename):
return send_from_directory(directory_to_folder, filename, as_attachment=True)
if name == "main":serve(app, host='localhost', port=int("5000"))
#index.html:
{% extends 'base.html' %}
{% block content %}
{% block title %} Welcome Home {% endblock %}
<table>
<tr>
<th>Test File</th>
</tr>
<tr>
<td>{{url_for('static', filename='Test2.xlsx')}}</td>
</tr>
</table>
{% endblock %}
In my flaskapp directory, I have the files:
app.py
\>templates
\>>base.html
\>>index.html
\>static
\>>css
\>>Test1.xlsx
Best,
John

How to display images from folder in Python html and flask

I am very new to python and Flask.
I have a folder with a list of jpeg images. I have to display them in my demo application with flask as below,
My app.py :
#app.route("/")
def home():
return render_template('home.html')
My home.html:
<img id="person" src={{ url_for('static',filename='pferson_folder/000_1.jpg') }}>
In the above code, I don't want to hardcode the images in the HTML tag. it needs to take the image source from folder dynamically.
Would you please help me with this. Thank you.
You can read all the file names out of the directory using os.listdir('Your path') and pass the array into the template:
Something like:
# Inside app.py
import os
#app.route('/')
def home():
image_names = os.listdir('Your path to images folder')
render_template('home.html', image_name=image_names)
And inside your template:
{% for name in image_names %}
<img src="{{ url_for('static', filename='pferson_folder/' + name) }}" >
{% endfor %}
Then you don't have to hardcode the names.

405 method not allowed when trying to upload a file to process on AWS S3 using Flask

I have created a Flask API which gets an Excel file from the user, runs a few operations on the data, and let's the user download the updated file. It is running fine on the local server. However, when I tried to run it on the AWS S3 bucket, it throws an error "405 Method Not Allowed" for "POST" operation.
My index.html looks like this:
<html>
<body>
<div class="container">
<h1>FILE INPUT</h1>
<form method="POST" action="/upload" enctype='multipart/form-data'>
<div class="form-group">
<label for = "inputFile">File input</label>
<input type="file" name="inputFile">
</div>
<br>
<button type="submit" class="btn btn-default"> Download Results </button>
</br>
</form>
</div>
</body>
</html>
And the flask file:
from flask import Flask, request, render_template, send_file
from io import BytesIO
import jsonify
import traceback
import pandas as pd
from pandas import datetime
import xlrd
import xlsxwriter
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/upload', methods=['GET','POST'])
def upload():
if request.method == 'POST':
file = request.files['inputFile']
file.save(file.filename)
return process(file.filename)
def process(filename):
#
### DO DATA(PANDAS) OPERATIONS ###
#
return send_file(output, attachment_filename=name+'.xlsx', as_attachment=True)
if __name__ == '__main__':
app.run(debug=True)
How do I make it run on S3? I tried updating the bucket policy to accept POST requests but that does not seem to help.
You're putting your Python code in the wrong AWS service, what you need is to deploy it on Elastic beanstalk. S3 is meant for storing static files like .html, .css or .js.
In this nice tutorial from the official AWS Docs, you can find what you need. Also, remember to have all the permissions you may need granted to not get a 403 error.

Calling functions from external python file throws 500 error

I am trying to call a function from another python file. I have imported that function. When i call the function externally it works as expected.
But when i try to call the function before returning a render_template or a redirect , i get a 500 error.
I know i am doing something wrong but i am not sure what. Any kind of help will be highly appreciated.
from flask import Flask, render_template, request, redirect, url_for
from content_man import Content,Page_Content
from url_trigger import trigger
TEST_TOPIC = Content()
PAGE_TOPIC = Page_Content()
app = Flask(__name__)
#app.route('/',methods=["GET","POST"])
def homepage():
return render_template("main.html")
#app.route('/dashboard/',methods=["GET","POST"])
def dashboard():
return render_template("dashboard.html", TEST_TOPIC=TEST_TOPIC)
#app.route('/test/', methods=["GET","POST"])
def test():
if request.method == "POST":
selected_list = request.form.getlist("to_run")
print (selected_list)
return redirect(url_for('trigger',selected_list=selected_list))
else:
return render_template("test.html", PAGE_TOPIC=PAGE_TOPIC)
#app.route('/trigger/', methods=["GET","POST"])
def trigger():
data = request.args.getlist('selected_list')
t = trigger(data)
return "hey"
if __name__ == "__main__":
app.run()
The error is in #app.route('/trigger/', methods=["GET","POST"]) where i am trying to call the function trigger.
My url_trigger python file contains the below simple definition:
def trigger(my_list=[], *args):
for i in my_list:
print (i)
The HTML file for the page test is as:
<div class="container">
<form method="post" action = "{{ url_for('test') }}">
{% for row_index in range(PAGE_TOPIC['Critical BP']|count) %}
<div class="checkbox">
<label><input type="checkbox" name="to_run" value="{{ PAGE_TOPIC['Critical BP'][row_index] }}">{{ PAGE_TOPIC['Critical BP'][row_index] }}</label>
</div>
{% endfor %}
<div>
<label><input type="submit" /></label>
</div>
</form>
</div>
You import a function named trigger, but you also a define a function named trigger in the module where you do the import. When trigger calls trigger, it is calling itself, and it accepts no arguments. You need to rename one of the functions, or do the import as import url_trigger and then refer to the imported function as url_trigger.trigger.

Link uploaded files on a list

I'm working on a simple file server, where you can upload files and these files go to a db and a upload folder. Now, it only needs a list of linked files.
Right now I have this:
#app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename)
The uploaded file shows right after uploaded. That is why I need those links.
from os import listdir
from os.path import isfile, join, abspath, dirname
#app.route('/files')
def files():
files = [f for f in listdir(app.config['UPLOAD_FOLDER']) if isfile(join(app.config['UPLOAD_FOLDER'], f))]
return render_template("files.html", files=files)
files.html
{% for file in files %}
{{ file }} <br />
{% endfor %}

Categories