images.html
<body>
{% if msg %} <h1>{{ msg }}!</h1> {% endif %}
<div class="container">
<h1>Here you can upload a file</h1>
<form id="upload_form" action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file" accept="uploaded_files/*" multiple>
<input type="submit" name="upload" value="Upload">
</form>
<hr>
<!--- <h1>Here you can download a file</h1>
<form id="download_form" action="/download" method="POST">
File Name: <input type="text" name="filename" placeholder="Enter file name"><br><br>
<input type="submit" name="download" value="download">
</form>
<hr>
<h1>Here you can delete a file</h1>
<form id="delete_form" action="/delete" method="POST">
File Name: <input type="text" name="filename" placeholder="Enter file name"><br><br>
<input type="submit" name="delete" value="delete">
</form>
<hr>--->
<h1>Here you can List,Download and delete all the files</h1>
{% if list_names %}
{% for item in list_names %}
<!--- {{ item }}--->
<img src="{{item}}" height="400px"/>
delete
{% endfor %}
{% endif %}
<form id="list_form" action="/list_files" method="POST">
<input type="submit" name="list" value="list">
</form>
<hr>
</div>
</body>
website.py
from flask import Flask, session, redirect, url_for, escape, request, render_template
import os
import base64
import mysql.connector
import base64
app = Flask(__name__)
if __name__ == '__main__':
db = mysql.connector.connect(host="mounika.cb3d7dg2fmod.us-east-1.rds.amazonaws.com",
user="mounika", password="mounika2061993", database="innodb")
cur = db.cursor()
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
class ServerError(Exception):pass
#app.route('/login', methods=['GET', 'POST'])
def login():
error = None
try:
if request.method == 'POST':
username_form = request.form['username']
data=cur.execute("select count(1) from users1 where username=%s",[username_form])
print data
if not cur.fetchone()[0]:
raise ServerError('Invalid username')
password_form = request.form['password']
print "SELECT password FROM users1 WHERE username=%s",[username_form]
data1=cur.execute("SELECT password FROM users1 WHERE username=%s",[username_form])
#print data1
for row in cur.fetchall():
if password_form== row[0]:
session['username'] = request.form['username']
return render_template('images.html', error=error)
raise ServerError('Invalid password')
except ServerError as e:
error = str(e)
except ServerError as e:
error = str(e)
return render_template('index.html', error=error)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/upload',methods=['POST'])
def uploaddownload():
username_session = escape(session['username'])
print username_session
get_files=request.files.get('file')
extension=os.path.splitext(get_files.filename)[1]
print extension
file_name = os.path.splitext(get_files.filename)[0]
new_file_name=file_name+extension
#dir_path = os.path.abspath(new_file_name)
#print dir_path
print "hi"
print new_file_name
print get_files
print file_name
app.config['UPLOAD_FOLDER'] = './static/Uploads'
get_files.save(os.path.join(app.config['UPLOAD_FOLDER'], new_file_name))
path=app.config['UPLOAD_FOLDER']+'/'+new_file_name
print "path"
print path
print "file saved succesfully to local upload folder"
extension_list=['.jpg','.jnpg','.jpeg','.png','.GIF','.BMP','.JPG','.JPNG']
if(extension in extension_list):
# print "hiiiiiiiii"
sql ="INSERT INTO images1 (user_name,images) VALUES(%s,%s)"
args=(session['username'],path,)
data= cur.execute(sql,args)
db.commit()
return render_template("images.html")
#app.route('/list_files',methods=['POST'])
def list_Files():
sql1="select images from images1"
cur.execute(sql1)
data= cur.fetchall()
print data
file_name_list=[]
for file in data:
#file_name_list.append(file.generate_url(3600,query_auth=False,force_http=True))
file_name_list.append(file[0].strip('.'))
print file_name_list
#print file.name
return render_template("images.html",list_names=file_name_list)
#app.route('/delete<filename>')
def delete(filename):
print "Hi"
return render_template("index.html")
if __name__ == '__main__':
app.run(debug=True)
The above is my code. In my html I have included anchor tag to delete. item will give the path of the image. so when I click the anchor tage it is searching for the route as '/delete/static/Uploads/14199543_1107156822698054_3500700356588134783_n.jpg'
In my python code I have included the route #app.route('/delete'). I am expecting that the filename is going to capture the path from html. But I guess this isn't working. How can I get item from html which here is the path of the image to the python code so that I could write a delete query including it in the where clause. Or can someone pls explain how to write a delete function that deletes the image when I click the anchor tag.
My code is messy. But the list and login are working fine. Any help regarding delete is appreciated. Thanks in advance
Related
I'm working on a web app right now and I don't know how to display an error message when the user types in an invalid log in name. How do I go about this?
this is my login.html
{% block body %}
<h1>Login</h1>
{% if error %}
<p>Invalid Username</p>
{% endif %}
<form method="POST" action="{{ url_for('login') }}">
<input type="text" name="username" placeholder="Your Username">
<input type="submit" value="Submit">
</form>
<a href='{{variable6}}'>Sign Up</a>
{% endblock %}
this is my app.py
#app.route("/login", methods=["GET", "POST"])
def login():
if flask.request.method == "GET":
return flask.render_template("login.html")
if flask.request.method == "POST":
username = flask.request.form["username"]
cursor.execute(
"SELECT user_name FROM public.users WHERE user_name = %s", [username]
)
results = cursor.fetchall()
if len(results) != 0: # if a user exists, "log" them in
return flask.redirect(flask.url_for("main"))
else:
return flask.render_template("login.html")
I believe that your problem is that you are not defining what the "error" variable is, you could fix this by when you are returning the render_template in the last line of app.py, adding error=True, leaving you with this as your last line for app.py.
return flask.render_template("login.html", error=True)
As otherwise Jinja (the templating language you used in login.html) would not know what error and would get the type None as the value of error in the {% if error %} statement in login.html and since None is not equal to true, it would skip over the code you want to run.
Hope this helps :)
In my flask app I want the user to be able to upload an image to a folder inside the static folder - called wallpaper. Currently I'm receiving a flask.debughelpers.DebugFilesKeyError, however I don't see any error in the keys I'm using
What I've tried
flaskapp.py
#app.route('/changeWallpaper' , methods = ['POST', 'GET'])
def change_home_wallpaper():
UPLOADS_PATH = join(dirname(realpath(__file__)), 'static\\wallpaper')
if request.method == "POST":
wallpaper = request.files['wallpaper']
if wallpaper.filename != '':
image = request.files['wallpaper']
image.save(os.path.join(UPLOADS_PATH, secure_filename(image.filename)))
cur = db2.cursor()
sql = f"UPDATE wallpaper set pic = {wallpaper.filename} where sno = 1"
cur.execute(sql)
db2.commit()
cur.close()
return redirect(url_for('home'))
else:
return redirect(url_for('home'))
loggedin.html
<div class="jumbotron">
<form action="{{url_for('change_home_wallpaper')}}" method="post">
<div class="container">
<input type="file" name="wallpaper"/>
<input type="submit" class="btn btn-primary"/>
</div>
</form>
</div>
Update your HTML
<form action="/path" method="post" enctype="multipart/form-data">
</form>
and put {wallpaper.filename} in quotes.
This question already has answers here:
Create and download a CSV file from a Flask view
(3 answers)
Closed 2 years ago.
My goal is to run my data de-identifying script and download my de-identified data from Flask. Right now, I have created a page to upload my file onto my web and I want to execute my de-identifying script using the execute button on my HTML and download the file.
My HTML:
{% block title %}Upload{% endblock %}
{% block main %}
<div class="container">
<div class="row">
<div class="col">
<h1>Upload the file</h1>
<hr>
<form action="/upload-file" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label>Select file</label>
<div class="custom-file">
<input type="file" class="custom-file-input" name="Dataset" id="Dataset">
<label class="custom-file-label" for="Dataset">Select file...</label>
</div>
</div>
<button type="submit" class="btn btn-primary">De-indentify</button>
</form>
<form action="/upload-file" method="GET" enctype="multipart/form-data">
<button type="submit" class="btn btn-primary">Execute</button>
</form>
</div>
</div>
</div>
{% endblock %}
My App Flask route:
app.config["FILE_UPLOADS"] = "app/app/static/csv/uploads"
app.config["ALLOWED_FILE_EXTENSIONS"] = ["csv"]
def allowed_file(filename):
# We only want files with a . in the filename
if not "." in filename:
return False
# Split the extension from the filename
ext = filename.rsplit(".", 1)[1]
# Check if the extension is in ALLOWED_IMAGE_EXTENSIONS
if ext.upper() in app.config["ALLOWED_FILE_EXTENSIONS"]:
return True
else:
return False
#app.route("/upload-file", methods=["GET", "POST"])
def upload_file():
if request.method == "POST":
if request.files:
Dataset = request.files["Dataset"]
if Dataset.filename == "":
print("File must have a filename ")
return redirect(request.url)
if allowed_file(Dataset.filename):
print("That file extension is not allowed")
return redirect(request.url)
else:
filename = secure_filename(Dataset.filename)
Dataset.save(os.path.join(
app.config["FILE_UPLOADS"], filename))
print("Dataset saved")
return redirect(request.url)
return render_template("public/upload_file.html")
The file that I have uploaded:
Housing,Houseprice,Name,Neighbourhood,State
123556,100000,John,Bloomingdale,Washington
111777,250000,Ian,Bloomingdale,Washington
998273,250000,Tom,Spring Valley,California
My de-identifying script:
import pandas as pd
import uuid as u
# generate a pseudo-identifier sequesnce using python random number generator library uudi.
def uudi_generator(length):
uudi_list= list()
i=0
while i < length:
uudi_list.append(u.uuid4())
i+=1
return uudi_list
#import dataset
dataset = pd.read_csv('C:\\mylocation\\housing.csv', index_col=False)
# pseudo identifier
sLength = len(dataset['Housing'])
dataset.insert(0, 'uuid', pd.Series(uudi_generator(sLength), index=dataset.index))
#delete identifiabLe record from dataset
del dataset['Name']
del dataset['Neigbourhood']
Try this:
from flask import Response
csv_text = ""
for row in dataset.values:
csv_text += f"{row[0]},{row[1]},{row[2]},{row[3]}\n"
return Response(csv_text, mimetype='text/csv')
You don't even need to del the unwanted columns. Just don't add them in csv_text. You don't really even need pandas. You could read the csv as a text file, split('\n') and add the uuids when you compile the csv_text
I am trying to upload a csv file into Mysql with choosing the correspanding columns but the problem is that once I change the route, the file is closed.
So I tried to render 2 templates in the same route: the first to load the file and the second to choose the columns. I can access only the first template.
I am testing the second form with env.is_submitted() but even when I am not submitting it prints "submitted"
#app.route('/upload', methods=['GET', 'POST'])
def upload():
form = UploadForm()
global columnscsv, salessource
if form.validate_on_submit():
try:
filename = secure_filename(form.csv.data.filename)
file = form.csv.data
if file and allowed_file(filename):
print 'file_path'
salessource = CSVSource(file, delimiter=',')
columnscsv = salessource.fieldnames
print columnscsv
finally:
return render(salessource)
return render_template('upload.html', form=form)
def render(salessource):
env = envForm()
if env.is_submitted():
print "submitted"
return render_template('form.html',columnscsv = columnscsv ,env =env)
upload.html
<html>
<head>
<title>Upload</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" >
{{ form.hidden_tag() }}
{{ form.csv }}
<input type="submit">
</form></body>
</html>
form.html
{% block body %}
<form name = "mapping" method="POST" enctype="multipart/form-data" >
{{ env.hidden_tag() }}
<table>
{% for csv in columnscsv %}
<tr> <td> {{ csv }}</td>
<td><select name = "{{ csv }}" >
<option >year </option>
<option >month</option>
<option >day</option>
<option>reference</option>
<option>designation</option>
</select></td>
</tr>
{% endfor %}
</table>
<input type="submit" value="Submit" name = "submit" >
</form>
{% endblock %}
Your form.html can only be rendered when you submit a form (your render(salessource) was inside the check of submit form), so I cant find anyway it does not print "Submitted" in this way.
If you want to render 2 templates, I find a work arround like this:
Add session['fileName'] = filename as a temp to know if a file was submitted
Redirect back to itself after submit
Check if session['fileName'] exist to choose what template to render
#app.route('/upload', methods=['GET', 'POST'])
def upload():
form = UploadForm()
global columnscsv, salessource
if form.validate_on_submit():
try:
filename = secure_filename(form.csv.data.filename)
file = form.csv.data
session['fileName'] = filename
if file and allowed_file(filename):
print 'file_path'
salessource = CSVSource(file, delimiter=',')
columnscsv = salessource.fieldnames
print columnscsv
redirect(url_for('upload'))
except:
raise
if session.get('fileName') != None:
render_template('form.html',columnscsv = columnscsv ,env=env)
else:
return render_template('upload.html', form=form)
I am new to Flask and web applications in general. I have images that could be located in different locations:
-directory1
-image1
-directory2
-subdirectory
-image2
-directory3
-flask_app
-app.py
-static
The purpose of the app is to dynamically provide access to the content in other directories which is not static and subject to change for each user. The content cannot be moved or modified.
How do I display images from other directories within the app without moving or modifying them based on input values from the user?
I have the following so far but the image link is broken:
from flask import Flask, render_template, request, send_from_directory
current_filepath = /directory2/image{}.png
app = Flask(__name__, static_url_path='')
#app.route('/js/<path:filename>')
def download_file(filename):
return send_from_directory('js', filename)
#app.route('/', methods=['GET','POST'])
def print_form():
if request.method == 'POST':
test = current_filepath.format(request.form['image_num'])
return render_template('form.html', result=test)
if request.method == 'GET':
return render_template('form.html')
if __name__ == '__main__':
app.run(debug=True)
With the following form.html file:
<!DOCTYPE html>
<html lang="en">
<body>
<form method="POST" action=".">
<input id="post_form_id" name="image_num" value="" />
<input type="submit">
</form>
{% if result %}
{{ url_for('download_file', filename= result) }}
<img src={{ url_for('download_file', filename= result) }}>
{% endif %}
</body>
</html>
app/
app.py
...
uploads/
dir1/
img1.png
...
...
app.config['UPLOAD_FOLDER'] = 'path/to/uploads/dir1'
#app.route('/file/<path:filename>')
def img_file(filename):
filename = filename + '.png'
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
#app.route('/', methods=['GET', 'POST'])
def index():
filename = None
if request.method == 'POST':
filename = request.form['img_num']
return render_template('form.html', filename=filename)
<form method="post" action="" >
<input type="text" id="form_id" name="img_num">
<input type="submit" value="submit">
</form>
{% if filename %}
<img src=" {{ url_for('img_file', filename=filename) }}">
{% endif %}