KeyError: <weakref at 0x7fc9e8267ad0; to 'Flask' at 0x7fc9e9ec5750> - python

I've been having a hard time handling sessions in flask. Since when I manage the application in the local environment everything works perfectly, including flask sessions. But when i already host it in Render i always get this error in every route.
[55] [ERROR] Error handling request /valle-de-guadalupe
Traceback (most recent call last):
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask/app.py", line 2525, in wsgi_app
response = self.full_dispatch_request()
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask/app.py", line 1822, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask/app.py", line 1820, in full_dispatch_request
rv = self.dispatch_request()
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask/app.py", line 1796, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
File "/opt/render/project/src/app_folder/routes/public.py", line 35, in valle_de_guadalupe
return render_template("public/cities/valle_guadalupe.html")
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask/templating.py", line 147, in render_template
return _render(app, template, context)
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask/templating.py", line 128, in _render
app.update_template_context(context)
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask/app.py", line 994, in update_template_context
context.update(func())
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask_login/utils.py", line 407, in _user_context_processor
return dict(current_user=_get_user())
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask_login/utils.py", line 372, in _get_user
current_app.login_manager._load_user()
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask_login/login_manager.py", line 364, in _load_user
user = self._user_callback(user_id)
File "/opt/render/project/src/app.py", line 52, in load_user
return User.get_by_id(int(user_id))
File "/opt/render/project/src/app_folder/models/models.py", line 82, in get_by_id
return User.query.get(id)
File "<string>", line 2, in get
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/sqlalchemy/util/deprecations.py", line 402, in warned
return fn(*args, **kwargs)
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 947, in get
return self._get_impl(ident, loading.load_on_pk_identity)
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 959, in _get_impl
execution_options=self._execution_options,
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 2959, in _get_impl
load_options=load_options,
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/sqlalchemy/orm/loading.py", line 534, in load_on_pk_identity
bind_arguments=bind_arguments,
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 1702, in execute
bind = self.get_bind(**bind_arguments)
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask_sqlalchemy/session.py", line 61, in get_bind
engines = self._db.engines
File "/opt/render/project/src/.venv/lib/python3.7/site-packages/flask_sqlalchemy/extension.py", line 629, in engines
return self._app_engines[app]
File "/usr/local/lib/python3.7/weakref.py", line 396, in __getitem__
return self.data[ref(key)]
KeyError: <weakref at 0x7fc9e8267ad0; to 'Flask' at 0x7fc9e9ec5750>
index.py
from app import app
from app_folder.utils.db import db
db.init_app(app)
with app.app_context():
db.create_all()
if __name__ == "__main__":
app.run(
debug = False,
port = 5000
)
app.py
from flask import Flask
"""Flask SqlAlchemy"""
from flask_sqlalchemy import SQLAlchemy
"""Flask Login"""
from flask_login import LoginManager
"""Dot Env"""
from dotenv import load_dotenv
"""App Folder Routes"""
from app_folder.handlers.stripe_handlers import stripe_error
from app_folder.handlers.web_handlers import web_error
from app_folder.models.models import User
from app_folder.routes.admin import admin
from app_folder.routes.public import public
from app_folder.routes.users import users
from app_folder.utils.db import db
"""Imports"""
import os
import stripe
load_dotenv()
"""config app"""
app = Flask(__name__,
static_url_path="",
template_folder="app_folder/templates",
static_folder="app_folder/static")
app.config['SECRET_KEY'] = os.getenv("SECRET_KEY")
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv("SQLALCHEMY_DATABASE_VERSION")+os.getenv("SQLALCHEMY_USERNAME")+":"+os.getenv("SQLALCHEMY_PASSWORD")+"#"+os.getenv("SQLALCHEMY_SERVER")+"/"+os.getenv("SQLALCHEMY_DATABASE")
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = os.getenv("SQLALCHEMY_TRACK_MODIFICATIONS")
"""blueprints"""
app.register_blueprint(stripe_error)
app.register_blueprint(web_error)
app.register_blueprint(admin)
app.register_blueprint(public)
app.register_blueprint(users)
SQLAlchemy(app)
login_manager = LoginManager(app)
""" stripe """
stripe_keys = {
'secret_key': os.getenv("STRIPE_SECRET_KEY"),
'publishable_key': os.getenv("STRIPE_PUBLISHABLE_KEY")
}
stripe.api_key = stripe_keys['secret_key']
"""Login Manager"""
#login_manager.user_loader
def load_user(user_id):
return User.get_by_id(int(user_id))
"""Teardown"""
#app.teardown_appcontext
def shutdown_session(exception=None):
db.session.remove()
Regardless of which route i'm on, while handling sessions I get the same error, but in this case use this path.
public.py
"""routes"""
#public.route("/", methods=["GET", "POST"])
def index():
return redirect(url_for('public.valle_de_guadalupe'))
"""cities"""
#public.route("/valle-de-guadalupe", methods=["GET", "POST"])
def valle_de_guadalupe():
return render_template("public/cities/valle_guadalupe.html")
I don't know if this has happened to someone else.

It's usually best to remove as many extra components and identify a minimal example that produces the error, otherwise it's often hard to help.
That said, I think that error suggests that db (SQLAlachemy() from flask-sqlalchemy) is not being inited with app.
I'm not sure what the db is that is being imported from app_folder.utils.db, but it appears that you may need to call db.init_app(app).
Relatedly, the line SQLAlchemy(app) is not being assigned. Perhaps you meant to assign that to db?

Other people report that this issue happens since the upgrade from flask-sqlalchemy v2.5.1 to v3. So downgrading might be a work around (not a permanent solution)
Source

Related

GAE + Flask Contact Form

I'm trying to build a simple contact form with Flask and hosting it on GAE but I can't seem to get it right.
I'd truly appreciate your help because I've spent several days trying to figure this out without any success.
Here's the error I get when I click submit:
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.
And here are the logs:
2022-02-14 23:03:33 default[20220215t000150] Traceback (most recent call last):
File "/layers/google.python.pip/pip/lib/python3.9/site-packages/flask/app.py", line 2073, in wsgi_app response = self.full_dispatch_request()
File "/layers/google.python.pip/pip/lib/python3.9/site-packages/flask/app.py", line 1518, in full_dispatch_request rv = self.handle_user_exception(e)
File "/layers/google.python.pip/pip/lib/python3.9/site-packages/flask/app.py", line 1516, in full_dispatch_request rv = self.dispatch_request()
File "/layers/google.python.pip/pip/lib/python3.9/site-packages/flask/app.py", line 1502, in dispatch_request return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "/srv/main.py", line 34, in contact message.send() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/google/appengine/api/mail.py", line 1209, in send make_sync_call('mail', self._API_CALL, message, response)
File "/layers/google.python.pip/pip/lib/python3.9/site-packages/google/appengine/api/apiproxy_stub_map.py", line 96, in MakeSyncCall return stubmap.MakeSyncCall(service, call, request, response)
File "/layers/google.python.pip/pip/lib/python3.9/site-packages/google/appengine/api/apiproxy_stub_map.py", line 355, in MakeSyncCall rpc.CheckSuccess()
File "/layers/google.python.pip/pip/lib/python3.9/site-packages/google/appengine/api/apiproxy_rpc.py", line 149, in CheckSuccess raise self.exception
File "/layers/google.python.pip/pip/lib/python3.9/site-packages/google/appengine/runtime/default_api_stub.py", line 267, in _CaptureTrace f(**kwargs)
File "/layers/google.python.pip/pip/lib/python3.9/site-packages/google/appengine/runtime/default_api_stub.py", line 260, in _SendRequest raise self._TranslateToError(parsed_response) File "/layers/google.python.pip/pip/lib/python3.9/site-packages/google/appengine/runtime/default_api_stub.py", line 134, in _TranslateToError raise self._ErrorException(exception_type, msg) google.appengine.runtime.apiproxy_errors.FeatureNotEnabledError: The API call mail.Send() is currently not enabled. -- Additional details from server: App Engine APIs are not enabled, please add app_engine_apis: true to your app.yaml to enable.
Here's my main.py:
from flask import Flask, redirect, render_template, url_for
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
from flask_talisman import Talisman
from google.appengine.api import mail, wrap_wsgi_app
app = Flask(__name__)
app.config['SECRET_KEY'] = 'my-very-very-secret-key'
app.wsgi_app = wrap_wsgi_app(app.wsgi_app)
Talisman(app)
EMAIL_ADDR = 'my_email#example.com'
class ContactForm(FlaskForm):
name = StringField(label='Name', validators=[DataRequired()])
submit = SubmitField(label='Submit')
#app.route('/')
def homepage():
return render_template('index.html')
#app.route('/contact', methods=['GET', 'POST'])
def contact():
form = ContactForm()
if form.validate_on_submit():
name = form.name.data
message = mail.EmailMessage(sender=EMAIL_ADDR,
subject='form test')
message.body = f'this is a test message from {name}'
message.to = EMAIL_ADDR
message.send()
return redirect(url_for('homepage'))
return render_template('contact.html', form=form)
if __name__ == '__main__':
app.run()
My app.yaml
runtime: python39
app_engine_apis: true
inbound_services:
- mail
- mail_bounce
My requirements.txt
Flask==2.0.2
flask-talisman==0.8.1
wtforms==3.0.0
Flask-WTF==1.0.0
appengine-python-standard>=0.3.1
I've stumbled upon the solution! If anyone else runs into this issue: 'gcloud beta app deploy' solves it. I used to deploy the app with 'gcloud app deploy' before.

python - blueprint declaration run with exceptions as I navigate it from a browser

I am using python 3.9.6 with ninja2 and blueprint.
py --version
returns:
Python 3.9.6
As far as I know, blueprint is a seperate folder, with seperate html templates and static files (css/js) , and I can have many blueprints in one runnable python project.
I have looked at Views with Jinja2 and blueprint
The hierarchy of the html+relevant files of myblueprint is:
main_project -> myblueprint -> templates -> myblueprint.html
-> static -> myblueprint.css
-> myblueprint.js
The relevant code:
import os
from flask import Flask, Blueprint, redirect, request, render_template, url_for, session
main_page = Blueprint('myblueprint', __name__)
#main_page.route("/myblueprint")
def home():
query = 'select * from users;'
users = interact_db(query=query, query_type='fetch')
return render_template('myblueprint.html')
...
#app.route('/', methods=['GET'])
def main():
return redirect("myblueprint")
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.secret_key = '12345'
app.run(host='0.0.0.0', port=port)
For some reason, when I run: https://localhost:5000, I get an error:
ERROR in app: Exception on /myblueprint [GET] Traceback (most recent
call last): File
"C:\Users\myusername\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py",
line 2073, in wsgi_app
response = self.full_dispatch_request() File "C:\Users\myusername\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py",
line 1518, in full_dispatch_request
rv = self.handle_user_exception(e) File "C:\Users\myusername\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py",
line 1516, in full_dispatch_request
rv = self.dispatch_request() File "C:\Users\myusername\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py",
line 1502, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "C:/main_project/myproject/app.py", line 17, in home
return render_template('myblueprint.html') File "C:\Users\myusername\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\templating.py",
line 148, in render_template
ctx.app.jinja_env.get_or_select_template(template_name_or_list), File
"C:\Users\myusername\AppData\Local\Programs\Python\Python36-32\lib\site-packages\jinja2\environment.py",
line 1068, in get_or_select_template
return self.get_template(template_name_or_list, parent, globals) File
"C:\Users\myusername\AppData\Local\Programs\Python\Python36-32\lib\site-packages\jinja2\environment.py",
line 997, in get_template
return self._load_template(name, globals) File "C:\Users\myusername\AppData\Local\Programs\Python\Python36-32\lib\site-packages\jinja2\environment.py",
line 958, in _load_template
template = self.loader.load(self, name, self.make_globals(globals)) File
"C:\Users\myusername\AppData\Local\Programs\Python\Python36-32\lib\site-packages\jinja2\loaders.py",
line 125, in load
source, filename, uptodate = self.get_source(environment, name) File
"C:\Users\myusername\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\templating.py",
line 59, in get_source
return self._get_source_fast(environment, template) File "C:\Users\myusername\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\templating.py",
line 95, in _get_source_fast
raise TemplateNotFound(template) jinja2.exceptions.TemplateNotFound: myblueprint.html
127.0.0.1 - - [04/Jan/2022 08:04:31] "GET /myblueprint HTTP/1.1" 500 -
127.0.0.1 - - [04/Jan/2022 08:04:31] "GET /favicon.ico HTTP/1.1" 404 -
I have also noticed that on the chrome network console (not in code run window), I see another exception:
Request URL: http://localhost:5000/
Request Method: GET
Status Code: 500 INTERNAL SERVER ERROR
Remote Address: 127.0.0.1:5000
Referrer Policy: strict-origin-when-cross-origin
What is the cross origin for blueprint, and how can I avoid that?
What is wrong in my code above, and should I fix the heirarchy?
Two problems in your code. First you have to register your blueprint
import os
from flask import Flask, Blueprint, redirect, request, render_template, url_for, session
app = Flask(__name__)
main_page = Blueprint('myblueprint', __name__)
#main_page.route('/myblueprint', methods=['GET'])
def home():
query = 'select * from users;'
users = interact_db(query=query, query_type='fetch')
return render_template('myblueprint.html')
#app.route('/', methods=['GET'])
def main():
return redirect("myblueprint")
app.register_blueprint(main_page)
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5800))
app.secret_key = '12345'
app.run(host='0.0.0.0', port=port)
Then your html file must simply be in the templates folder:
> templates > myblueprint.html

Flask SQLAlchemy KeyError 'False' in create_engine

I have a flask app that connects with mysql using sqlalchemy. A strange error happens on DB query.
`Traceback (most recent call last):
File "/home/Desktop/work/nesting-app/env/lib/python3.8/site-packages/sqlalchemy/util/_collections.py", line 1008, in call
return self.registry[key]
KeyError: <greenlet.greenlet object at 0x7f22a0936a90 (otid=0x7f22a08ef100) current active started main>
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File
"/home/Desktop/work/nesting-app/server/users/routes.py", line
28, in register_new_user
if form.validate_on_submit(): File "/home/Desktop/work/nesting-app/env/lib/python3.8/site-packages/flask_wtf/form.py",
line 100, in validate_on_submit
return self.is_submitted() and self.validate() File "/home/Desktop/work/nesting-app/env/lib/python3.8/site-packages/wtforms/form.py",
line 318, in validate
return super(Form, self).validate(extra) File "/home/Desktop/work/nesting-app/env/lib/python3.8/site-packages/wtforms/form.py",
line 150, in validate
if not field.validate(self, extra): File "/home/Desktop/work/nesting-app/env/lib/python3.8/site-packages/wtforms/fields/core.py",
line 226, in validate
stop_validation = self._run_validation_chain(form, chain) File "/home/Desktop/work/nesting-app/env/lib/python3.8/site-packages/wtforms/fields/core.py",
line 246, in _run_validation_chain
validator(form, self) File "/home/Desktop/work/nesting-app/server/users/forms.py", line
43, in validate_email
user = User.query.filter_by(email=email.data).first() File "/home/Desktop/work/nesting-app/env/lib/python3.8/site-packages/flask_sqlalchemy/init.py",
line 552, in get
return type.query_class(mapper, session=self.sa.session()) File "/home/Desktop/work/nesting-app/env/lib/python3.8/site-packages/sqlalchemy/orm/scoping.py",
line 47, in call
sess = self.registry() File "/home/Desktop/work/nesting-app/env/lib/python3.8/site-packages/sqlalchemy/util/collections.py", line 1010, in call
return self.registry.setdefault(key, self.createfunc()) File "/home/Desktop/work/nesting-app/env/lib/python3.8/site-packages/sqlalchemy/orm/session.py",
line 4171, in call
return self.class(**local_kw) File "/home/Desktop/work/nesting-app/env/lib/python3.8/site-packages/flask_sqlalchemy/init.py",
line 176, in init
bind = options.pop('bind', None) or db.engine File "/home/Desktop/work/nesting-app/env/lib/python3.8/site-packages/flask_sqlalchemy/init.py",
line 998, in engine
return self.get_engine() File "/home/Desktop/work/nesting-app/env/lib/python3.8/site-packages/flask_sqlalchemy/init.py",
line 1017, in get_engine
return connector.get_engine() File "/home/Desktop/work/nesting-app/env/lib/python3.8/site-packages/flask_sqlalchemy/init.py",
line 594, in get_engine
self._engine = rv = self._sa.create_engine(sa_url, options) File "/home/Desktop/work/nesting-app/env/lib/python3.8/site-packages/flask_sqlalchemy/init.py",
line 1027, in create_engine
return sqlalchemy.create_engine(sa_url, **engine_opts) File "", line 2, in create_engine File
"/home/Desktop/work/nesting-app/env/lib/python3.8/site-packages/sqlalchemy/util/deprecations.py", line 298, in warned
return fn(*args, **kwargs) File "/home/Desktop/work/nesting-app/env/lib/python3.8/site-packages/sqlalchemy/engine/create.py",
line 661, in create_engine
engine = engineclass(pool, dialect, u, **engine_args) File "/home/Desktop/work/nesting-app/env/lib/python3.8/site-packages/sqlalchemy/engine/base.py",
line 2758, in init
self.echo = echo File "/home/Desktop/work/nesting-app/env/lib/python3.8/site-packages/sqlalchemy/log.py",
line 225, in set
instance_logger(instance, echoflag=value) File "/home/Desktop/work/nesting-app/env/lib/python3.8/site-packages/sqlalchemy/log.py",
line 202, in instance_logger
logger = InstanceLogger(echoflag, name) File "/home/Desktop/work/nesting-app/env/lib/python3.8/site-packages/sqlalchemy/log.py",
line 103, in init
if self._echo_map[echo] <= logging.INFO and not self.logger.handlers: KeyError: 'False' `
Here is the config.py
from os import environ, path
from dotenv import load_dotenv
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
load_dotenv(path.join(BASE_DIR, '.env'))
class Config:
SECRET_KEY = environ.get('SECRET_KEY')
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://user:password#127.0.0.1:3306/dbname'
# SQLALCHEMY_ECHO: When set to 'True', Flask-SQLAlchemy will log all database
# activity to Python's stderr for debugging purposes.
SQLALCHEMY_ECHO = environ.get('SQLALCHEMY_ECHO')
# To suppress the warning "this option takes a lot of system resources" set
SQLALCHEMY_TRACK_MODIFICATIONS = environ.get('SQLALCHEMY_TRACK_MODIFICATIONS')
Here is the init.py
db = SQLAlchemy()
bcrypt = Bcrypt()
login_manager = LoginManager()
login_manager.login_view = 'users.login'
mail = Mail()
csrf = CSRFProtect()
def create_app(config_class=Config):
flask_app = Flask(__name__)
flask_app.config.from_object(config_class)
db.init_app(flask_app)
bcrypt.init_app(flask_app)
login_manager.init_app(flask_app)
mail.init_app(flask_app)
csrf.init_app(flask_app)
I have tried with different connection strings:
SQLALCHEMY_DATABASE_URI=mysql+mysqlconnector://user:pass#localhost:3306/dbname
SQLALCHEMY_DATABASE_URI=mysql+mysqlconnector://user:pass#localhost/dbname
SQLALCHEMY_DATABASE_URI=mysql+mysqlconnector://user:pass#127.0.0.1:3306/dbname
Thank you for any help.
The echo flag for SQLAlchemy's create_engine function accepts a limited set of values: None, False, True, "debug" (source).
The traceback shows that the string "False" is being passed: KeyError: 'False'. In fact, the error can be reproduced by passing any string (except "debug") as the value of create_engine's echo flag:
create_engine('sqlite://', echo='banana')
results in
Traceback (most recent call last):
...
KeyError: 'banana'
At a guess, the problem is that
SQLALCHEMY_ECHO = environ.get('SQLALCHEMY_ECHO')
does not consider that environment variables are always strings. Something like this might be better:
SQLALCHEMY_ECHO = environ.get('SQLALCHEMY_ECHO') in ('1', 'True')
as it will result in a boolean value being assigned.

I get the error in my api maybe about pymysql.connect but I don't know what happened

I am making my api about output data from mysql. And I follow this link to do this but I get the Type Error. https://flask.palletsprojects.com/en/2.0.x/config/ I don't know what wrong in my code. And I try to fix this. I follow this link How do I save database configuration without writting them on my python file but still not work.
# -*- coding: utf-8 -*-
from flask import Flask, g, render_template, request, jsonify, json, current_app
import pymysql
import pymysql.cursors
from flask_sqlalchemy import SQLAlchemy
import flask
from global_setup import *
app = Flask(__name__)
def connect_db():
return pymysql.connect(MY_DB_SERVER,
MY_DB_USER,
MY_DB_PASS,
MY_DB_DB,
MY_DB_PORT,
charset='utf8',
cursorclass=pymysql.cursors.DictCursor)
def get_db():
'''Opens a new database connection per request.'''
if not hasattr(g, 'db'):
g.db = connect_db()
return g.db
#app.teardown_appcontext
def close_db(error):
'''Closes the database connection at the end of request.'''
if hasattr(g, 'db'):
g.db.close()
#app.route('/api/CRM',methods = ['POST'])
def index1():
cursor = get_db().cursor()
cursor.execute("select * from customer")
rows = cursor.fetchall()
return jsonify(rows)
if __name__ == '__main__':
app.config['JSON_AS_ASCII'] = False
app.run(debug=True, host='0.0.0.0', port=5000)
The error:
127.0.0.1 - - [21/Jun/2021 18:40:29] "POST /api/CRM HTTP/1.1" 500 -
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 2088, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 2073, in wsgi_app
response = self.handle_exception(e)
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 2070, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1515, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1513, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1499, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "/home/Teemo.Tsui/git/KF/api_123.py", line 34, in index1
cursor = get_db().cursor()
File "/home/Teemo.Tsui/git/KF/api_123.py", line 23, in get_db
g.db = connect_db()
File "/home/Teemo.Tsui/git/KF/api_123.py", line 18, in connect_db
cursorclass=pymysql.cursors.DictCursor)
TypeError: __init__() takes 1 positional argument but 6 positional arguments (and 2 keyword-only arguments) were given
This is my global_setup.py
MY_DB_SERVER = ""
MY_DB_USER = ""
MY_DB_PASS = ""
MY_DB_DB = ""
MY_DB_PORT = 3306
It looks like the pymysql.connect args need to be named, so:
def connect_db():
return pymysql.connect(host=MY_DB_SERVER,
user=MY_DB_USER,
password=MY_DB_PASS,
database=MY_DB_DB,
port=MY_DB_PORT,
charset='utf8',
cursorclass=pymysql.cursors.DictCursor)

Flask_SQLAlchemy create_all() doesn't work

I started learning how to use SQLAlchemy for my code but for some reason when I ran the code it raised this exception:
Traceback (most recent call last):
File "C:/Users/smadar.KLAG/PycharmProjects/keylogger/site/practice.py", line 118, in <module>
db.create_all()
File "C:\Users\c\projects\test\venv\lib\site-packages\flask_sqlalchemy\__init__.py", line 1039, in create_all
self._execute_for_all_tables(app, bind, 'create_all')
File "C:\Users\c\projects\test\venv\lib\site-packages\flask_sqlalchemy\__init__.py", line 1031, in _execute_for_all_tables
op(bind=self.get_engine(app, bind), **extra)
File "C:\Users\c\projects\test\venv\lib\site-packages\flask_sqlalchemy\__init__.py", line 962, in get_engine
return connector.get_engine()
File "C:\Users\c\projects\test\venv\lib\site-packages\flask_sqlalchemy\__init__.py", line 555, in get_engine
options = self.get_options(sa_url, echo)
File "C:\Users\c\projects\test\venv\lib\site-packages\flask_sqlalchemy\__init__.py", line 570, in get_options
self._sa.apply_driver_hacks(self._app, sa_url, options)
File "C:\Users\c\projects\test\venv\lib\site-packages\flask_sqlalchemy\__init__.py", line 914, in apply_driver_hacks
sa_url.database = os.path.join(app.root_path, sa_url.database)
AttributeError: can't set attribute
This is the code:
from flask import Flask, redirect, url_for, render_template, request, session, flash
from time import sleep
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.sqlite3'
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
class Users(db.Model):
_id = db.Column("id", db.Integer, primary_key=True)
email = db.Column(db.String(100))
password = db.Column(db.String(100))
if __name__ == '__main__':
db.create_all()
app.run(debug=True)
I tried running the code of a friend of mine that has SQLAlchemy (the code does work for him) incase it was a coding issue but I have reached the same error with his code as well.
Is there something I am doing incorrectly?
I just ran into this too. Looks like SQLAlchemy just released version 1.4, which breaks flask_sqlalchemy.
I was able to resolve the issue on my system by installing the previous (1.3) version instead.
EDIT: the latest version of SQLAlchemy works now (version 1.4 as of writing this)
installing SQLAlchemy 1.3.23 worked for me.
pip install SQLAlchemy==1.3.23

Categories

Resources