I can across a script on github that send a Post request using flask.
I am trying run the script to establish a connection on my local host. But I get the below response
The method is not allowed for the requested URL.
#app.route('/', methods = ['POST'])
def index():
if 'file' not in request.files:
return redirect(request.url)
file = request.files['file']
# if user does not select file, browser also
# submit a empty part without filename
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
warped = transform_file(file)
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
if __name__ == '__main__':
app.run(host='127.0.0.1', threaded=True)
you are trying to have only a root i.e "/" in your route.
Can you try with a site, something like below:
#app.route('/', methods=['GET', 'POST'])
First of all it's because you do not have a GET method for the route: / address but only POST and that's the reason why Flask displays that error.
Definitely you should have a return statment at the end of function with either html code as #CoderRambo wrote in the comment or using render_template function pointing html file inside the templates folder.
Also if your going to use:
#app.route('/', methods=['GET', 'POST'])
you should add an if statment if request.method == 'POST': beforehand that partif 'file' not in request.files: - that would handle the post request and in else block have the return statment that will display the page onto which your going to enter data you'd like to post. As Flask's documention shows https://flask.palletsprojects.com/en/1.1.x/quickstart/:
Hope I helped.
Cheers
Related
I am developing an app using Flask, In the app, user upload files to the server, before uploading I used to check that user is authenticated or not. If the user is authenticated, then the uploading file is saved in the server otherwise flask redirected to home page.
Code -
In app.py -
#login_required
#app.route('/home')
def home():
if current_user.Is_Authenticated:
return redirect(url_for('post1'))
else:
return render_template('post2.html')
#app.route('/upload', methods=['POST'])
def upload():
if current_user.Is_Authenticated:
user = current_user.Email
flag = True
else:
print("Current User is not Authenticated")
flag = False
if(flag):
if(request.method == "POST"):
if(request.files['myfile']):
myfile = request.files["myfile"]
sfname = os.path.join(os.getcwd(), 'static', str(secure_filename(myfile.filename)))
myfile.save(sfname)
return render_template('post.html')
else:
return redirect(url_for('home'))
When, I am testing the app, I found that, before authenticated, a user upload files with larger than 10MB, it shows "Site is not reachable". If it is small sized file, then flask redirected to home page, correctly.
how to solve this, why flask is not working when the uploading file size is larger than 10Mb, Thank you
In Flask you can limit the file size using MAX_CONTENT_LENGTH while configuring your app.
If the file size is greater than MAX_CONTENT_LENGTH you get this kind of errors Please refer to this (for error messages, for different browser and there are also solutions as well)
Increase this MAX_CONTENT_LENGTH to handle large file size
or use the below code to handle large file error
#app.errorhandler(413)
def request_entity_too_large(error):
return 'File Too Large', 413
Happy coding!
I have a simple flask app where I take an image file path from an input page and then switches over to an output page with the image being displayed. My app works properly and manages to access my saved files and displays them on the new page, but I realized I have two routes that point towards the same place. My code is shown below:
#app.route('/')
def main_page():
return render_template('input_receiver.html')
#app.route('/', methods = ['POST', 'GET'])
def get_input():
if request.method == 'POST':
user = request.form['nm']
return redirect(url_for('success', name=user))
These two functions point towards my initial localhost:5000 page, the first function renders an html file with a text field input and a button. In order to connect to the actual flask script, it includes the following line in the form tag:
<form action = "http://localhost:5000" method = "post">
('nm' is the text field input on the initial HTML page)
The second function takes in the user input of the local image file path and redirects them to an HTML file after they press a button which displays the picture they entered. This is done through the below function.
#app.route('/<name>')
def success(name):
return render_template('popup.html', picture_path = "/static/" + name)
Both routes point towards the initial localhost:5000 page, so how does flask handle execution? If this is considered as a bad way to create this sort of functionality, what is the better way of doing it?
You can put both GET and POST in the same method under same route.
#app.route('/', methods = ['POST', 'GET'])
def get_input():
if request.method == 'POST':
user = request.form['nm']
return redirect(url_for('success', name=user))
return render_template('input_receiver.html')
You have already given the methods as GET and POST for the route / - method get_input(), so you can completely remove the other method - main_page.
Both your GET and POST request can be handled by this one method.
I have this problem, where I try to redirect to another URL using FLASK. My HTML form uses POST to get the input to backend:
if request.method == 'POST' and 'redirectButton' in request.form:
createRedirect(request.form['redirectButton'])
And then using my createRedirect func. I would like to redirect them, to URL I have assembled:
def createRedirect(videoName):
redirectLink = "https://www.youtube.com/watch?v={}".format(VIDEOID[videoname])
print(redirectLink)
return redirect(redirectLink, code=302)
If I click on the printed link, new tab opens on my explorer and it works fine, but the redirect does not happen -> the URL is right
Also I have no problem with formatting
How about
if request.method == 'POST' and 'redirectButton' in request.form:
redirect_data = createRedirect(request.form['redirectButton']
return redirect(redirect_data["link"], code=redirect_data["code"])
def createRedirect(videoName):
redirectLink = "https://www.youtube.com/watch?v={}".format(VIDEOID[videoname])
print(redirectLink)
return {"link": redirectLink, "code": 302}
I think you have to return the redirect.
#app.route('/')
def hello():
return redirect(redirectLink, code=302)
I'm using Flask, Flask-Bootstrap and Flask-Uploads with Python 3.7.1 to create a very simple application that accepts a csv file containing raw data.
The 'upload' page must allow only .csv files to be uploaded. I have tried to implement the answer given on this post.
Upload attempts with .csv work as expected, but other file types (eg .jpg) still appear to be accepted. Am I missing something obvious here?
'details.html' simply renders the filename on the page for now.
Python Code:
import os
from flask import Flask, render_template, url_for, request
from flask_bootstrap import Bootstrap
from flask_uploads import UploadSet, configure_uploads
app = Flask(__name__)
Bootstrap(app)
# Upload files configuration
csv_file = UploadSet('files', ('csv'))
app.config['UPLOADED_FILES_DEST'] = 'static/uploadstorage'
configure_uploads(app, csv_file)
# index
#app.route('/')
def index():
return render_template('index.html')
# if csv file, show the data in a table. if not csv file, reload index page
#app.route('/datauploads', methods=['GET', 'POST'])
def datauploads():
if request.method == 'POST' and 'csv_data' in request.files:
file = request.files['csv_data']
filename = file.filename
file.save(os.path.join('static/uploadstorage', filename))
return render_template('details.html', filename=filename)
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
You are ignoring the upload set when you accept files. You need to use the UploadSet.save() method for extension checking to kick in.
You also need to pass in a sequence of extensions, currently you pass in a string, add a comma to make it a tuple:
csv_file = UploadSet('files', ('csv',))
and in your view use:
#app.route('/datauploads', methods=['GET', 'POST'])
def datauploads():
if request.method == 'POST' and 'csv_data' in request.files:
filename = csv_file.save(request.files['csv_data'])
return render_template('details.html', filename=filename)
return render_template('index.html')
You probably want to catch the UploadNotAllowed exception, however, as you'd otherwise get a 500 error:
from flask_uploads import UploadSet, configure_uploads, UploadNotAllowed
from flask import flash
#app.route('/datauploads', methods=['GET', 'POST'])
def datauploads():
if request.method == 'POST' and 'csv_data' in request.files:
try:
filename = csv_file.save(request.files['csv_data'])
return render_template('details.html', filename=filename)
except UploadNotAllowed:
flash('Only CSV files can be uploaded, please correct', 'error')
return render_template('index.html')
I used message flashing (which Flask-Bootstrap can support directly), but your index.html could also be altered to accept an error message.
I'm trying to create a web app with Flask that lets a user upload a file and serve them to another user. Right now, I can upload the file to the upload_folder correctly. But I can't seem to find a way to let the user download it back.
I'm storing the name of the filename into a database.
I have a view serving the database objects. I can delete them too.
#app.route('/dashboard', methods=['GET', 'POST'])
def dashboard():
problemes = Probleme.query.all()
if 'user' not in session:
return redirect(url_for('login'))
if request.method == 'POST':
delete = Probleme.query.filter_by(id=request.form['del_button']).first()
db.session.delete(delete)
db.session.commit()
return redirect(url_for('dashboard'))
return render_template('dashboard.html', problemes=problemes)
In my HTML I have:
<td>Facture</td>
and a download view :
#app.route('/uploads/<path:filename>', methods=['GET', 'POST'])
def download(filename):
return send_from_directory(directory=app.config['UPLOAD_FOLDER'], filename=filename)
But it's returning :
Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
I just want to link the filename to the object and let the user download it (For every object in the same view)
You need to make sure that the value you pass to the directory argument is an absolute path, corrected for the current location of your application.
The best way to do this is to configure UPLOAD_FOLDER as a relative path (no leading slash), then make it absolute by prepending current_app.root_path:
#app.route('/uploads/<path:filename>', methods=['GET', 'POST'])
def download(filename):
uploads = os.path.join(current_app.root_path, app.config['UPLOAD_FOLDER'])
return send_from_directory(directory=uploads, filename=filename)
It is important to reiterate that UPLOAD_FOLDER must be relative for this to work, e.g. not start with a /.
A relative path could work but relies too much on the current working directory being set to the place where your Flask code lives. This may not always be the case.
To download file on flask call. File name is Examples.pdf
When I am hitting 127.0.0.1:5000/download it should get
download.
Example:
from flask import Flask
from flask import send_file
app = Flask(__name__)
#app.route('/download')
def downloadFile ():
#For windows you need to use drive name [ex: F:/Example.pdf]
path = "/Examples.pdf"
return send_file(path, as_attachment=True)
if __name__ == '__main__':
app.run(port=5000,debug=True)
I was also developing a similar application. I was also getting not found error even though the file was there. This solve my problem. I mention my download folder in 'static_folder':
app = Flask(__name__,static_folder='pdf')
My code for the download is as follows:
#app.route('/pdf/<path:filename>', methods=['GET', 'POST'])
def download(filename):
return send_from_directory(directory='pdf', filename=filename)
This is how I am calling my file from html.
<a class="label label-primary" href=/pdf/{{ post.hashVal }}.pdf target="_blank" style="margin-right: 5px;">Download pdf </a>
<a class="label label-primary" href=/pdf/{{ post.hashVal }}.png target="_blank" style="margin-right: 5px;">Download png </a>
#HTML Code
<ul>
{% for file in files %}
<li> {{ file }}</li>
{% endfor %}
</ul>
#Python Code
from flask import send_from_directory
app.config['UPLOAD_FOLDER']='logs'
#app.route('/uploads/<path:filename>', methods=['GET', 'POST'])
def download(filename):
print(app.root_path)
full_path = os.path.join(app.root_path, app.config['UPLOAD_FOLDER'])
print(full_path)
return send_from_directory(full_path, filename)