When a user goes on my flask app with a URL that has more than 3 sub paths, like "domain.com/var1/var2/var3/var4", it throws the error below:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1478, in full_dispatch_request
response = self.make_response(rv)
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1574, in make_response
rv = self.response_class(rv, headers=headers, status=status)
File "/usr/local/lib/python2.7/site-packages/werkzeug/wrappers.py", line 758, in __init__
self.status = status
File "/usr/local/lib/python2.7/site-packages/werkzeug/wrappers.py", line 862, in _set_status
self._status = to_native(value)
File "/usr/local/lib/python2.7/site-packages/werkzeug/_compat.py", line 111, in to_native
return x.encode(charset, errors)
AttributeError: 'NotFound' object has no attribute 'encode'
It works fine for url's that have less than or equal to 3 subpaths like "domain.com/var1/var2/var3", but I have routes for url's with 1, 2, and 3 subpaths.
How can I get my app to go to the 404 Page Not Found method instead of throwing this error?
Thank you!
edit..
Here's a pastebin of the route methods I'm using. http://pastebin.com/kjYsqk9n
Sorry I can't provide an example of this problem, it's really weird and I don't know how to reproduce it myself. My other flask apps work fine, this one doesn't. If anyone needs clarification, please let me know... thanks for all your help!
Found out why it was returning that error. It turns out I was passing in the error object instead of "404" at the end of this line:
return render_template("error.html", usa=usa, canada=canada, breadcrumbs=breadcrumbs, error_code=e), 404
Thanks!
Related
I'm writing a function in Python Flask to deal with the oauth2 call backs of multiple api's.
The function as it stands is:
#app.route('/external_api/<api>/oauth2callback', methods=['POST', 'GET'])
def gdrive_oauth2callback(api):
toReturn = external_api.APIs[api]['lib'].oauth2callback(os.path.join(APP_OAUTH, str(api + '_id.json')))
userSession = UserSession()
userSession.addUserAuth(api)
return toReturn
However this causes a build error:
raise BuildError(endpoint, values, method)
BuildError: ('gdrive_oauth2callback', {}, None)
I'm confused as to why this is happening, as when i replace the api variable with the string 'gdrive' no error is created and it works perfectly. I'm calling the function in the same manner on both occasions (example.com/external_api/gdrive/oauth2callback), I'm wondering if Flask is unable to deal with both a POST request and a GET request at the same time, and if anyone else has had the same issue?
The full error log is below:
ERROR:app:Exception on /external_api/gdrive/connect [GET]
Traceback (most recent call last):
File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/app/app/views.py", line 43, in gdrive_connect
toReturn = external_api.APIs[api]['lib'].makeConnection()
File "/app/app/external_api/gdrive/api.py", line 14, in makeConnection
return flask.redirect(flask.url_for('gdrive_oauth2callback'))
File "/app/.heroku/python/lib/python2.7/site-packages/flask/helpers.py", line 312, in url_for
return appctx.app.handle_url_build_error(error, endpoint, values)
File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1641, in handle_url_build_error
reraise(exc_type, exc_value, tb)
File "/app/.heroku/python/lib/python2.7/site-packages/flask/helpers.py", line 305, in url_for
force_external=external)
File "/app/.heroku/python/lib/python2.7/site-packages/werkzeug/routing.py", line 1616, in build
raise BuildError(endpoint, values, method)
BuildError: ('gdrive_oauth2callback', {}, None) - at=info method=GET path
If anyone could give me any pointers on this that would be great! Thanks!
I think that flask must not be failing, if you take a look to this example, it works perfectly, http://flask.pocoo.org/snippets/62/.
I tried:
from flask import Flask
app = Flask(__name__)
#app.route("/<name>",methods=['POST', 'GET'])
def hello(name):
return "Hello World!"+name
if __name__ == "__main__":
app.run()
and it works fine on post and get requests. I know that isnt enougth but it shows what the problem probably isn’t.
I have an email confirmation feature on my Flask application. For this to work, I must create a token which will go in a confirmation link. To create the token I'm using Its Dangerous like so:
from itsdangerous import URLSafeTimedSerializer
ts = URLSafeTimedSerializer(app.config["SECRET_KEY"])
token = ts.dumps(email, salt='email-confirm-key')
confirm = url_for('confirm', token=token, _external=True)
After running this, I receive an error stating cannot concatenate 'str' and 'NoneType' objects from the following traceback:
Traceback (most recent call last):
File "/Users/pavsidhu/Documents/Web-Development/myapp/env/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/pavsidhu/Documents/Web-Development/myapp/env/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/pavsidhu/Documents/Web-Development/myapp/env/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/pavsidhu/Documents/Web-Development/myapp/env/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Users/pavsidhu/Documents/Web-Development/myapp/env/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/pavsidhu/Documents/Web-Development/myapp/env/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/pavsidhu/Documents/Web-Development/myapp/env/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/pavsidhu/Documents/Web-Development/myapp/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/pavsidhu/Documents/Web-Development/myapp/myapp/views/confirmation.py", line 62, in resend
activateEmail(email)
File "/Users/pavsidhu/Documents/Web-Development/myapp/myapp/views/functions.py", line 34, in activateEmail
token = ts.dumps(email, salt='email-confirm-key')
File "/Users/pavsidhu/Documents/Web-Development/myapp/env/lib/python2.7/site-packages/itsdangerous.py", line 566, in dumps
rv = self.make_signer(salt).sign(payload)
File "/Users/pavsidhu/Documents/Web-Development/myapp/env/lib/python2.7/site-packages/itsdangerous.py", line 412, in sign
return value + sep + self.get_signature(value)
File "/Users/pavsidhu/Documents/Web-Development/myapp/env/lib/python2.7/site-packages/itsdangerous.py", line 347, in get_signature
key = self.derive_key()
File "/Users/pavsidhu/Documents/Web-Development/myapp/env/lib/python2.7/site-packages/itsdangerous.py", line 334, in derive_key
self.secret_key).digest()
TypeError: cannot concatenate 'str' and 'NoneType' objects
I'm unsure what the issue is, as email is a string and the salt is one too. What could be the problem? Thanks.
The issue is this line:
ts = URLSafeTimedSerializer(app.config["SECRET_KEY"])
It looks like your app.config["SECRET_KEY"] is not being set correctly. If you replace that line with this
ts = URLSafeTimedSerializer('test')
You should find that it works. So you need to find out why app.config["SECRET_KEY"] is not being set correctly.
I am developing a website based on Flask and SQLAlchemy
ssis created by sessionmaker in sqlalchemy.orm
Anime, ActorQuote, AnimeComment are models based on database structure
```
#app.route('/page/<anime_name>', methods=['GET', 'POST'])
def show_page(anime_name):
if request.method == 'GET':
anime = ss.query(Anime).filter_by(anime_name=anime_name).first()
actor_quotes = ss.query(ActorQuote).filter_by(anime_id=anime.id).all()
anime_comments = ss.query(AnimeComment).filter_by(anime_id=anime.id).all()
return render_template('page.html', anime=anime, actor_lines=actor_quotes, comments=anime_comments)
As excepted, it would return a page with these arguments -- anime, actor_quotes, anime_comments, and it does, but also throw a Attribute Error.
```
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/windrunner/hiacg/index.py", line 138, in show_page
actor_lines = ss.query(ActorQuote).filter_by(anime_id=anime.id).all()
AttributeError: 'NoneType' object has no attribute 'id'
When I use try-except to catch the error, it throws another UnboundLocalError.
```
try:
anime = ss.query(Anime).filter_by(anime_name=anime_name).first()
actor_quotes = ss.query(ActorQuote).filter_by(anime_id=anime.id).all()
anime_comments = ss.query(AnimeComment).filter_by(anime_id=anime.id).all()
except AttibuteError:
print 'AttibuteError occurs again!'
What is more strange is the website still works well as nothing happened.
/page/化物语 This shows the page as expected without error.
/page/剑风传奇 This shows the page as expected but with error.
In your line
anime = ss.query(Anime).filter_by(anime_name=anime_name).first()
the variable anime is None if not found (as you said in database empty) and thus the AttributeError when trying to access None.id.
Btw I kindly suggest you to use Flask-SQLAlchemy extension that tackles all the db connection logic and exposes some useful functions such as `.first_or_404'.
With it your code would become
anime = Anime.query.filter_by(anime_name=anime_name).first_or_404()
I have a simple code that creates an album in imgur, via pyimgur. This is the code:
#app.route('/get_album')
def get_album():
im = pyimgur.Imgur(CLIENT_ID)
new_album = im.create_album()
return new_album.link
(I tried with im = pyimgur.Imgur(CLIENT_ID) line before the route handlers as well, same thing happens)
On Windows, everything is perfectly fine. However, when I upload the code to my VPS, I get the following error when I try to do something with the api:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1836, in __ca ll__
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 hand le_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 hand le_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 disp atch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/api/imgur.py", line 161, in get_album_link
new_album = im.create_album()
File "/usr/local/lib/python2.7/dist-packages/pyimgur-0.4.2-py2.7.egg/pyimgur/_ _init__.py", line 754, in create_album
resp = self._send_request(url, params=payload, method='POST')
File "/usr/local/lib/python2.7/dist-packages/pyimgur-0.4.2-py2.7.egg/pyimgur/_ _init__.py", line 687, in _send_request
result = request.send_request(url, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/pyimgur-0.4.2-py2.7.egg/pyimgur/r equest.py", line 91, in send_request
content = resp.json()
TypeError: 'dict' object is not callable
I updated flask to the latest version, and I've been using pyimgur 4, latest release I got from github (pip install doesnt work so I had to install it manually, on both Windows and Ubuntu, since some error about setup.py pops out. I used python setup.py install command)
OK, so I have found a solution. The solution was a change in requests module, which probably came along with updated flask or something, so the old method didn't behave like it used to. I updated the requests as well on my VPS (forgot to do it when upgrading flask), and the issue is now solved.
The documentation says to use request.get_json(), but that causes the service to return an error:
Server returned HTTP response code: 500
calling request.data or request.json both work, however.
Stack trace:
Traceback (most recent call last):
File "/home/blake/ves/p27/lib/python2.7/site-packages/flask/app.py", line 1701, in __call__
return self.wsgi_app(environ, start_response)
File "/home/blake/ves/p27/lib/python2.7/site-packages/werkzeug/contrib/fixers.py", line 125, in __call__
return self.app(environ, start_response)
File "/home/blake/ves/p27/lib/python2.7/site-packages/flask/app.py", line 1689, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/home/blake/ves/p27/lib/python2.7/site-packages/flask/app.py", line 1687, in wsgi_app
response = self.full_dispatch_request()
File "/home/blake/ves/p27/lib/python2.7/site-packages/flask/app.py", line 1360, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/blake/ves/p27/lib/python2.7/site-packages/flask/app.py", line 1358, in full_dispatch_request
rv = self.dispatch_request()
File "/home/blake/ves/p27/lib/python2.7/site-packages/flask/app.py", line 1344, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/blake/workspace/starcycle-flask/starcycleweb.py", line 17, in api
print request.get_json()
File "/home/blake/ves/p27/lib/python2.7/site-packages/werkzeug/local.py", line 336, in __getattr__
return getattr(self._get_current_object(), name)
AttributeError: 'Request' object has no attribute 'get_json'
I thought get_json is was the preferred way to get the json data.
In Flask/wrappers.py the method get_json() is defined as method to the class Request.
However, the same file still contains the old, deprecated method json(). If you have an old version of flask, then a) update or b) use request.json() instead.
I had similar error with the flask Response object, it ended up being a version issue, we used flask 0.12.1 and get_json() is available on 1.0.2
Docs:
http://flask.pocoo.org/docs/0.12/api/#response-objects
VS
http://flask.pocoo.org/docs/1.0/api/#response-objects