I followed this tutorial for uploading files to a webserver via Flask, with the notable exception of the return part.
My intention is to upload pictures.
Here's my code:
from flask import Flask, request, jsonify, json, Blueprint, redirect, url_for, send_from_directory
from werkzeug import secure_filename
app = Flask(__name__)
allowed_extensions = set(['png', 'jpg', 'jpeg', 'gif', 'bmp'])
folder_upload = '/Users/myusername/Documents/Project_Upload/'
#CustomersAPI.route('/customers/addpicture', methods=['POST'])
def add_picture():
file = request.files['value']
print file.filename
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
#return redirect(url_for('uploaded_file', filename=filename))
return str(url_for('uploaded_file', filename=filename))
return "Unable to upload."
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in allowed_extensions
if __name__ == '__main__':
app.config['UPLOAD FOLDER'] = folder_upload
app.run(host = '0.0.0.0', debug=True)
As I do not have the HTML files yet (hence the commented out return redirect), I use CocoaRestClient for testing, and here are the parameters I used:
Everything okay so far, until I hit the Submit button. Then, the following error appears:
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Library/Python/2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Python/2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Library/Python/2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/myusername/Documents/Project_Omnimoda/API/main.py", line 192, in add_picture
return redirect(url_for('uploaded_file', filename=filename))
File "/Library/Python/2.7/site-packages/flask/helpers.py", line 312, in url_for
return appctx.app.handle_url_build_error(error, endpoint, values)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1641, in handle_url_build_error
reraise(exc_type, exc_value, tb)
File "/Library/Python/2.7/site-packages/flask/helpers.py", line 305, in url_for
force_external=external)
File "/Library/Python/2.7/site-packages/werkzeug/routing.py", line 1649, in build
raise BuildError(endpoint, values, method)
BuildError: ('uploaded_file', MultiDict([('filename', '3611571-dc_holiday.jpg')]), None)
Funny thing is, the image '3611571-dc_holiday.jpg' actually did get copied from my Downloads folder to the Project_Upload folder, so it worked, there's just an error that I'm not sure how to solve.
Any ideas? Thanks.
You haven't defined the uploaded_file endpoint. You need to do that.
#CustomersAPI.route('/customers/SOMETHINGOGESTHERE')
def uploaded_file(filename):
# Do something here with the file, like return it.
return send_from_directory(
folder_upload, filename, as_attachment=True)
Related
I am getting the error jinja2.exceptions.TemplateNotFound. Even I have my HTML files in the templates folder, still I am receiving this error. It was working fine sometime ago, and now I am getting this error.
Full error code:
Traceback (most recent call last)
File "E:\price\web\Lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "E:\price\web\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "E:\price\web\Lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "E:\price\web\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "E:\price\web\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "E:\price\web\Lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "E:\price\web\Lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "E:\price\web\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "E:\price\web\Lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "E:\price\web\Lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "E:\price\web\flasktest.py", line 6, in index
return render_template('about.html')
File "E:\price\web\Lib\site-packages\flask\templating.py", line 138, in render_template
ctx.app.jinja_env.get_or_select_template(template_name_or_list),
File "E:\price\web\Lib\site-packages\jinja2\environment.py", line 1068, in get_or_select_template
return self.get_template(template_name_or_list, parent, globals)
File "E:\price\web\Lib\site-packages\jinja2\environment.py", line 997, in get_template
return self._load_template(name, globals)
File "E:\price\web\Lib\site-packages\jinja2\environment.py", line 958, in _load_template
template = self.loader.load(self, name, self.make_globals(globals))
File "E:\price\web\Lib\site-packages\jinja2\loaders.py", line 125, in load
source, filename, uptodate = self.get_source(environment, name)
File "E:\price\web\Lib\site-packages\flask\templating.py", line 60, in get_source
return self._get_source_fast(environment, template)
File "E:\price\web\Lib\site-packages\flask\templating.py", line 89, in _get_source_fast
raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: about.html
Here's my code snippet:
from flask import Flask, render_template
app = Flask('test', template_folder= 'templates')
#app.route('/')
def index():
return render_template('about.html')
if __name__ == '__main__':
app.run(debug = True, host = '127.0.0.1', port = 5000)
Here is the screenshot of my directories:
Update:
My code is working perfectly in a new file. Is it due to cache?
Tried app = Flask(name) but still same issue.
A new Test.py file works completely fine but not the old ones.
have a look at this topic https://flask.palletsprojects.com/en/2.0.x/api/#application-object and head over this section About the First Parameter
so my guess, you should import the right package name,
so try __name__ instead of test
app = Flask(__name__, template_folder='templates')
BTW, Flask already expects templates as default folder to look at, meaning it's optional and you can define your app like so
app = Flask(__name__)
Flask looks for templates by default in the "templates" folder https://flask.palletsprojects.com/en/2.0.x/quickstart/#rendering-templates.
Try this:
app = Flask(__name__)
#app.route('/')
def index():
return render_template('about.html')
Finally I got the solution where it went wrong.
I was doing this:
app = Flask('__name__')
But the correct way was this:
app = Flask(__name__)
I'm building my first flask app and am having trouble accessing my uploaded files in functions later on in my script. I'm using a variation of the basic Flask Upload script, and currently I have two forms which each take in some sort of text file. I am trying to run the input files through a function later on in my script to compare discrepancies. As it is right now I get this error:
UnboundLocalError: local variable 'filename1' referenced before assignment
I'm trying to get my head around if this is a form issue, or a saved file issue.
Here is my upload folder:
UPLOAD_FOLDER = '/uploads'
ALLOWED_EXTENSIONS = set(['doc', 'docx', 'html', 'txt','rtf'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.secret_key = 'MySecretKey'
if not os.path.isdir(UPLOAD_FOLDER):
os.mkdir(UPLOAD_FOLDER)
And here is one of the file uploads, the other is almost identical besides the filenames:
def allowed_audio_file(reference_file):
return '.' in reference_file and \
reference_file.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
#app.route('/referenceupload', methods=['GET', 'POST'])
def upload_reference_file():
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
ref_file = request.files['file']
# if user does not select file, browser also
# submit a empty part without filename
if ref_file.filename == '':
flash('No selected file')
return redirect(request.url)
if ref_file and allowed_audio_file(ref_file.filename):
filename1 = secure_filename(ref_file.filename)
ref_file.save(os.path.join(UPLOAD_FOLDER, filename1))
return redirect(url_for('uploaded_reference_file',
filename1=filename1))
return render_template('reference.html', filename1=filename1)
#app.route('/uploads/<filename1>')
def uploaded_reference_file(filename1):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename1)
Here is the full error:
File "C:\Python\Python36\lib\site-packages\flask\app.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python\Python36\lib\site-packages\flask\app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "C:\Python\Python36\lib\site-packages\flask\app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python\Python36\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\Python\Python36\lib\site-packages\flask\app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python\Python36\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python\Python36\lib\site-packages\flask\app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python\Python36\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\Python\Python36\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python\Python36\lib\site-packages\flask\app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\Jesse\eclipse-workspace\WER\src\Word_error_rate\uploads.py", line 55, in upload_reference_file
return render_template('reference.html', filename1=filename1)
UnboundLocalError: local variable 'filename1' referenced before assignment
following the document conversion API example trying to use Flask to convert msword document to text, but it does not work.
Here is the code
import os, json, requests
from flask import Flask, jsonify
from watson_developer_cloud import DocumentConversionV1
app = Flask(__name__) #create flask instance
#app.route('/')
def Welcome():
v = json.loads(os.getenv('VCAP_SERVICES'))
svcName = 'document_conversion'
svc = v[svcName][0]['credentials']
url = svc['url']
user = svc['username']
password = svc['password']
document_conversion = DocumentConversionV1(username=user, password=password,version='2015-12-15')
# Example of retrieving html or plain text
with open('./doc.docx', 'rb') as document:
config = {'conversion_target': DocumentConversionV1.NORMALIZED_TEXT}
print(json.dumps(document_conversion.convert_document(document=document, config=config),indent=2))
if __name__ == "__main__":
port = os.getenv('VCAP_APP_PORT', '5000')
app.run(host='0.0.0.0', port=int(port),debug=True)
Here is the runtime log
File "/home/vcap/app/.heroku/python/lib/python3.5/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/home/vcap/app/.heroku/python/lib/python3.5/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/home/vcap/app/.heroku/python/lib/python3.5/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/vcap/app/.heroku/python/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/home/vcap/app/.heroku/python/lib/python3.5/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/home/vcap/app/.heroku/python/lib/python3.5/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/vcap/app/.heroku/python/lib/python3.5/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/vcap/app/.heroku/python/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/home/vcap/app/.heroku/python/lib/python3.5/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/home/vcap/app/.heroku/python/lib/python3.5/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/vcap/app/welcome.py", line 39, in Welcome
password = svc['password']
document_conversion = DocumentConversionV1(username=user, password=password,version='2015-12-15')
# Example of retrieving html or plain text
with open('./doc.docx', 'rb') as document:
config = {'conversion_target': DocumentConversionV1.NORMALIZED_TEXT}
print(json.dumps(document_conversion.convert_document(document=document, config=config),indent=2))
if __name__ == "__main__":
port = os.getenv('VCAP_APP_PORT', '5000')
File "/home/vcap/app/.heroku/python/lib/python3.5/json/__init__.py", line 237, in dumps
**kw).encode(obj)
File "/home/vcap/app/.heroku/python/lib/python3.5/json/encoder.py", line 201, in encode
chunks = list(chunks)
File "/home/vcap/app/.heroku/python/lib/python3.5/json/encoder.py", line 436, in _iterencode
o = _default(o)
File "/home/vcap/app/.heroku/python/lib/python3.5/json/encoder.py", line 180, in default
raise TypeError(repr(o) + " is not JSON serializable")
The documentation appears to be out of date. The object returned is a Response object, as seen in the Requests library. In my experience, you can just use .text to get a string representing the JSON. I should say, you might have to use the .json representation to get something you can call .dumps() on.
I am building a basic app with Flask: it has a unique route that requests just a token authentication, i.e. if the token provided in the headers is correct, then the request is satisfied. To do so, I installed both Flask and Flask-Security. This is a snippet of my app:
from flask import Flask
from flask.ext.security import auth_token_required
from flask.ext.security import Security
app = Flask(__name__)
app.config['SECURITY_TOKEN_AUTHENTICATION_KEY'] = 'mytoken'
security = Security(app)
#app.route('/myurl')
#auth_token_required
def myrequest():
return 'OK'
if __name__ == '__main__':
app.run(debug=True)
I test it by running:
$ curl -H 'Authorization: Token token="mytoken"' localhost:5000/myurl
or even:
$ curl localhost:5000/myurl
However, I get the following error:
Traceback (most recent call last):
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask_security/decorators.py", line 113, in decorated
if _check_token():
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask_security/decorators.py", line 50, in _check_token
header_key = _security.token_authentication_header
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/werkzeug/local.py", line 338, in __getattr__
return getattr(self._get_current_object(), name)
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/werkzeug/local.py", line 297, in _get_current_object
return self.__local()
File "/Users/username/.virtualenvs/my_env/lib/python2.7/site-packages/flask_security/decorators.py", line 24, in <lambda>
_security = LocalProxy(lambda: current_app.extensions['security'])
KeyError: 'security'
Do you know where the error lies? Is it in the app or in some conflicts among the Flask libraries?
EDIT: added Security(app) initialization
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)
I've get UnicodeEncodeError, when I try to create model instance with unicode field using curl
Here's my code, I've put it in one file for simplicity:
import flask
import flask.ext.sqlalchemy
import flask.ext.restless
from flask import send_from_directory
from sqlalchemy import Column, UnicodeText
from sqlalchemy.ext.declarative import declarative_base
app = flask.Flask(__name__, static_url_path='')
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://scott:tiger#localhost:5432/db'
db = flask.ext.sqlalchemy.SQLAlchemy(app)
Base = declarative_base()
class Tag(Base):
__tablename__ = 'tags'
name = Column(UnicodeText, primary_key=True)
# debug only
#app.route('/')
def index():
return send_from_directory('templates', 'index.html')
if __name__ == '__main__':
manager = flask.ext.restless.APIManager(app, flask_sqlalchemy_db=db)
# Create API endpoints, which will be available at /api/<tablename> by
# default. Allowed HTTP methods can be specified as well.
manager.create_api(Tag, methods=['GET', 'POST', 'DELETE'])
# start the flask loop
app.run(host='0.0.0.0', debug=True)
When I try to create model, using curl:
curl -i -H "Content-Type: application/json;charset=utf-8" -X POST -d '{"name": "ащьф"}' http://127.0.0.1:5000/api/tags
I get following error:
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/usr/local/lib/python2.7/dist-packages/flask_restless/views.py", line 139, in decorator
return func(*args, **kw)
File "/usr/local/lib/python2.7/dist-packages/mimerender.py", line 227, in wrapper
result = target(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/flask/views.py", line 84, in view
return self.dispatch_request(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/flask/views.py", line 149, in dispatch_request
return meth(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/flask_restless/views.py", line 1230, in post
primary_key = str(result[primary_key_name(instance)])
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-9: ordinal not in range(128)
How can I avoid this issue? I think I need to create preprocessors, which will be encode data correctly, or is there more easier way to fix this problem?
This looks like a bug with Flask-Restless. I noticed you've already submitted an issue there. If you find the solution, open a pull request and update us on the answer.