AttributeError: 'Test' object has no attribute '__name__' - flask

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)

Related

flask application starts correctly but shows an error once logged-in

I am using the dockerized version of this python app.
https://github.com/tunl/cast-sh/blob/dev/cast/app.py
The home-page loads correctly. But after typing the default password "admin", I get an error.
[2021-04-30 15:07:23,451] ERROR in app: Exception on /cast [GET]
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
TypeError: wrapper() missing 1 required positional argument: 'fn'
Not sure if this error is related to docker or flask.
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
I think that within the file "routes.py", line 41 the brackets behind the decorator are missing.
It should read as follows because the decorator allows optional parameters and otherwise the function will not be wrapped correctly.
#http.route("/cast")
#jwt_required()
def index():
# ...

2021-02-16 10:43:57,123 ERROR in app: Exception on / GET?

I want to embed/put a tkinter gui in a flask app, but the code i made seems not to be rendering/show and gives this error when i run my code:
[2021-02-16 10:43:57,123] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\User\untitled0.py", line 14, in my_app
File "C:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 2369, in __init__
Widget.__init__(self, master, 'button', cnf, kw)
File "C:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 2299, in __init__
(widgetName, self._w) + extra + self._options(cnf))
File "C:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 1326, in _options
v = self._register(v)
File "C:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 1372, in _register
self.tk.createcommand(name, f)
RuntimeError: main thread is not in main loop
127.0.0.1 - - [16/Feb/2021 10:43:57] "GET / HTTP/1.1" 500 -
also when i want to run the flask web server it shows Internal Server Error The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
from flask import Flask
from webbrowser import open
app = Flask(__name__)
root = Tk()
root.title("Tkinter")
#app.route('/')
def my_app():
def click():
l = Label(root, text = "You Clicked!").pack()
b = Button(root, text = "Click Me!", command = click).pack()
return(root)
if __name__ == '__main__':
open('http://127.0.0.1:5000/')
app.run()
#root.mainloop()

flask-admin basic example throws builtins.AttributeError exception

Not sure what I am doing wrong. I am following flask-admin's Quick Start guide (link) and just tried running the basic example provided under the Initialization section. When I run that code and browse to localhost:5000/admin/ I get the following error
builtins.AttributeError
AttributeError: 'For' object has no attribute 'test'
There is a detailed exception stack I can paste as well if helpful.
I suspected a dependency is missing and trying reinstalling flask-admin, but it didn't help. Here's my pip freeze output:
$ pip freeze
APScheduler==3.3.1
click==6.7
dominate==2.3.1
Flask==0.12.2
Flask-Admin==1.5.0
Flask-APScheduler==1.7.0
Flask-Bootstrap==3.3.7.1
Flask-SQLAlchemy==2.2
itsdangerous==0.24
Jinja2==2.9.6
MarkupSafe==1.0
python-dateutil==2.6.1
pytz==2017.2
six==1.10.0
SQLAlchemy==1.1.13
SQLAlchemy-Utils==0.32.14
tzlocal==1.4
visitor==0.1.3
Werkzeug==0.12.2
WTForms==2.1
I'm using python 3.6.1
My code is exactly as in the example:
from flask import Flask
from flask.ext.admin import Admin
app = Flask(__name__)
admin = Admin(app)
app.run()
And this is the exception stack:
Traceback (most recent call last):
File "c:\project\.venv\lib\site-packages\flask\app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "c:\project\.venv\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "c:\project\.venv\lib\site-packages\flask\app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "c:\project\.venv\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "c:\project\.venv\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "c:\project\.venv\lib\site-packages\flask\app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "c:\project\.venv\lib\site-packages\flask_admin\base.py", line 69, in inner
return self._run_view(f, *args, **kwargs)
File "c:\project\.venv\lib\site-packages\flask_admin\base.py", line 368, in _run_view
return fn(self, *args, **kwargs)
File "c:\project\.venv\lib\site-packages\flask_admin\base.py", line 452, in index
return self.render(self._template)
File "c:\project\.venv\lib\site-packages\flask_admin\base.py", line 308, in render
return render_template(template, **kwargs)
File "c:\project\.venv\lib\site-packages\flask\templating.py", line 134, in render_template
context, ctx.app)
File "c:\project\.venv\lib\site-packages\flask\templating.py", line 116, in _render
rv = template.render(context)
File "c:\project\.venv\lib\site-packages\jinja2\asyncsupport.py", line 76, in render
return original_render(self, *args, **kwargs)
File "c:\project\.venv\lib\site-packages\jinja2\environment.py", line 1008, in render
return self.environment.handle_exception(exc_info, True)
File "c:\project\.venv\lib\site-packages\jinja2\environment.py", line 780, in handle_exception
reraise(exc_type, exc_value, tb)
File "c:\project\.venv\lib\site-packages\jinja2\_compat.py", line 37, in reraise
raise value.with_traceback(tb)
File "c:\project\.venv\lib\site-packages\flask_admin\templates\bootstrap2\admin\index.html", line 1, in top-level template code
{% extends 'admin/master.html' %}
File "c:\project\.venv\lib\site-packages\flask_admin\templates\bootstrap2\admin\master.html", line 1, in top-level template code
{% extends admin_base_template %}
File "c:\project\.venv\lib\site-packages\jinja2\environment.py", line 543, in _generate
optimized=self.optimized)
File "c:\project\.venv\lib\site-packages\jinja2\compiler.py", line 82, in generate
generator.visit(node)
File "c:\project\.venv\lib\site-packages\jinja2\visitor.py", line 38, in visit
return f(node, *args, **kwargs)
File "c:\project\.venv\lib\site-packages\jinja2\compiler.py", line 772, in visit_Template
self.blockvisit(block.body, block_frame)
File "c:\project\.venv\lib\site-packages\jinja2\compiler.py", line 372, in blockvisit
self.visit(node, frame)
File "c:\project\.venv\lib\site-packages\jinja2\visitor.py", line 38, in visit
return f(node, *args, **kwargs)
File "c:\project\.venv\lib\site-packages\jinja2\compiler.py", line 1130, in visit_If
self.blockvisit(node.body, if_frame)
File "c:\project\.venv\lib\site-packages\jinja2\compiler.py", line 372, in blockvisit
self.visit(node, frame)
File "c:\project\.venv\lib\site-packages\jinja2\visitor.py", line 38, in visit
return f(node, *args, **kwargs)
File "c:\project\.venv\lib\site-packages\jinja2\compiler.py", line 1014, in visit_For
if node.test:
AttributeError: 'For' object has no attribute 'test'
Will appreciate any advice.
I suspect I messed up my venv somehow. I tried again with a brand new venv, installed all packages and now everything works fine. Hope this helps someone.

Using MySQLdb --> conn.select_db() with Flask [duplicate]

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.

Flask test client refuse arobase in data?

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.