error in flask-peewee Admin User creation - python

Database example.db is created but generates error !!!
Traceback (most recent call last):
File "db_testing.py", line 39, in admin.save()
File "C:\Users\dell\Envs\surveyApp\lib\site-packages\peewee.py", line 2405, in save
new_pk = insert.execute()
File "C:\Users\dell\Envs\surveyApp\lib\site-packages\peewee.py", line 1721, in execute
return self.database.last_insert_id(self._execute(), self.model_class)
File "C:\Users\dell\Envs\surveyApp\lib\site-packages\peewee.py", line 1420, in _execute
return self.database.execute_sql(sql, params, self.require_commit)
File "C:\Users\dell\Envs\surveyApp\lib\site-packages\peewee.py", line 1824, in execute_sql
res = cursor.execute(sql, params or ())
sqlite3.IntegrityError: column email is not unique
Code
import datetime
from flask import Flask
from flask_peewee.admin import Admin
from flask_peewee.auth import Auth
from flask_peewee.db import Database
from peewee import *
# configure our database
DATABASE = {
'name': 'example.db',
'engine': 'peewee.SqliteDatabase',
}
DEBUG = True
SECRET_KEY = 'ssshhhh'
app = Flask(__name__)
app.config.from_object(__name__)
# instantiate the db wrapper
db = Database(app)
# create an Auth object for use with our flask app and database wrapper
auth = Auth(app, db)
admin = Admin(app, auth)
class Note(db.Model):
message = TextField()
created = DateTimeField(default=datetime.datetime.now)
admin.register(Note)
admin.setup()
if __name__ == '__main__':
auth.User.create_table(fail_silently=True)
Note.create_table(fail_silently=True)
admin = auth.User(username='admin', email='aoeu#gmail.com', admin=True, active=True)
admin.set_password('admin')
admin.save()
app.run()
using example from
http://flask-peewee.readthedocs.org/en/latest/getting-started.html#setting-up-a-simple-base-template

Database was already created, deleting previous database solved it

Related

not able to create database SQLAlchemy with sqllight

It is the first time when I am using SQLAlchemy with sqllight.
My code looks like this:
#we are going to create the flask app
app = Flask(__name__)
global db
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqllite:///databse.db'
app.config['SECRET_KEY'] = 'ca8b6694c31960d1f7ee2d1ac73c669f'
db = SQLAlchemy(app)
app = create_app()
The next step is to go the terminal and type python. The python interpreter will come and I typed "from main import db", since my file is called main I have to imported from the main.
But this is the actual error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/alex/portal/main.py", line 15, in <module>
db = SQLAlchemy(app)
File "/home/alex/portal/venv/lib/python3.10/site-packages/flask_sqlalchemy/extension.py", line 219, in __init__
self.init_app(app)
File "/home/alex/portal/venv/lib/python3.10/site-packages/flask_sqlalchemy/extension.py", line 326, in init_app
engines[key] = self._make_engine(key, options, app)
File "/home/alex/portal/venv/lib/python3.10/site-packages/flask_sqlalchemy/extension.py", line 614, in _make_engine
return sa.engine_from_config(options, prefix="")
File "/home/alex/portal/venv/lib/python3.10/site-packages/sqlalchemy/engine/create.py", line 817, in engine_from_config
return create_engine(url, **options)
File "<string>", line 2, in create_engine
File "/home/alex/portal/venv/lib/python3.10/site-packages/sqlalchemy/util/deprecations.py", line 277, in warned
return fn(*args, **kwargs) # type: ignore[no-any-return]
File "/home/alex/portal/venv/lib/python3.10/site-packages/sqlalchemy/engine/create.py", line 556, in create_engine
entrypoint = u._get_entrypoint()
File "/home/alex/portal/venv/lib/python3.10/site-packages/sqlalchemy/engine/url.py", line 754, in _get_entrypoint
cls = registry.load(name)
File "/home/alex/portal/venv/lib/python3.10/site-packages/sqlalchemy/util/langhelpers.py", line 365, in load
raise exc.NoSuchModuleError(
sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:sqllite
If you have any suggestions please let me know.
Plus I am trying to put this code in the "_ init _.py" from the script in order to have a cleaner code.
You have mis-spelled sqlite as sqllite:
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///databse.db'
But even if you fix that you're going to have additional problems, because you're redefining app at the end of your code. Here's a working example, which is a simplified version of this example from the documentation.
from flask import Flask, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///databse.db"
app.config["SECRET_KEY"] = "ca8b6694c31960d1f7ee2d1ac73c669f"
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String, unique=True, nullable=False)
email = db.Column(db.String)
def as_dict(self):
return {c.name: getattr(self, c.name) for c in self.__table__.columns}
with app.app_context():
db.create_all()
#app.route("/users", methods=["GET"])
def user_list():
res = db.session.execute(db.select(User).order_by(User.username)).scalars()
users = res.fetchall()
return [user.as_dict() for user in users]
#app.route("/users", methods=["POST"])
def user_create():
user = User(**request.get_json())
db.session.add(user)
db.session.commit()
return user.as_dict()
#app.route("/user/<int:id>")
def user_detail(id):
user = db.get_or_404(User, id)
return user.as_dict()
You can create a user entry:
$ curl http://localhost:5000/users -H content-type:application/json \
-d '{"username": "alice", "email": "alice#example.com"}'
{
"email": "alice#example.com",
"id": 1,
"username": "alice"
}
Get a list of users:
$ curl http://localhost:5000/users
[
{
"email": "alice#example.com",
"id": 1,
"username": "alice"
}
]
Get details on a single user:
$ curl http://localhost:5000/user/1
{
"email": "alice#example.com",
"id": 1,
"username": "alice"
}
Etc.

Flask-SQLAlchemy not able to connect to remote mysql server: AttributeError: 'NoneType' object has no attribute 'drivername'

So I'm at the stage where I'm trying to learn how to deploy a flask app and I can't get it to connect to my remote server and I'm getting this error
File "C:\saiscripts\intercept_branch\Payment Web App Project\paymentWebApp\wsgi.py", line 11, in <module>
app = start()
File "C:\saiscripts\intercept_branch\Payment Web App Project\paymentWebApp\wsgi.py", line 5, in start
app = create_app()
File "C:\saiscripts\intercept_branch\Payment Web App Project\paymentWebApp\website\__init__.py", line 31, in create_app
db.create_all()
File "C:\Users\saiha\AppData\Local\Programs\Python\Python310\lib\site-packages\flask_sqlalchemy\__init__.py", line 1094, in create_all
self._execute_for_all_tables(app, bind, 'create_all')
File "C:\Users\saiha\AppData\Local\Programs\Python\Python310\lib\site-packages\flask_sqlalchemy\__init__.py", line 1086, in _execute_for_all_tables
op(bind=self.get_engine(app, bind), **extra)
File "C:\Users\saiha\AppData\Local\Programs\Python\Python310\lib\site-packages\flask_sqlalchemy\__init__.py", line 1017, in get_engine
return connector.get_engine()
File "C:\Users\saiha\AppData\Local\Programs\Python\Python310\lib\site-packages\flask_sqlalchemy\__init__.py", line 593, in get_engine
sa_url, options = self.get_options(sa_url, echo)
File "C:\Users\saiha\AppData\Local\Programs\Python\Python310\lib\site-packages\flask_sqlalchemy\__init__.py", line 608, in get_options
sa_url, options = self._sa.apply_driver_hacks(self._app, sa_url, options)
File "C:\Users\saiha\AppData\Local\Programs\Python\Python310\lib\site-packages\flask_sqlalchemy\__init__.py", line 933, in apply_driver_hacks
if sa_url.drivername.startswith('mysql'):
AttributeError: 'NoneType' object has no attribute 'drivername'
I tried connecting through mysql connector which actually works
db = mysql.connector.connect(
host="172.***.*.***",
user="sai",
passwd="**********"
)
I've checked the privileges
mysql> GRANT ALL PRIVILEGES ON *.* TO 'sai'#'%';
I've checked the sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf files
bind-address = 0.0.0.0
So then I thought it would be the way my config is setup even though when I had it as a localhost server it worked fine but I can't figure out the issue
/paymentWebApp/wsgi.py
from website import create_app, db
from website.extensions_inits import load_preset_data
def start():
app = create_app()
app.app_context().push()
db.create_all()
load_preset_data(app, db)
return app
app = start()
if __name__=='__main__':
app.run(host='0.0.0.0')
/paymentWebApp/website/_init_.py
db = SQLAlchemy()
migrate = Migrate()
DB_NAME = "main"
def create_app():
#Flask Instance
app = Flask(__name__)
#app.config.from_pyfile('config.py')
app.config.from_object(config.ProdConfig)
...
/paymentWebApp/website/config.py
class Config:
"""Base config."""
#SESSION_COOKIE_NAME = environ.get('SESSION_COOKIE_NAME')
MAX_CONTENT_LENGTH = 16*1000*1000
RECEIPT_FOLDER = '..\\assets\\receipts'
UPLOAD_EXTENSIONS = ['.jpg', '.png', '.pdf']
STATIC_FOLDER = 'static'
TEMPLATES_FOLDER = 'templates'
class ProdConfig(Config):
basedir = path.abspath(path.dirname(__file__))
load_dotenv('/home/sai/.env')
env_dict = dict(environ)
FLASK_ENV = 'production'
DEBUG = False
TESTING = False
SQLALCHEMY_DATABASE_URI = environ.get('PROD_DATABASE_URI')
SECRET_KEY = environ.get('SECRET_KEY')

How to make a value in a database a universal variable which can be called

I am trying to make a chat app which is linked with a database which stores the users username and password but i would like to call the username in multiple functions. I currently have a global variable which is called NAME_KEY and i would like to replace it with the username of which ever user is logged in.
Here is my code as it currently stands!
from flask import render_template, redirect, session, request, url_for, jsonify, flash, Blueprint
from .database import DataBase
from flask_mysqldb import MySQL
from flask_socketio import SocketIO
import bcrypt
import MySQLdb
from config import *
view = Blueprint("views", __name__)
# GLOBAL CONSTANTS
NAME_KEY = 'username'
MSG_LIMIT = 20
socketio = SocketIO(app) # used for user communication
db = MySQL(app)
password = b"1234"
hashed = bcrypt.hashpw(password, bcrypt.gensalt())
# VIEWS
#view.route("/login", methods=["POST", "GET"])
def login():
"""
displays main login page and handles saving name in session
:exception POST
:return: None
"""
if request.method == 'POST':
if 'username' in request.form and 'password' in request.form:
username = request.form.get('username')
password = request.form.get('password').encode("utf-8")
cursor = db.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT * FROM logininfo WHERE email=%s AND password=%s", (username, password))
info = cursor.fetchone()
if info is not None:
if bcrypt.checkpw(password, hashed):
session['loginsuccess'] = True
flash(f'You were successfully logged in as {username}.')
return redirect(url_for('views.home'))
else:
flash("Profile doesn't exist please try again!")
return render_template("login.html", **{"session": session})
#view.route('/new/', methods=['GET', 'POST'])
def new_user():
if request.method == "POST":
if "one" in request.form and "two" in request.form and "three" in request.form:
username = request.form['one']
email = request.form['two']
password = request.form['three']
cur = db.connection.cursor(MySQLdb.cursors.DictCursor)
cur.execute("INSERT INTO login.logininfo(name, password, email)VALUES(%s, %s, %s)",
(username, password, email))
db.connection.commit()
return redirect(url_for('login'))
return render_template("register.html")
#view.route("/logout")
def logout():
"""
logs the user out by popping username from session
:return: None
"""
session.pop(NAME_KEY, None)
flash("0You were logged out.")
return redirect(url_for("views.login"))
#view.route("/")
#view.route("/home")
def home():
"""
displays home page if logged in
:return: None
"""
if NAME_KEY not in session:
return redirect(url_for("views.login"))
return render_template("index.html", **{"session": session})
#view.route("/history")
def history():
if NAME_KEY not in session:
flash("0Please login before viewing message history")
return redirect(url_for("views.login"))
json_messages = get_history(session[NAME_KEY])
print(json_messages)
return render_template("history.html", **{"history": json_messages})
#view.route("/get_name")
def get_name():
"""
:return: a json object storing name of logged in user
"""
data = {"name": ""}
if NAME_KEY in session:
data = {"name": session[NAME_KEY]}
return jsonify(data)
#view.route("/get_messages")
def get_messages():
"""
:return: all messages stored in database
"""
db = DataBase()
msgs = db.get_all_messages(MSG_LIMIT)
messages = remove_seconds_from_messages(msgs)
return jsonify(messages)
#view.route("/get_history")
def get_history(name):
"""
:param name: str
:return: all messages by name of user
"""
db = DataBase()
msgs = db.get_messages_by_name(name)
messages = remove_seconds_from_messages(msgs)
return messages
Currently this line of code is throwing an error
'cursor = db.connection.cursor(MySQLdb.cursors.DictCursor)'
The error is as follows
"KeyError: 'MYSQL_HOST'"
I also have no idea how to go about replacing the global variable NAME_KEY with one that takes which ever user is signed up and stored in my database.
I also have a config file which is as follows
from dotenv import load_dotenv
from pathlib import Path # python3 only
import os
from flask import Flask
# set path to env file
env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path)
app = Flask(__name__)
class Config:
"""Set Flask configuration vars from .env file."""
# Load in environment variables
TESTING = os.getenv('TESTING')
FLASK_DEBUG = os.getenv('FLASK_DEBUG')
SECRET_KEY = os.getenv('SECRET_KEY')
SERVER = os.getenv('SERVER')
app.config["MYSQL_HOST"] = "login#localhost"
app.config["MYSQL_USER"] = "root"
app.config["MYSQL_PASSWORD"] = "pleasehelp"
app.config["MYSQL_DB"] = "login"
Any help or suggestions would be greatly appreciated.
Here are my errors
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\flask_socketio\__init__.py", line 46, in __call__
start_response)
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\engineio\middleware.py", line 71, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\User\PycharmProjects\testApp\testApp\application\views.py", line 40, in login
cursor = db.connection.cursor(MySQLdb.cursors.DictCursor)
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\flask_mysqldb\__init__.py", line 94, in connection
ctx.mysql_db = self.connect
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\flask_mysqldb\__init__.py", line 43, in connect
if current_app.config['MYSQL_HOST']:
KeyError: 'MYSQL_HOST'

Flask in memory database test fails with No application found. Either work inside a view function or push'

I have written my unitest in flask like (with in memory database);
import unittest
import json
from lobdcapi import app
from dal.dbContext import db
from models.AtgSiteToPoll import *
class TestAtgSiteToPollEP(unittest.TestCase):
def setUp(self):
app.testing = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
self.app = app.test_client()
with app.app_context():
db.init_app(app)
db.drop_all()
db.create_all()
def tearDown(self):
pass
def test_atg_sitetopoll(self):
a = AtgSiteToPoll()
a.SiteId = 1
a.IPAddress = '10.10.10.10'
a.Port = 3000
a.Category = 1
a.UserId = 'test'
a.Password = 'test123'
a.ReceiveTimeoutInMilliSeconds = 60
db.session.add(a)
db.session.commit()
assert len(AtgSiteToPoll.query.all()) is 1
When running the test I get;
Traceback (most recent call last):
File "/Users/ratha/projects/test711/ATGWS/tests/TestAtgSitesToPollEP.py", line 31, in test_atg_sitetopoll
db.session.add(a)
File "/Users/ratha/projects/test711/ATGWS/venv/lib/python2.7/site-packages/sqlalchemy/orm/scoping.py", line 153, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "/Users/ratha/projects/test711/ATGWS/venv/lib/python2.7/site-packages/sqlalchemy/util/_collections.py", line 1001, in __call__
return self.registry.setdefault(key, self.createfunc())
File "/Users/ratha/projects/test711/ATGWS/venv/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 2939, in __call__
return self.class_(**local_kw)
File "/Users/ratha/projects/test711/ATGWS/venv/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py", line 141, in __init__
self.app = app = db.get_app()
File "/Users/ratha/projects/test711/ATGWS/venv/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py", line 912, in get_app
'No application found. Either work inside a view function or push'
RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.
What Im doing wrong here?

Can't load plugin: sqlalchemy.dialects:sqlite3

I'm learning to create API's using Python here. I've gotten everything ready and downloaded the database, however when I run my app I'm getting the following error:
Traceback (most recent call last):
File "app.py", line 7, in <module>
e = create_engine("sqlite3:///salaries.db")
File "C:\Python27\lib\site-packages\sqlalchemy\engine\__init__.py", line 387, in create_engine
return strategy.create(*args, **kwargs)
File "C:\Python27\lib\site-packages\sqlalchemy\engine\strategies.py", line 56, in create
entrypoint = u._get_entrypoint()
File "C:\Python27\lib\site-packages\sqlalchemy\engine\url.py", line 139, in _get_entrypoint
cls = registry.load(name)
File "C:\Python27\lib\site-packages\sqlalchemy\util\langhelpers.py", line 212, in load
(self.group, name))
sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:sqlite3
What am I doing wrong to where it will not load the correct plugin?
from flask import Flask, request
from flask_restful import Resource, Api
from sqlalchemy import create_engine
from json import dumps
e = create_engine("sqlite3:///salaries.db")
app = Flask(__name__)
api = Api(app)
class DepartmentsMeta(Resource):
def get(self):
conn = e.connect()
query = conn.execute("select distinct DEPARTMENT from salaries")
return {"departments": [i[0] for i in query.cursor.fetchall()]}
class DepartmentSalary(Resource):
def get(self, department_name):
conn = e.connect()
query = conn.execute("select * from salaries where Department='%s'" % department_name)
result = {"data": [dict(zip(tuple(query.keys()), i))] for i in query.cursor}
return result
api.add_resource(DepartmentSalary, "/dept/<string:department_name>")
api.add_resource(DepartmentsMeta, "/department")
if __name__ == "__main__":
app.run()
Please try replacing this line:
e = create_engine("sqlite3:///salaries.db")
with
e = create_engine("sqlite:///salaries.db")
I got the same problem. I've solved it by:
pip3 uninstall flask_sqlalchemy and pip3 install flask-sqlalchemy==2.5.1 because big changes with flask-sqlalchemy==3.0 SQLite DB in memory are not set as default in this version.
Hope it helps you.

Categories

Resources