I am trying to debug a view in my Flask app that is return a 500 status with the error TypeError: 'bool' object is not callable in the traceback. The view calls login_user from Flask-Login then returns True to indicate that the login was successful.
I have debugged until app_iter = app(environ, start_response) and the app is now a boolean with the value True rather than the Flask app object.
Traceback (most recent call last):
File "D:\Python27\lib\site-packages\flask\app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "D:\Python27\lib\site-packages\flask\app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "D:\Python27\lib\site-packages\flask\app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "D:\Python27\lib\site-packages\flask\app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "D:\Python27\lib\site-packages\flask\app.py", line 1478, in full_dispatch_request
response = self.make_response(rv)
File "D:\Python27\lib\site-packages\flask\app.py", line 1577, in make_response
rv = self.response_class.force_type(rv, request.environ)
File "D:\Python27\lib\site-packages\werkzeug\wrappers.py", line 824, in force_type
response = BaseResponse(*_run_wsgi_app(response, environ))
File "D:\Python27\lib\site-packages\werkzeug\wrappers.py", line 57, in _run_wsgi_app
return _run_wsgi_app(*args)
File "D:\Python27\lib\site-packages\werkzeug\test.py", line 854, in run_wsgi_app
app_iter = app(environ, start_response)
TypeError: 'bool' object is not callable
#app.route('/login', methods=['POST'])
def login():
username = request.form['username']
user = User.query.filter_by(username=username).first()
if user:
login_user(user)
return True
return False
In Flask, a view must return one of the following:
a string
a Response object (or subclass)
a tuple of (string, status, headers) or (string, status)
a valid WSGI application
Flask tests for the first 3 options, and if they don't fit, assumes it is the fourth. You returned True somewhere, and it is being treated as a WSGI application instead.
See About Responses in the documentation.
Related
This is the app.py. i faced this problem on my main project so i created a spearate test project to test it. and it occures again. here i tried to make a database in mongo then create a form out of it. pretty straight forward but no idea why the error happend
from flask_mongoengine.wtf import model_form
from flask_mongoengine import MongoEngine
from flask import render_template,request,Blueprint,Flask
app=Flask(__name__)
db= MongoEngine()
app.config\['MONGODB_SETTINGS'\]={'db':'project_database','host':'localhost','port':27017,'alias':'default'}
\#assign app to database
db.init_app(app)
class Test1(db.Document):
in1=db.StringField()
in2=db.StringField()
in3=db.StringField()
#app.route('/',methods=\['GET','POST'\])
def index():
test=model_form(Test1())
return render_template('inedx.html',test=test)
app.run(debug=True)
This is the error
Traceback (most recent call last):
File "C:\Users\Give Up\AppData\Local\Programs\Python\Python310\lib\site-packages\flask\app.py", line 2548, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\Give Up\AppData\Local\Programs\Python\Python310\lib\site-packages\flask\app.py", line 2528, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\Give Up\AppData\Local\Programs\Python\Python310\lib\site-packages\flask\app.py", line 2525, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\Give Up\AppData\Local\Programs\Python\Python310\lib\site-packages\flask\app.py", line 1822, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\Give Up\AppData\Local\Programs\Python\Python310\lib\site-packages\flask\app.py", line 1820, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\Give Up\AppData\Local\Programs\Python\Python310\lib\site-packages\flask\app.py", line 1796, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
File "g:\Documents\onedrive\OneDrive - MSFT\Huzaifa\CODE\TESST\asdasdasdasd\app.py", line 25, in index
test=model_form(Test1())
File "C:\Users\Give Up\AppData\Local\Programs\Python\Python310\lib\site-packages\flask_mongoengine\wtf\orm.py", line 306, in model_form
return type(model.__name__ + "Form", (base_class,), field_dict)
AttributeError: 'Test1' object has no attribute '__name__'
I wanted to make a ModelForm from Mongo Document. But I have no idea what is the problem
Found the solution. pretty dumb that I didn't notice. but here is the right way
def index():
test=model_form(Test1)
test=test()
return render_template('inedx.html',test=test)
I'm attempting to write a unit test for a url in my application. I used django's Client class to simulate a get() request and compare the response's status code.
Here's the test i'm running:
from unittest.mock import patch
from django.shortcuts import reverse
class DashboardViewTest(TestCase):
#patch("ordering.mixins.OrderingAppPermissionRequired.handle_not_logged_in")
#patch("ordering.mixins.OrderingAppPermissionRequired.handle_no_profile")
#patch("ordering.mixins.OrderingAppPermissionRequired.handle_no_id")
def test_order_list_view(self, *mocks):
client = Client()
response = client.get(reverse('ordering:list'))
self.assertEqual(response.status_code, 200)
I'm facing the following error (path redacted for privacy):
Traceback (most recent call last):
File "[python_root]\python\python37\Lib\unittest\mock.py", line 1191, in patched
return func(*args, **keywargs)
File "[project_root]\ordering\tests\test_dashboard.py", line 20, in test_order_list_view
response = client.get(reverse('ordering:list'))
File "[virtual_env_root]\lib\site-packages\django\test\client.py", line 527, in get
response = super().get(path, data=data, secure=secure, **extra)
File "[virtual_env_root]\lib\site-packages\django\test\client.py", line 339, in get
**extra,
File "[virtual_env_root]\lib\site-packages\django\test\client.py", line 414, in generic
return self.request(**r)
File "[virtual_env_root]\lib\site-packages\django\test\client.py", line 495, in request
raise exc_value
File "[virtual_env_root]\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "[virtual_env_root]\lib\site-packages\django\utils\deprecation.py", line 93, in __call__
response = self.process_response(request, response)
File "[virtual_env_root]\lib\site-packages\django\contrib\sessions\middleware.py", line 45, in process_response
patch_vary_headers(response, ('Cookie',))
File "[virtual_env_root]\lib\site-packages\django\utils\cache.py", line 266, in patch_vary_headers
vary_headers = cc_delim_re.split(response['Vary'])
TypeError: expected string or bytes-like object
Help is appreciated. Thank you.
I'm trying to do some functional testing on Flask view functions.
Currently I'm using login, logout from Flask Security module and when I try to follow the login and logout guide from flask's documentation(http://flask.pocoo.org/docs/0.12/testing/#logging-in-and-out), the 'post' of login seems to not working. I've been getting this same error when I try to post using requests module too.
My Flask-Security's login endpoint is /login_test/
Below are piece of my unit test code.
class TestUser(unittest.TestCase):
#run before each test
def setUp(self):
self.client = app.test_client()
db.create_all()
def tearDown(self):
#db.session.remove()
#DropEverything().drop_db()
pass
def login(self, email, password):
return self.client.post('/login_test/', data=dict(
email=email,
password=password
), follow_redirects=False)
def logout(self):
return self.client.get('/logout', follow_redirects=True)
def test_login_logout(self):
response = self.client.post('/login_test', data=dict(
email='admin',
password='admin'
), follow_redirects=False)
self.assertIn(b'You logged in', response.data)
The error message that I got after hitting test_login_logout is like below. The below is when I hit the url with '/login_test'
Ran 1 test in 0.187s
FAILED (failures=1)
Failure
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/case.py", line 58, in testPartExecutor
yield
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/case.py", line 600, in run
testMethod()
File "/Users/genom003dm/PycharmProjects/sample_accessioning_dev/app/tests/user_management_testing.py", line 38, in test_login_logout
), follow_redirects=False)
File "/Users/genom003dm/sample_accessioning_dev_virtual_env/lib/python3.5/site-packages/werkzeug/test.py", line 801, in post
return self.open(*args, **kw)
File "/Users/genom003dm/sample_accessioning_dev_virtual_env/lib/python3.5/site-packages/flask/testing.py", line 127, in open
follow_redirects=follow_redirects)
File "/Users/genom003dm/sample_accessioning_dev_virtual_env/lib/python3.5/site-packages/werkzeug/test.py", line 764, in open
response = self.run_wsgi_app(environ, buffered=buffered)
File "/Users/genom003dm/sample_accessioning_dev_virtual_env/lib/python3.5/site-packages/werkzeug/test.py", line 677, in run_wsgi_app
rv = run_wsgi_app(self.application, environ, buffered=buffered)
File "/Users/genom003dm/sample_accessioning_dev_virtual_env/lib/python3.5/site-packages/werkzeug/test.py", line 884, in run_wsgi_app
app_rv = app(environ, start_response)
File "/Users/genom003dm/sample_accessioning_dev_virtual_env/lib/python3.5/site-packages/flask/app.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/genom003dm/sample_accessioning_dev_virtual_env/lib/python3.5/site-packages/flask/app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "/Users/genom003dm/sample_accessioning_dev_virtual_env/lib/python3.5/site-packages/flask/app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/genom003dm/sample_accessioning_dev_virtual_env/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/Users/genom003dm/sample_accessioning_dev_virtual_env/lib/python3.5/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/Users/genom003dm/sample_accessioning_dev_virtual_env/lib/python3.5/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/genom003dm/sample_accessioning_dev_virtual_env/lib/python3.5/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/genom003dm/sample_accessioning_dev_virtual_env/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/Users/genom003dm/sample_accessioning_dev_virtual_env/lib/python3.5/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/genom003dm/sample_accessioning_dev_virtual_env/lib/python3.5/site-packages/flask/app.py", line 1590, in dispatch_request
self.raise_routing_exception(req)
File "/Users/genom003dm/sample_accessioning_dev_virtual_env/lib/python3.5/site-packages/flask/app.py", line 1576, in raise_routing_exception
raise FormDataRoutingRedirect(request)
flask.debughelpers.FormDataRoutingRedirect: b'A request was sent to this URL (http://localhost/login_test) but a redirect was issued automatically by the routing system to "http://localhost/login_test/". The URL was defined with a trailing slash so Flask will automatically redirect to the URL with the trailing slash if it was accessed without one. Make sure to directly send your POST-request to this URL since we can\'t make browsers or HTTP clients redirect with form data reliably or without user interaction.\n\nNote: this exception is only raised in debug mode'
If I change the URL to /login_test/ then I get HTTP 400 errors. I'm assuming that this is happening due to the fact that I'm missing form object for login? (but in this case I don't have form object because I'm trying just trying to login with post api).
I want to know is there a way to login using flask-security's /login_test/ url.
Thanks
Ok, I found an answer. The reason why I was only seeing HTTP 400 errors instead of the specifics of HTTP 400 errors are because I put the error handling on Flask app and it just showed me 400 rather than what the actual error was. Once I removed the HTTP 400 error handling, it was saying that the CSRF token was missing. So what I did was to WTF_CSRF_ENABLED = False in app config file.
I'm trying to implement the email function inside my Flask admin panel.
I've successfully integrated it within my admin panel but the problem is when I try to send any mail, it gives me below error with traceback.
builtins.AttributeError
AttributeError: 'NoneType' object has no attribute 'send'
File
"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/app.py", line 2000, in __call__
return self.wsgi_app(environ, start_response)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/app.py", line 1991, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/app.py", line 1567, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/app.py", line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask/app.py", line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask_admin/base.py", line 69, in inner
return self._run_view(f, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/flask_admin/base.py", line 368, in _run_view
return fn(self, *args, **kwargs)
File "/Users/genomics/PycharmProjects/side_project_one/app/security_layer.py", line 44, in index
send_email(admin_form.subject.data, admin_form.sender.data, [i], admin_form.content.data, None)
File "/Users/genomics/PycharmProjects/side_project_one/app/views/send_email.py", line 41, in send_email
mail.send(msg)
AttributeError: 'NoneType' object has no attribute 'send'
send_email.py
mail = None
def configure_mail(app):
# EMAIL SETTINGS
global mail
app.config.update(
MAIL_SERVER='smtp.gmail.com',
MAIL_PORT=587,
MAIL_USE_SSL=False,
MAIL_USERNAME='xxxx',
MAIL_PASSWORD='xxxx',
MAIL_USE_TLS=True,
DEFAULT_MAIL_SENDER='Danny from DPC'
#SECRET_KEY='abcdefd_thats_a_charming_secret_key',
)
mail = Mail(app)
def send_email(subject, sender, recipients, text_body, html_body):
msg = Message(subject, sender=sender, recipients=recipients)
msg.body = text_body
msg.html = html_body
mail.send(msg)
flask_security.py
from app.views.login_forms import AdminForm
from app.views.send_email import send_email
class EmailRegisterView(BaseView):
def is_accessible(self):
if not current_user.is_active or not current_user.is_authenticated:
return False
if current_user.has_role('admin_danny'):
return True
return False
#expose('/', methods=['GET', 'POST'])
def index(self):
admin_form = AdminForm()
if request.method == 'POST':
if admin_form.validate_on_submit():
recipients = [admin_form.recipient.data]
divided_recipients = recipients[0].split(',')
for i in divided_recipients:
send_email(admin_form.subject.data, admin_form.sender.data, [i], admin_form.content.data, None)
return self.render('admin.html', form=admin_form)
Ok, I found a solution.
So my importing structure was wrong
Inside def configure_mail, I have mail = Mail(app) set as global variable.
And that mail variable was not doing anything.
So what I did is, inside my app.init
app.config.update(
MAIL_SERVER='smtp.gmail.com',
MAIL_PORT=587,
MAIL_USE_SSL=False,
MAIL_USERNAME='something',
MAIL_PASSWORD='xxxxxx',
MAIL_USE_TLS=True,
DEFAULT_MAIL_SENDER='Danny from DPC'
# SECRET_KEY='abcdefd_thats_a_charming_secret_key',
)
mail = Mail(app)
and I called this above mail into send_email.py and everything is working fine. I still can't figure out what the exact error was but this did the trick.
I'm trying to set up tests in my Flask but for an unknown reason, Flask fails when I add a parameter with arobase.
I followed the snippet here http://flask.pocoo.org/snippets/26/ and can make a successful request (it works), but when I try to do a post, it fails (with the following exception) :
def test_auth_login_fail(self):
""" Login fail """
result = self.client.post(self._make_url("/auth/login"), data=dict(
email="user#website.com",
password='cxcxz'
))
self.assertEqual(result.status_code, 404)
And the exception :
Traceback (most recent call last):
File "/var/www/html/api/apps/auth/tests/login.py", line 20, in test_auth_login_fail
password='cxcxz'
File "/usr/lib/python2.7/site-packages/werkzeug/test.py", line 772, in post
return self.open(*args, **kw)
File "/usr/lib/python2.7/site-packages/flask/testing.py", line 108, in open
follow_redirects=follow_redirects)
File "/usr/lib/python2.7/site-packages/werkzeug/test.py", line 736, in open
response = self.run_wsgi_app(environ, buffered=buffered)
File "/usr/lib/python2.7/site-packages/werkzeug/test.py", line 659, in run_wsgi_app
rv = run_wsgi_app(self.application, environ, buffered=buffered)
File "/usr/lib/python2.7/site-packages/werkzeug/test.py", line 855, in run_wsgi_app
app_iter = app(environ, start_response)
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/var/www/html/api/utils/middlewares.py", line 55, in __call__
return self.app(environ, start_response)
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1478, in full_dispatch_request
response = self.make_response(rv)
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1577, in make_response
rv = self.response_class.force_type(rv, request.environ)
File "/usr/lib/python2.7/site-packages/werkzeug/wrappers.py", line 827, in force_type
response = BaseResponse(*_run_wsgi_app(response, environ))
File "/usr/lib/python2.7/site-packages/werkzeug/wrappers.py", line 57, in _run_wsgi_app
return _run_wsgi_app(*args)
File "/usr/lib/python2.7/site-packages/werkzeug/test.py", line 855, in run_wsgi_app
app_iter = app(environ, start_response)
TypeError: 'tuple' object is not callable
For informations, this doesn't generate an exception :
def test_auth_login_fail(self):
""" Login fail """
result = self.client.post(self._make_url("/auth/login"), data=dict(
email="userwebsite.com",
password='cxcxz'
))
self.assertEqual(result.status_code, 404)
(notice the "#" removed)
I also removed the Middleware (indicated in the traceback) without much success.
What am I missing ?
Looks like in case of an email is correct, you return something wrong (a tuple) from your view function. And when you pass a malformed email, the value you return is ok.