ModuleNotFoundError: No module named 'MySQLdb' in Flask-sqlalchemy - flask

I am just new in Flask, so I am trying to send data to the database using different tutorial source. I build simple blog type websites and my database server is http://localhost/phpmyadmin/. After I clicked on the submit button on contact.html. I got this error. So how can I fixed this error.
Traceback (most recent call last):
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\sqlalchemy\util\_collections.py", line 1020, in __call__
return self.registry[key]
KeyError: 6528
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "F:\Flask\01\tut1.py", line 33, in contact
db.session.add(entry)
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\sqlalchemy\orm\scoping.py", line 163, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\sqlalchemy\util\_collections.py", line 1022, in __call__
return self.registry.setdefault(key, self.createfunc())
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\sqlalchemy\orm\session.py", line 3286, in __call__
return self.class_(**local_kw)
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_sqlalchemy\__init__.py", line 138, in __init__
bind = options.pop('bind', None) or db.engine
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_sqlalchemy\__init__.py", line 943, in engine
return self.get_engine()
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_sqlalchemy\__init__.py", line 962, in get_engine
return connector.get_engine()
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_sqlalchemy\__init__.py", line 556, in get_engine
self._engine = rv = self._sa.create_engine(sa_url, options)
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_sqlalchemy\__init__.py", line 972, in create_engine
return sqlalchemy.create_engine(sa_url, **engine_opts)
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\sqlalchemy\engine\__init__.py", line 500, in create_engine
return strategy.create(*args, **kwargs)
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\sqlalchemy\engine\strategies.py", line 87, in create
dbapi = dialect_cls.dbapi(**dbapi_args)
File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\sqlalchemy\dialects\mysql\mysqldb.py", line 118, in dbapi
return __import__("MySQLdb")
ModuleNotFoundError: No module named 'MySQLdb'
My code is here
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:#localhost/blog'
db = SQLAlchemy(app)
class Contacts(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
email = db.Column(db.String(255), nullable=False)
phone_number = db.Column(db.String(50), nullable=False)
message = db.Column(db.String(120), nullable=False)
date_created = db.Column(db.String(50), nullable=True )
#app.route('/contact/', methods=['GET','POST'])
def contact():
if request.method == 'POST':
name = request.form.get('name')
email = request.form.get('email')
phone_number = request.form.get('phone_number')
message = request.form.get('message')
entry = Contacts(name=name, email=email, phone_number=phone_number, message=message, date_created=datetime.now())
db.session.add(entry)
db.session.commit()
return render_template('contact.html')
app.run(debug=True)
Does anyone knows, how I get this error ?

Running command pip install pymysql and pip install mysqldbmodel help me to kicked this freaking(**) error.
Edit:
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:#localhost/blog'
I find this solution at ImportError: No module named MySQLdb

datetime.now: Does not return a String you need to convert it to String or change the type in the database to date like this
date_created = db.Column(db.DateTime, nullable=True )
I have used this and it worked very will with me
from flask import Flask, render_template, request,redirect
from flask_sqlalchemy import SQLAlchemy
import sqlite3
from datetime import *
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database1.db'
db = SQLAlchemy(app)
class Contacts(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
email = db.Column(db.String(255), nullable=False)
phone_number = db.Column(db.String(50), nullable=False)
message = db.Column(db.String(120), nullable=False)
date_created = db.Column(db.DateTime, nullable=True )
db.create_all()
#app.route('/contact', methods=['GET','POST'])
def contact():
if request.method == 'POST':
name = request.form.get('name')
email = request.form.get('email')
phone_number = request.form.get('phone_number')
message = request.form.get('message')
entry = Contacts(name="name", email="email", phone_number="phone_number", message="message", date_created=datetime.now())
try:
db.session.add(entry)
db.session.commit()
db.session.close()
return render_template('h.html')
except:
return "Error"
app.run(debug=True)
You need to change the things i have changed like the render_template
if it did not work please provide you github

Related

How to specify SQLAlchemy ForeignKey with specific schema name?

I have a Flask / Flask-User app that I am trying to convert from Python 3.6 to Flask / Flask-Security-Too under Python 3.10. There have been a lot of changes in the world since 3.6 and I am playing whack-a-mole trying to figure them out. In this particular case I am redoing the database tables since nothing from the old app needs to transfer to the new version. I am using the latest version of PyCharm and all of the latest versions of the libraries that Flask and Flask-Security-Too require.
Things to note: the target database is an MS SQL Server instance. There is an existing "database" that I must use and a specific "schema name" under which any tables I create must live.
I have successfully run flask db init and am trying to run the first flask db migrate but get the error:
(venv) PS C:\Users\me\PycharmProjects\MyProject\UserInterface\MyApp> flask db migrate
INFO [alembic.runtime.migration] Context impl MSSQLImpl.
INFO [alembic.runtime.migration] Will assume transactional DDL.
Traceback (most recent call last):
File "C:\Python310\lib\runpy.py", line 196, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Python310\lib\runpy.py", line 86, in _run_code
exec(code, run_globals)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\Scripts\flask.exe\__main__.py", line 7, in <module>
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\flask\cli.py", line 988, in main
cli.main()
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\flask\cli.py", line 579, in main
return super().main(*args, **kwargs)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\click\core.py", line 1055, in main
rv = self.invoke(ctx)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\click\core.py", line 1657, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\click\core.py", line 1657, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\click\core.py", line 1404, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\click\core.py", line 760, in invoke
return __callback(*args, **kwargs)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\click\decorators.py", line 26, in new_func
return f(get_current_context(), *args, **kwargs)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\flask\cli.py", line 427, in decorator
return __ctx.invoke(f, *args, **kwargs)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\click\core.py", line 760, in invoke
return __callback(*args, **kwargs)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\flask_migrate\cli.py", line 104, in migrate
_migrate(directory, message, sql, head, splice, branch_label, version_path,
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\flask_migrate\__init__.py", line 98, in wrapped
f(*args, **kwargs)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\flask_migrate\__init__.py", line 155, in migrate
command.revision(config, message, autogenerate=True, sql=sql,
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\command.py", line 229, in revision
script_directory.run_env()
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\script\base.py", line 569, in run_env
util.load_python_file(self.dir, "env.py")
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\util\pyfiles.py", line 94, in load_python_file
module = load_module_py(module_id, path)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\util\pyfiles.py", line 110, in load_module_py
spec.loader.exec_module(module) # type: ignore
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\MyApp\migrations\env.py", line 104, in <module>
run_migrations_online()
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\MyApp\migrations\env.py", line 98, in run_migrations_online
context.run_migrations()
File "<string>", line 8, in run_migrations
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\runtime\environment.py", line 853, in run_migrations
self.get_context().run_migrations(**kw)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\runtime\migration.py", line 611, in run_migrations
for step in self._migrations_fn(heads, self):
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\command.py", line 205, in retrieve_migrations
revision_context.run_autogenerate(rev, context)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\autogenerate\api.py", line 526, in run_autogenerate
self._run_environment(rev, migration_context, True)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\autogenerate\api.py", line 573, in _run_environment
compare._populate_migration_script(
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\autogenerate\compare.py", line 55, in _populate_migration_script
_produce_net_changes(autogen_context, upgrade_ops)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\autogenerate\compare.py", line 89, in _produce_net_changes
comparators.dispatch("schema", autogen_context.dialect.name)(
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\util\langhelpers.py", line 267, in go
fn(*arg, **kw)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\autogenerate\compare.py", line 125, in _autogen_for_tables
[(table.schema, table.name) for table in autogen_context.sorted_tables]
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 1113, in __get__
obj.__dict__[self.__name__] = result = self.fget(obj)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\alembic\autogenerate\api.py", line 443, in sorted_tables
result.extend(m.sorted_tables)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\sqlalchemy\sql\schema.py", line 4697, in sorted_tables
return ddl.sort_tables(
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\sqlalchemy\sql\ddl.py", line 1213, in sort_tables
for (t, fkcs) in sort_tables_and_constraints(
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\sqlalchemy\sql\ddl.py", line 1291, in sort_tables_and_constraints
dependent_on = fkc.referred_table
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\sqlalchemy\sql\schema.py", line 3808, in referred_table
return self.elements[0].column.table
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 1113, in __get__
obj.__dict__[self.__name__] = result = self.fget(obj)
File "C:\Users\me\PycharmProjects\MyProject\UserInterface\venv\lib\site-packages\sqlalchemy\sql\schema.py", line 2507, in column
raise exc.NoReferencedTableError(
sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'roles_users.role_id' could not find table 'role' with which to generate a foreign key to target column 'id'
The User and Role models look like (pruned for length):
### USER
#
import uuid
from flask_security import UserMixin
from sqlalchemy import Column, Integer, String, Boolean, Unicode, DateTime, func
from sqlalchemy.orm import relationship, backref
from app.database import Base
class User(Base, UserMixin):
__tablename__ = 'user'
__table_args__ = {"schema": "ExistingSchemaName"}
id = Column(Integer,primary_key=True)
email = Column(Unicode(255),nullable=False,server_default=u'',unique=True)
...
# Flask-Security-Too fields
fs_uniquifier = Column(String(255), unique=True, nullable=False)
confirmed_at = Column(DateTime())
last_login_at = Column(DateTime())
current_login_at = Column(DateTime())
last_login_ip = Column(String(100))
current_login_ip = Column(String(100))
login_count = Column(Integer)
# Relationships
child_roles = relationship('Role',back_populates='parent_user')
import uuid
### ROLE
#
from flask_security import RoleMixin
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from app.database import Base
class Role(Base, RoleMixin):
__tablename__ = 'role'
__table_args__ = {"schema": "ExistingSchemaName"}
id = Column(Integer(),primary_key=True)
name = Column(String(64),nullable=False,server_default=u'',unique=True)
description = Column(String(255),nullable=False,server_default=u'')
# Have also tried adding schema name to ForeignKey without success, as in:
# user_id = Column(Integer,ForeignKey("ExistingSchemaName.user.id"))
user_id = Column(Integer,ForeignKey("user.id"))
parent_user = relationship("User",back_populates="child_roles")
The app.database.py file looks like:
from .settings import SQLALCHEMY_DATABASE_URI
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine(SQLALCHEMY_DATABASE_URI)
db = scoped_session(
sessionmaker(
autocommit=False,
autoflush=False,
bind=engine
)
)
Base = declarative_base()
Base.query = db.query_property()
def init_db():
import app.models
Base.metadata.create_all(bind=engine)
I think that I have set the one-to-many relationships correctly but I do not know what I am missing.

Marshmallow for python giving ValueError: not enough values to unpack (expected 2, got 1)

I am using Marshmallow for serialization/deserialization purposes in the API I am building but I'm getting the above-stated error. Here are my Schema, Model, and Resource file for the same.
schemas/post.py
from marshmallow import Schema, fields, validate, post_dump
from schemas.user import UserSchema
class PostSchema(Schema):
class Meta:
ordered = True
id = fields.Int(dump_only=True)
body = fields.Str(required=True, validate=[validate.Length(max=500, min=1)])
created_at = fields.DateTime(dump_only=True)
updated_at = fields.DateTime(dump_only=True)
author = fields.Nested(UserSchema, attribute='user', dump_only=True, only=['id', 'username'])
#post_dump(pass_many=True)
def wrap_output_with_envelope(self, data, many, **kwargs):
if many:
return {'data': data}
return data
models/post.py
from database import db
class Post(db.Model):
__tablename__ = 'post'
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.String, nullable=False)
created_at = db.Column(db.DateTime(), nullable=False, server_default=db.func.now())
updated_at = db.Column(db.DateTime(), nullable=False, server_default=db.func.now(), onupdate=db.func.now())
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
#classmethod
def get_by_post_id(cls, id):
return cls.query.filter_by(id=id).first()
#classmethod
def get_all_posts(cls):
return cls.query.all()
def data(self):
return {'id': self.id, 'body': self.body, 'user_id': self.user_id}
def save(self):
db.session.add(self)
db.session.commit()
def delete(self):
db.session.delete(self)
db.session.commit()
and resources/post.py
from flask import request
from flask_restful import Resource
from http import HTTPStatus
from flask_jwt_extended import jwt_required, get_jwt_identity, jwt_optional
from models.post import Post
from schemas.post import PostSchema
post_schema = PostSchema()
post_list_schema = PostSchema(many=True)
class PostListResource(Resource):
def get(self):
posts = Post.get_all_posts()
return post_list_schema.dump(posts), HTTPStatus.OK
#jwt_required
def post(self):
json_data = request.get_json()
current_user = get_jwt_identity()
data, errors = post_schema.load(data=json_data)
if errors:
return {'message': "Validation errors", 'errors': errors}, HTTPStatus.BAD_REQUEST
post = Post(**data)
post.user_id = current_user
post.save()
return post_schema.dump(post), HTTPStatus.CREATED
I try sending the following JSON: {"body": "This is some text."} and the error I get is:
Traceback (most recent call last):
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask_restful\__init__.py", line 272, in error_router
return original_handler(e)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\_compat.py", line 38, in reraise
raise value.with_traceback(tb)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask_restful\__init__.py", line 272, in error_router
return original_handler(e)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\_compat.py", line 38, in reraise
raise value.with_traceback(tb)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask_restful\__init__.py", line 468, in wrapper
resp = resource(*args, **kwargs)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask\views.py", line 89, in view
return self.dispatch_request(*args, **kwargs)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask_restful\__init__.py", line 583, in dispatch_request
resp = meth(*args, **kwargs)
File "C:\Users\USER\.virtualenvs\blogposts-QxTRQ3FG\Lib\site-packages\flask_jwt_extended\view_decorators.py", line 108, in wrapper
return fn(*args, **kwargs)
File "D:\blogposts\resources\post.py", line 23, in post
data, errors = post_schema.load(data=json_data)
ValueError: not enough values to unpack (expected 2, got 1)
Please help. Thanks!
You must have been following an outdated doc/tuto.
Since marshmallow 3, only data is returned. A ValidationError is raised in case of error.
Change
data, errors = post_schema.load(data=json_data)
if errors:
return {'message': "Validation errors", 'errors': errors}, HTTPStatus.BAD_REQUEST
into
try:
data = post_schema.load(data=json_data)
except ValidationError as exc:
return {'message': "Validation errors", 'errors': exc.messages}, HTTPStatus.BAD_REQUEST

Error while select_related query

I have Question and QuestionChoices models as below, when I try to retrieve the Question and related Answers from the Questionchoices I get the below error saying that the query is expecting string. What could be wrong model/query?
class Question(models.Model):
Question_Id = models.AutoField(primary_key=True)
Question_Text = models.TextField(max_length=1000)
def __str__(self):
return self.Question_Text
def __int__(self):
return self.Question_Id
class QuestionChoices(models.Model):
Choice_Id = models.AutoField(primary_key=True)
Question_Choices_Question_Id = models.ForeignKey("Question", on_delete=models.CASCADE)
Choice = models.TextField(max_length=500)
Is_Right_Choice = models.BooleanField(default=False)
>>> QuestionChoices.objects.select_related().filter(Question_Choices_Question_Id = Question.Question_Id)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 836, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 854, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\query.py", line 1253, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\query.py", line 1277, in _add_q
split_subq=split_subq,
File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\query.py", line 1215, in build_filter
condition = self.build_lookup(lookups, col, value)
File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\query.py", line 1085, in build_lookup
lookup = lookup_class(lhs, rhs)
File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\lookups.py", line 18, in __init__
self.rhs = self.get_prep_lookup()
File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\fields\related_lookups.py", line 115, in get_prep_lookup
self.rhs = target_field.get_prep_value(self.rhs)
File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\fields\__init__.py", line 947, in get_prep_value
return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute'
I got the same error after running your shell command. The problem is caused by the way the code's filter() is set-up. The argument requires a model object OR foreign key as the value.
Answer:
python3 manage.py shell
>>> from my_app.models import *
>>> my_question_obj = Question.objects.create(Question_Text = "This is my question")
>>> QuestionChoices.objects.select_related().filter(Question_Choices_Question_Id=my_model_obj)
Alternatively if you already have a question you would like to filter on in your database you can use get() to retrieve the object.
python3 manage.py shell
>>> from my_app.models import *
>>> my_question_obj = Question.objects.get(Question_Text="This is the text of your question")
>>> QuestionChoices.objects.select_related().filter(Question_Choices_Question_Id = my_model_obj)

Flask Security, Flask Mail AttributeError: 'NoneType' object has no attribute 'send'

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.

PyMySql + SQLAlchemy on Flask: create_all fails

I am starting a brand new project that involves Flask + SQLAlchemy with pymysql. Currently, creation of tables based on model fails with the following:
The lines in my code (main.py) leading up to the error are:
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://myapp:myapp#localhost/myapp'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
guid = db.Column(db.String(255), unique=True)
def __init__(self):
self.guid = str(uuid.uuid1())
db.create_all()
# Note: We don't need to call run() since our application is embedded within
# the App Engine WSGI application server.
#app.route('/')
def hello():
"""Return a friendly HTTP greeting."""
return 'Hello World!'
#app.errorhandler(404)
def page_not_found(e):
"""Return a custom 404 error."""
return 'Sorry, nothing at this URL.', 404
Traceback (most recent call last):
File "/Users/myuserid/Documents/Development/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/Users/myuserid/Documents/Development/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "/Users/myuserid/Documents/Development/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 85, in LoadObject
obj = __import__(path[0])
File "/Users/myuserid/Documents/Development/myapp-server/main.py", line 9, in <module>
db.create_all()
File "/Users/myuserid/Documents/Development/myapp-server/lib/flask_sqlalchemy/__init__.py", line 895, in create_all
self._execute_for_all_tables(app, bind, 'create_all')
File "/Users/myuserid/Documents/Development/myapp-server/lib/flask_sqlalchemy/__init__.py", line 887, in _execute_for_all_tables
op(bind=self.get_engine(app, bind), **extra)
File "/Users/myuserid/Documents/Development/myapp-server/lib/sqlalchemy/sql/schema.py", line 3614, in create_all
tables=tables)
File "/Users/myuserid/Documents/Development/myapp-server/lib/sqlalchemy/engine/base.py", line 1850, in _run_visitor
with self._optional_conn_ctx_manager(connection) as conn:
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py", line 17, in __enter__
return self.gen.next()
File "/Users/myuserid/Documents/Development/myapp-server/lib/sqlalchemy/engine/base.py", line 1843, in _optional_conn_ctx_manager
with self.contextual_connect() as conn:
File "/Users/myuserid/Documents/Development/myapp-server/lib/sqlalchemy/engine/base.py", line 2034, in contextual_connect
self._wrap_pool_connect(self.pool.connect, None),
File "/Users/myuserid/Documents/Development/myapp-server/lib/sqlalchemy/engine/base.py", line 2069, in _wrap_pool_connect
return fn()
File "/Users/myuserid/Documents/Development/myapp-server/lib/sqlalchemy/pool.py", line 376, in connect
return _ConnectionFairy._checkout(self)
File "/Users/myuserid/Documents/Development/myapp-server/lib/sqlalchemy/pool.py", line 708, in _checkout
fairy = _ConnectionRecord.checkout(pool)
File "/Users/myuserid/Documents/Development/myapp-server/lib/sqlalchemy/pool.py", line 480, in checkout
rec = pool._do_get()
File "/Users/myuserid/Documents/Development/myapp-server/lib/sqlalchemy/pool.py", line 1049, in _do_get
self._dec_overflow()
File "/Users/myuserid/Documents/Development/myapp-server/lib/sqlalchemy/util/langhelpers.py", line 60, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "/Users/myuserid/Documents/Development/myapp-server/lib/sqlalchemy/pool.py", line 1046, in _do_get
return self._create_connection()
File "/Users/myuserid/Documents/Development/myapp-server/lib/sqlalchemy/pool.py", line 323, in _create_connection
return _ConnectionRecord(self)
File "/Users/myuserid/Documents/Development/myapp-server/lib/sqlalchemy/pool.py", line 449, in __init__
self.connection = self.__connect()
File "/Users/myuserid/Documents/Development/myapp-server/lib/sqlalchemy/pool.py", line 602, in __connect
connection = self.__pool._invoke_creator(self)
File "/Users/myuserid/Documents/Development/myapp-server/lib/sqlalchemy/engine/strategies.py", line 97, in connect
return dialect.connect(*cargs, **cparams)
File "/Users/myuserid/Documents/Development/myapp-server/lib/sqlalchemy/engine/default.py", line 377, in connect
return self.dbapi.connect(*cargs, **cparams)
File "/Users/myuserid/Documents/Development/myapp-server/lib/pymysql/__init__.py", line 88, in Connect
return Connection(*args, **kwargs)
File "/Users/myuserid/Documents/Development/myapp-server/lib/pymysql/connections.py", line 644, in __init__
self._connect()
File "/Users/myuserid/Documents/Development/myapp-server/lib/pymysql/connections.py", line 837, in _connect
self._get_server_information()
File "/Users/myuserid/Documents/Development/myapp-server/lib/pymysql/connections.py", line 1048, in _get_server_information
packet = self._read_packet()
File "/Users/myuserid/Documents/Development/myapp-server/lib/pymysql/connections.py", line 882, in _read_packet
packet_header = self._read_bytes(4)
File "/Users/myuserid/Documents/Development/myapp-server/lib/pymysql/connections.py", line 899, in _read_bytes
data = self._rfile.read(num_bytes)
File "/Users/myuserid/Documents/Development/myapp-server/lib/pymysql/_socketio.py", line 64, in readinto
n = e.args[0]
IndexError: tuple index out of range
INFO 2015-05-05 23:30:40,803 module.py:788] default: "GET / HTTP/1.1" 500 -