I am trying to delete two files from my flask application. But it does not work
html
<button href="/remove/wellness" id="remove" class="btn btn-success mr-2">Remove</button>
Here is my delete function:
#app.route('/remove/<file_id>')
def remove(file_id):
filename_jsonl = f"{file_id}.jsonl"
filename_csv = f"{file_id}.csv"
return os.remove(filename_jsonl, filename_csv)
Any and all help is appreciated. Thanks!
I solved the issue with the following directory structure:
.
├── app.py
├── templates
│ └── delete_files.html
├── wellness.csv
└── wellness.jsonl
As you can see I have two files called wellness.csv and wellness.jsonl in the directory where I have placed my app.py file. The name wellness will be passed from the template and these two files will be deleted from the directory.
app.py:
import os
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def search():
return render_template('delete_files.html')
#app.route('/remove/<file_id>')
def remove(file_id):
filename_jsonl = f"{file_id}.jsonl"
filename_csv = f"{file_id}.csv"
try:
os.remove(filename_jsonl)
os.remove(filename_csv)
return "Files are deleted successfully"
except Exception as e:
return f"Error in deleting files: {e}"
delete_files.html:
<html>
<head>
<title>Delete files using button click in Flask</title>
</head>
<body>
Remove
</body>
</html>
Output:
After clicking the delete button I see the message Files are deleted successfully.
The folder structure after deletion of the files:
.
├── app.py
└── templates
└── delete_files.html
Update
If you want to redirect to root url after successful deletion you can use redirect method like below:
import os
from flask import Flask, render_template, redirect, url_for
app = Flask(__name__)
#app.route('/')
def search():
return render_template('delete_files.html')
#app.route('/remove/<file_id>')
def remove(file_id):
filename_jsonl = f"{file_id}.jsonl"
filename_csv = f"{file_id}.csv"
try:
os.remove(filename_jsonl)
os.remove(filename_csv)
return redirect(url_for('search'))
except Exception as e:
return f"Error in deleting files: {e}"
Related
This question already has answers here:
Flask raises TemplateNotFound error even though template file exists
(13 answers)
Closed 18 days ago.
python file pass value to html with flask
error
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.`
import mysql.connector
# from mysql import connector
import webbrowser
import time
import pymysql
from flask import Flask,render_template
app = Flask(__name__)
mydb = mysql.connector.connect(
host="196.168.101.141",
user="root",
password="password123",
database="cool_db",
auth_plugin='mysql_native_password'
)
mycursor = mydb.cursor()
mycursor.execute("SELECT P_TITLE,P_DESC FROM webpage WHERE P_ID = 'en_1-01'")
myresult = mycursor.fetchall()
print(myresult) # does get the result I want
# but below function not send "myresult" to html successfully
#app.route('/')
def index():
return render_template("index.html", myresult = myresult)
if __name__ == "__main__":
app.run()
index.html
<!DOCTYPE html>
<html>
<body>
<p> this is {{myresult}}</p>
</body>
</html>
I already read through the discussion how to pass data to html page using flask? and also other tutorial but not see how to solve, therefore I need a hand thanks
error:jinja2.exceptions.TemplateNotFound: index.html
You are getting this error because there is no index.html file present in the templates folder. In flask, you need to create a folder named templates in the same location where your app.py file is located. Inside that templates folder, you need to create the index.html file.
So, your directory structure should look like:
|- firstflaskapp.py
|- templates/
| |- index.html
I am sure this will resolve your error.
The full directory structure followed used in flask is:
|- app.py
|- templates/
| |- index.html
| |- login.html
| |- ...
|- static/
| |- css/
| | |- main.css
| |- images/
| | |- logo.png
| |- ...
|- requirements.txt
app.py is the main Flask application file
templates/ directory contains HTML templates for the application
static/ directory contains static files like CSS, JS, images, etc.
requirements.txt is a text file containing the list of python libraries by the application.
import mysql.connector
import webbrowser
import time
import pymysql
from flask import Flask,render_template, request
app = Flask(__name__)
mydb = mysql.connector.connect(
host="196.168.101.141",
user="root",
password="password123",
database="cool_db",
auth_plugin='mysql_native_password'
)
mycursor = mydb.cursor()
# send result to index.html
#app.route('/')
def index():
mycursor.execute("SELECT P_TITLE,P_PRICE FROM webpage WHERE P_ID = '%s'",(request.args.get("ProductID"),))
myresult = mycursor.fetchall()
return render_template("Myshop.html", myresult = myresult)
if __name__ == "__main__":
app.run(debug=True)
you dont enter the Myshop.html in the url if your using flask. You go to the / route and it will render the Myshop.html.
If you want to pass data from the get request like in your example
http://192.168.0.206:8080/?ProductID=001
You can access that data via the request
#app.route('/')
def index():
# if key doesn't exist, returns None
myresult = request.args.get('ProductID')
return render_template("Myshop.html", myresult = myresult)
This tutorial explains it in more detail: https://www.digitalocean.com/community/tutorials/processing-incoming-request-data-in-flask
I am trying to develop an flask web application in which banners should be displayed on web pages,but when I run the app initially banners are displayed on title page,when I click on any hyperlink it should redirect to next page,but on that page banners are not displaying why?
my html codes are in templates folder and images are in static folder
i had used this in title.html
<img src="../static/inner_banner5.jpg" width="1400" height="222">
and i had also used the same in admin_login.html
my app.py code is
__author__ = 'mullapudi'
from flask import Flask,request,redirect,Blueprint,render_template,flash
blueprint = Blueprint('app', __name__, url_prefix='/title')
#blueprint.route('/', methods=['GET', 'POST'])
def title():
# Located at https://yourdomain.com/login
return render_template('title.html')
#blueprint.route('/home/', methods=['GET', 'POST'])
def home():
return redirect('/title/')
#blueprint.route('/admin/', methods=['GET', 'POST'])
def admin():
return render_template('admin_login.html')
the problem here is the banner is displaying in title page where it has a hyper link to redirect to the admin_login page but in admin_login page it was not displaying the banner why
Don't use relative URLs, use url_for:
<img src="{{ url_for('static', filename='inner_banner5.jpg') }}" width="1400" height="222">
Your directory structure would then be
.
├── app.py
├── env
├── static
│ └── inner_banner5.jpg
└── templates
I want to show an image in the homepage of a python web application. So far I wrote the following program:
My directories and files
myWebApp/
app/
__init__.py
views.py
templates/
home.html
static/
Desert.jpg
run.py
__init__.py
from flask import Flask
app = Flask(__name__)
from app import views
views.py
from app import app
from flask import render_template
from flask import url_for
#app.route('/')
def root():
imag = url_for ('static', filename = 'Desert.jpg')
tle = "Hey"
return render_template('home.html', imag,tle)
home.html
<html>
<title>{{ tle }}</title>
<body>
<img src="{{ imag }}"/>
</body>
</html>
run.py
from app import app
if __name__ == "__main__":
app.run()
And when I run the run.py, I receive the following Internal Server Error:
What's wrong?
That's not the correct syntax for the render_template function. You need to use keyword arguments:
return render_template('home.html', imag=imag, tle=tle)
I can upload a File with flask by following Uploading Files:
A <form> tag is marked with enctype=multipart/form-data and an <input type=file> is placed in that form.
The application accesses the file from the files dictionary on the request object.
Use the save() method of the file to save the file permanently somewhere on the filesystem.
But I don't know how to upload folder or some files. I searched, and I found Uploading multiple files with Flask.
However, still I don't know how to upload a folder and files that belong to the folder.
Could you please tell how?
Directory tree I am working on:
.
├── manage.py
├── templates
│ ├── file_upload.html
│ └── hello.html
└── uploads
├── BX6dKK7CUAAakzh.jpg
└── sample.txt
Source code of uploading file:
from flask import Flask,abort,render_template,request,redirect,url_for
from werkzeug import secure_filename
import os
app = Flask(__name__)
UPLOAD_FOLDER = './uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
#app.route('/')
def index():
return redirect(url_for('hello'))
#app.route('/hello/')
#app.route('/hello/<name>')
def hello(name = None):
return render_template('hello.html',name=name)
#app.route('/upload/',methods = ['GET','POST'])
def upload_file():
if request.method =='POST':
file = request.files['file']
if file:
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
return hello()
return render_template('file_upload.html')
if __name__ == '__main__':
app.run(debug = True)
template for file uploading(manage.py):
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form action='' method="POST" enctype="multipart/form-data">
<p><input type='file' name='file[]' multiple=''>
<input type='submit' value='upload'>
</p>
</form>
file = request.files['file']
change it to
file = request.files['file[]']
the issue here is that flask's app.config isn't relative to itself, it's absolute. so when you put:
UPLOAD_FOLDER = './uploads'
flask doesn't find this directory and returns a 500 error.
if you changed it to:
UPLOAD_FOLDER = '/tmp'
and then uploaded your file and navigated to the /tmp/ directory you would see it.
you will need to edit your path to the proper directory for the file to be uploaded properly.
I'm trying to use cherrypy for application dispatching with Flask. The docs give an example with a development server, but when using the cherrypy example snippet and modifying the url prefix, the page is unable to find the static folder.
My directory structure is as follows:
cherry
├── app1
│ ├── __init__.py
│ └── app1.py
├── app2
│ ├── __init__.py
│ ├── app2.py
│ ├── static
│ │ └── js.js
│ └── templates
│ └── index.html
└── cherry_app.py
Some relevant files:
## cherry_app.py
from cherrypy import wsgiserver
from app1.app1 import app as app1
from app2.app2 import app as app2
d = wsgiserver.WSGIPathInfoDispatcher({'/first': app1,
'/second': app2,
})
server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 9999), d)
if __name__ == '__main__':
try:
print 'Start at 0.0.0.0:9999'
server.start()
except KeyboardInterrupt:
server.stop()
## app2.py
from flask import Flask, send_file
import flask
app = Flask(__name__)
#app.route("/")
def root():
return ("Hello World!\nThis is the second app. Url is %s"
% flask.url_for('root'))
#app.route("/index")
def index():
return send_file('templates/index.html')
if __name__ == "__main__":
app.run()
## index.html
<script src="/static/js.js"></script>
JS loaded?
## js.js
alert('Loaded!');
Going to http://0.0.0.0:9999/second/ correctly tells me that the Url is /second/, and the javascript is loaded when I go to http://0.0.0.0:9999/second/static/js.js. But the html gives the error GET http://0.0.0.0:9999/static/js.js 404 (Not Found). It appears it doesn't know to use the prefix /second when looking for /static even when I change the line:
app = Flask(__name__, static_url_path='/second/static')
How can I get the webpage to correctly load the static files? Preferrably without html templating (like jinja).
Did you try to use url_for to locate static files? Here is the static files section in Flask quickstart.
So in your situation, modify src value of script element in index.html:
<script src="{{ url_for("static", "js.js") }}"></script>
The second argument js.js should be the relative path of static file (say js.js) to the static folder. So if the directory structure of static looks like:
static/scripts/js.js
just replace js.js with scripts/js.js:
<script src="{{ url_for("static", "scripts/js.js") }}"></script>
Hope this will make sense.