flask-security with SQLALCHEMY_BINDS loses connections from pool for static files - flask-login

flask-security with SQLALCHEMY_BINDS loses connections from pool for static files -- at least I think what is happening.
First comment under Caching Flask-Login user_loader suggests using flask-principal's skip_static=True, but I don't see that that flask-principal parameter is accessible when using flask-security.
Using
Flask-Login==0.5.0
Flask-Mail==0.9.1
flask-nav==0.6
Flask-Principal==0.4.0
Flask-Security-Too==3.3.3
Flask-SQLAlchemy==2.4.1
Flask-WTF==0.14.3
SQLAlchemy==1.3.13
I initialize the SQLALCHEMY variables as below
class RealDb(Config):
def __init__(self, configfiles):
if type(configfiles) == str:
configfiles = [configfiles]
# connect to database based on configuration
config = {}
for configfile in configfiles:
config.update(getitems(configfile, 'database'))
dbuser = config['dbuser']
password = config['dbpassword']
dbserver = config['dbserver']
dbname = config['dbname']
# app.logger.debug('using mysql://{uname}:*******#{server}/{dbname}'.format(uname=dbuser,server=dbserver,dbname=dbname))
db_uri = 'mysql://{uname}:{pw}#{server}/{dbname}'.format(uname=dbuser, pw=password, server=dbserver,
dbname=dbname)
self.SQLALCHEMY_DATABASE_URI = db_uri
# https://flask-sqlalchemy.palletsprojects.com/en/2.x/binds/
userdbuser = config['userdbuser']
userpassword = config['userdbpassword']
userdbserver = config['userdbserver']
userdbname = config['userdbname']
userdb_uri = 'mysql://{uname}:{pw}#{server}/{dbname}'.format(uname=userdbuser, pw=userpassword, server=userdbserver,
dbname=userdbname)
self.SQLALCHEMY_BINDS = {
'users': userdb_uri
}
My users model (the main model is empty at this point)
# pypi
from flask_sqlalchemy import SQLAlchemy
from flask_security import UserMixin, RoleMixin
# set up database - SQLAlchemy() must be done after app.config SQLALCHEMY_* assignments
db = SQLAlchemy()
Table = db.Table
Column = db.Column
Integer = db.Integer
Float = db.Float
Boolean = db.Boolean
String = db.String
Text = db.Text
Date = db.Date
Time = db.Time
DateTime = db.DateTime
Sequence = db.Sequence
Enum = db.Enum
UniqueConstraint = db.UniqueConstraint
ForeignKey = db.ForeignKey
relationship = db.relationship
backref = db.backref
object_mapper = db.object_mapper
Base = db.Model
# some string sizes
DESCR_LEN = 512
INTEREST_LEN = 32
APPLICATION_LEN = 32
# role management, some of these are overloaded
USERROLEDESCR_LEN = 512
ROLENAME_LEN = 32
EMAIL_LEN = 100
NAME_LEN = 256
PASSWORD_LEN = 255
UNIQUIFIER_LEN = 255
# common roles
ROLE_SUPER_ADMIN = 'super-admin'
userinterest_table = Table('users_interests', Base.metadata,
Column('user_id', Integer, ForeignKey('user.id')),
Column('interest_id', Integer, ForeignKey('interest.id')),
info={'bind_key': 'users'},
)
appinterest_table = Table('apps_interests', Base.metadata,
Column('application_id', Integer, ForeignKey('application.id')),
Column('interest_id', Integer, ForeignKey('interest.id')),
info={'bind_key': 'users'},
)
class Interest(Base):
__tablename__ = 'interest'
__bind_key__ = 'users'
id = Column(Integer(), primary_key=True)
version_id = Column(Integer, nullable=False, default=1)
interest = Column(String(INTEREST_LEN))
users = relationship("User",
secondary=userinterest_table,
backref=backref("interests"))
applications = relationship("Application",
secondary=appinterest_table,
backref=backref("interests"))
description = Column(String(DESCR_LEN))
public = Column(Boolean)
class Application(Base):
__tablename__ = 'application'
__bind_key__ = 'users'
id = Column(Integer(), primary_key=True)
application = Column(String(APPLICATION_LEN))
# user role management
# adapted from
# https://flask-security-too.readthedocs.io/en/stable/quickstart.html (SQLAlchemy Application)
class RolesUsers(Base):
__tablename__ = 'roles_users'
__bind_key__ = 'users'
id = Column(Integer(), primary_key=True)
user_id = Column('user_id', Integer(), ForeignKey('user.id'))
role_id = Column('role_id', Integer(), ForeignKey('role.id'))
class Role(Base, RoleMixin):
__tablename__ = 'role'
__bind_key__ = 'users'
id = Column(Integer(), primary_key=True)
version_id = Column(Integer, nullable=False, default=1)
name = Column(String(ROLENAME_LEN), unique=True)
description = Column(String(USERROLEDESCR_LEN))
class User(Base, UserMixin):
__tablename__ = 'user'
__bind_key__ = 'users'
id = Column(Integer, primary_key=True)
version_id = Column(Integer, nullable=False, default=1)
email = Column( String(EMAIL_LEN), unique=True ) # = username
password = Column( String(PASSWORD_LEN) )
name = Column( String(NAME_LEN) )
given_name = Column( String(NAME_LEN) )
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 )
active = Column( Boolean() )
fs_uniquifier = Column( String(UNIQUIFIER_LEN) )
confirmed_at = Column( DateTime() )
roles = relationship('Role', secondary='roles_users',
backref=backref('users', lazy='dynamic'))
Logging connection pool:
logging.basicConfig()
logging.getLogger('sqlalchemy.pool').setLevel(logging.DEBUG)
Using the above I see connections not released for static files which eventually causes sqlalchemy.exc.TimeoutError: QueuePool limit of size 10 overflow 10 reached, connection timed out, timeout 30 (Background on this error at: http://sqlalche.me/e/3o7r). (I believe the db.session.commit() within /admin/users causes that connection to be returned).
DEBUG:sqlalchemy.pool.impl.QueuePool:Created new connection <_mysql.connection open to '127.0.0.1' at 0000020389174368>
DEBUG:sqlalchemy.pool.impl.QueuePool:Connection <_mysql.connection open to '127.0.0.1' at 0000020389174368> checked out from pool
127.0.0.1 - - [10/Mar/2020 15:10:03] "GET /static/js/jquery-ui-1.12.1.custom/images/ui-bg_glass_50_3baae3_1x400.png HTTP/1.1" 200 -
INFO:werkzeug:127.0.0.1 - - [10/Mar/2020 15:10:03] "GET /static/js/jquery-ui-1.12.1.custom/images/ui-bg_glass_50_3baae3_1x400.png HTTP/1.1" 200 -
DEBUG:sqlalchemy.pool.impl.QueuePool:Created new connection <_mysql.connection open to '127.0.0.1' at 00000203891761C8>
DEBUG:sqlalchemy.pool.impl.QueuePool:Connection <_mysql.connection open to '127.0.0.1' at 00000203891761C8> checked out from pool
request.path = /admin/users
DEBUG:sqlalchemy.pool.impl.QueuePool:Connection <_mysql.connection open to '127.0.0.1' at 00000203891761C8> being returned to pool
DEBUG:sqlalchemy.pool.impl.QueuePool:Connection <_mysql.connection open to '127.0.0.1' at 00000203891761C8> rollback-on-return
DEBUG:sqlalchemy.pool.impl.QueuePool:Connection <_mysql.connection open to '127.0.0.1' at 00000203891761C8> checked out from pool
[2020-03-10 15:10:05,773] DEBUG in tables: rendertemplate(): self.templateargs = {}
DEBUG:members:rendertemplate(): self.templateargs = {}
127.0.0.1 - - [10/Mar/2020 15:10:05] "GET /admin/users HTTP/1.1" 200 -
INFO:werkzeug:127.0.0.1 - - [10/Mar/2020 15:10:05] "GET /admin/users HTTP/1.1" 200 -
DEBUG:sqlalchemy.pool.impl.QueuePool:Created new connection <_mysql.connection open to '127.0.0.1' at 0000020389175298>
DEBUG:sqlalchemy.pool.impl.QueuePool:Connection <_mysql.connection open to '127.0.0.1' at 0000020389175298> checked out from pool
127.0.0.1 - - [10/Mar/2020 15:10:06] "GET /static/js/jquery-ui-1.12.1.custom/jquery-ui.css HTTP/1.1" 200 -
INFO:werkzeug:127.0.0.1 - - [10/Mar/2020 15:10:06] "GET /static/js/jquery-ui-1.12.1.custom/jquery-ui.css HTTP/1.1" 200 -
DEBUG:sqlalchemy.pool.impl.QueuePool:Created new connection <_mysql.connection open to '127.0.0.1' at 00000203891770F8>
:
Traceback (most recent call last):
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\flask\app.py", line 2463, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\flask\app.py", line 2449, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\flask\app.py", line 1866, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\flask\app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\flask\app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\flask\app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\flask\app.py", line 1947, in full_dispatch_request
rv = self.preprocess_request()
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\flask\app.py", line 2241, in preprocess_request
rv = func()
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\flask_principal.py", line 477, in _on_before_request
identity = loader()
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\flask_security\core.py", line 405, in _identity_loader
if not isinstance(current_user._get_current_object(), AnonymousUserMixin):
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\werkzeug\local.py", line 306, in _get_current_object
return self.__local()
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\flask_login\utils.py", line 26, in <lambda>
current_user = LocalProxy(lambda: _get_user())
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\flask_login\utils.py", line 346, in _get_user
current_app.login_manager._load_user()
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\flask_login\login_manager.py", line 318, in _load_user
user = self._user_callback(user_id)
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\flask_security\core.py", line 345, in _user_loader
user = _security.datastore.find_user(id=user_id)
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\flask_security\datastore.py", line 382, in find_user
return query.filter_by(**kwargs).first()
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\sqlalchemy\orm\query.py", line 3287, in first
ret = list(self[0:1])
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\sqlalchemy\orm\query.py", line 3065, in __getitem__
return list(res)
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\sqlalchemy\orm\query.py", line 3389, in __iter__
return self._execute_and_instances(context)
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\sqlalchemy\orm\query.py", line 3411, in _execute_and_instances
querycontext, self._connection_from_session, close_with_result=True
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\sqlalchemy\orm\query.py", line 3426, in _get_bind_args
mapper=self._bind_mapper(), clause=querycontext.statement, **kw
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\sqlalchemy\orm\query.py", line 3404, in _connection_from_session
conn = self.session.connection(**kw)
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\sqlalchemy\orm\session.py", line 1133, in connection
execution_options=execution_options,
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\sqlalchemy\orm\session.py", line 1139, in _connection_for_bind
engine, execution_options
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\sqlalchemy\orm\session.py", line 432, in _connection_for_bind
conn = bind._contextual_connect()
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\sqlalchemy\engine\base.py", line 2242, in _contextual_connect
self._wrap_pool_connect(self.pool.connect, None),
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\sqlalchemy\engine\base.py", line 2276, in _wrap_pool_connect
return fn()
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\sqlalchemy\pool\base.py", line 363, in connect
return _ConnectionFairy._checkout(self)
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\sqlalchemy\pool\base.py", line 773, in _checkout
fairy = _ConnectionRecord.checkout(pool)
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\sqlalchemy\pool\base.py", line 492, in checkout
rec = pool._do_get()
File "C:\Users\lking\Documents\Lou's Software\projects\members\members\venv\lib\site-packages\sqlalchemy\pool\impl.py", line 131, in _do_get
code="3o7r",
sqlalchemy.exc.TimeoutError: QueuePool limit of size 10 overflow 10 reached, connection timed out, timeout 30 (Background on this error at: http://sqlalche.me/e/3o7r)
If I don't use the SQLALCHEMY_BINDS the connections are released to the pool, similar to below:
DEBUG:sqlalchemy.pool.impl.QueuePool:Created new connection <_mysql.connection open to '127.0.0.1' at 000002A68ED917D8>
DEBUG:sqlalchemy.pool.impl.QueuePool:Created new connection <_mysql.connection open to '127.0.0.1' at 000002A68ED94F88>
DEBUG:sqlalchemy.pool.impl.QueuePool:Connection <_mysql.connection open to '127.0.0.1' at 000002A68ED917D8> checked out from pool
DEBUG:sqlalchemy.pool.impl.QueuePool:Connection <_mysql.connection open to '127.0.0.1' at 000002A68ED94F88> checked out from pool
request.path = /admin/users
DEBUG:sqlalchemy.pool.impl.QueuePool:Connection <_mysql.connection open to '127.0.0.1' at 000002A68ED917D8> being returned to pool
DEBUG:sqlalchemy.pool.impl.QueuePool:Connection <_mysql.connection open to '127.0.0.1' at 000002A68ED917D8> rollback-on-return, via agent
127.0.0.1 - - [10/Mar/2020 15:25:44] "GET /static/js/jquery-ui-1.12.1.custom/images/ui-icons_ffffff_256x240.png HTTP/1.1" 200 -
INFO:werkzeug:127.0.0.1 - - [10/Mar/2020 15:25:44] "GET /static/js/jquery-ui-1.12.1.custom/images/ui-icons_ffffff_256x240.png HTTP/1.1" 200 -
DEBUG:sqlalchemy.pool.impl.QueuePool:Connection <_mysql.connection open to '127.0.0.1' at 000002A68ED94F88> being returned to pool
DEBUG:sqlalchemy.pool.impl.QueuePool:Connection <_mysql.connection open to '127.0.0.1' at 000002A68ED94F88> rollback-on-return
DEBUG:sqlalchemy.pool.impl.QueuePool:Connection <_mysql.connection open to '127.0.0.1' at 000002A68ED917D8> checked out from pool
[2020-03-10 15:25:44,829] DEBUG in tables: rendertemplate(): self.templateargs = {}
DEBUG:runningroutes:rendertemplate(): self.templateargs = {}
DEBUG:sqlalchemy.pool.impl.QueuePool:Connection <_mysql.connection open to '127.0.0.1' at 000002A68ED917D8> being returned to pool
DEBUG:sqlalchemy.pool.impl.QueuePool:Connection <_mysql.connection open to '127.0.0.1' at 000002A68ED917D8> rollback-on-return, via agent
:

Issue was that I was using two different SQLAlchemy() instances. Not sure how I could have been looking at this for two days, and within five minutes after posting to stackoverflow I had an epiphany.

Related

NotImplementedError asynchronous

I'm trying to use fastapi connect to Postgresql with async,but I got a NotimplementError,
It's seems the coderecord = await objects.get(test5, orderId=result['orderId'])
cause this problem.
but I don't know how to fixed it
there is some solution in network,but it did'n work
import platform
import asyncio
if platform.system() == "Windows":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
*code
import peewee_async
import peewee_asyncext
from fastapi import FastAPI
from playhouse.postgres_ext import *
db = peewee_asyncext.PooledPostgresqlExtDatabase(
database = 'postgres',
host = '127.17.0.2',
port = '5432',
user = 'postgres',
password = 1234,
register_hstore = False,
max_connections = 20,
connect_timeout = 3
)
objects = peewee_async.Manager(database =db)
db.set_allow_sync = False
class test5(Model):
orderId = FixedCharField(primary_key = True)
transactionId = FixedCharField()
class Meta:
database = db
table_name = 'test'
app = FastAPI()
#app.post("/test")
async def test():
result = {
"orderId":"test",
"transactionId":"123"
}
try:
record = await objects.get(test5, orderId=result['orderId'])
except Exception as e:
if str(e) == "":
await objects.execute(test5.insert(result))
return result
*request
import requests,json
data={}
url='http://127.0.0.1:8000/test'
r=requests.post(url,json.dumps(data))
print(r.text)
*error
Future exception was never retrieved
future: <Future finished exception=NotImplementedError()>
Traceback (most recent call last):
File "D:\Python\lib\site-packages\peewee_async.py", line 852, in connect_async
await conn.connect()
File "D:\Python\lib\site-packages\peewee_async.py", line 1014, in connect
self.pool = await aiopg.create_pool(
File "D:\Python\lib\site-packages\aiopg\pool.py", line 300, in from_pool_fill
await self._fill_free_pool(False)
File "D:\Python\lib\site-packages\aiopg\pool.py", line 336, in _fill_free_pool
conn = await connect(
File "D:\Python\lib\site-packages\aiopg\connection.py", line 65, in connect
connection = Connection(
File "D:\Python\lib\site-packages\aiopg\connection.py", line 772, in __init__
self._loop.add_reader(
File "D:\Python\lib\asyncio\events.py", line 504, in add_reader
raise NotImplementedError
NotImplementedError
Future exception was never retrieved
future: <Future finished exception=NotImplementedError()>
Traceback (most recent call last):
File "C:\Users\user\Desktop\test\others\.\test5.py", line 39, in test
record = await objects.get(test5, orderId=result['orderId'])
File "D:\Python\lib\site-packages\peewee_async.py", line 166, in get
await self.connect()
File "D:\Python\lib\site-packages\peewee_async.py", line 302, in connect
await self.database.connect_async(loop=self.loop, timeout=self._timeout)
File "D:\Python\lib\site-packages\peewee_async.py", line 852, in connect_async
await conn.connect()
File "D:\Python\lib\site-packages\peewee_async.py", line 1014, in connect
self.pool = await aiopg.create_pool(
File "D:\Python\lib\site-packages\aiopg\pool.py", line 300, in from_pool_fill
await self._fill_free_pool(False)
File "D:\Python\lib\site-packages\aiopg\pool.py", line 336, in _fill_free_pool
conn = await connect(
File "D:\Python\lib\site-packages\aiopg\connection.py", line 65, in connect
connection = Connection(
File "D:\Python\lib\site-packages\aiopg\connection.py", line 772, in __init__
self._loop.add_reader(
File "D:\Python\lib\asyncio\events.py", line 504, in add_reader
raise NotImplementedError
NotImplementedError
*Windows version info:
Python 3.9.10 (tags/v3.9.10:f2f3f53, Jan 17 2022, 15:14:21) [MSC v.1929 64 bit (AMD64)] on
win32
Windows 10 Pro, version 20H2, OS build 19042.1526

Python multiprocessing, can't pickle thread.lock (pymongo.Cursor)

First, let me assure you I read all the relevant answers and they don't work for me.
I am using multiprocessing Pool to parallelize my data creation. I am using Mongodb 5.0 and pymongo client.
As you can see I am initializing the mongo client in the worker as suggested by the available answers but still I get a :
TypeError: cannot pickle '_thread.lock' object
Exception ignored in: <function CommandCursor.__del__ at 0x7f96f6fff160>
Is there a way I can use multiprocessing with pymongo.Cursor ??
Any help will be appreciated
This is the function that calls the Pool
def get_all_valid_events(
event_criteria:str,
all_listings:List[str],
earnings:List[Dict[str,Any]],
days_around_earnings=0,
debug=False,
poolsize=10,
chunk_size=100,
lookback=30,
lookahead = 0
):
start = time.perf_counter()
listings = Manager().list(all_listings.copy())
valid_events = []
if debug:
for i in range(ceil(len(listings)/chunk_size)):
valid_events += get_valid_event_dates_by_listing(event_criteria,listings[i*chunk_size:(i+1)*chunk_size] , earnings, days_around_earnings,debug)
else:
payload = list()
for i in range(ceil(len(listings)/chunk_size)):
payload.append(
[
event_criteria,
listings[i*chunk_size:(i+1)*chunk_size],
earnings,
days_around_earnings,
debug,
lookback,
lookahead
]
)
with ThreadPool(poolsize) as pool:
valid_events = pool.starmap(get_valid_event_dates_by_listing, payload)
print(f"getting all valid true events took {time.perf_counter() - start} sec")
return valid_events
And this is the worker function:
def get_valid_event_dates_by_listing(
event_criteria:str,
listings:List[str],
earnings_list,
days_around_earnings=0,
debug=False,
lookback=30,
lookahead=0
) -> List[Tuple[Tuple[str, datetime], int]]:
#TODO: generalize event filter
start = time.perf_counter()
client = MongoClient()
db = client['stock_signals']
cursor_candles_by_listing = db.candles.find(
{'listing': {'$in': listings}},
{'_id':0, 'listing':1, 'date':1,'position':1, 'PD_BBANDS_6_lower':1, 'close':1, 'PD_BBANDS_6_upper':1}
)
candles = list(cursor_candles_by_listing)
df = pd.DataFrame(candles).dropna()
minimum_position_dict = dict(df.groupby('listing').min()['position']) # We need the minimum position by listing to filter only events that have lookback
# Filter only the dates that satisfy the criteria
lte_previous_bb_6_lower = df['close'] <= df[f"{event_criteria}_lower"].shift()
gte_previous_bb_6_upper = df['close'] >= df[f"{event_criteria}_upper"].shift()
potential_true_events_df = df[lte_previous_bb_6_lower | gte_previous_bb_6_upper]
potential_false_events_df = df.drop(potential_true_events_df.index)
potential_true_event_dates = potential_true_events_df[['listing', 'date', 'position']].values
actual_true_event_dates = earning_helpers.filter_event_dates_by_earnings_and_position(potential_true_event_dates, earnings_list, minimum_position_dict ,days_around_earning=days_around_earnings, lookback=lookback)
true_event_dates = [((event_date[0], event_date[1], event_date[2]), 1) for event_date in actual_true_event_dates]
potential_false_event_dates = potential_false_events_df[['listing', 'date', 'position']].values
actual_false_event_dates = _random_false_events_from_listing_df(potential_false_event_dates, len(actual_true_event_dates), earnings_list, minimum_position_dict, days_around_earnings,lookback)
false_events_dates = [((event_date[0], event_date[1], event_date[2]), 0) for event_date in actual_false_event_dates]
all_event_dates = true_event_dates + false_events_dates
shuffle(all_event_dates)
print(f"getting a true sequence for listing took {time.perf_counter() - start} sec")
return all_event_dates
And this is my main
from utils import event_helpers, earning_helpers
from utils.queries import get_candle_listing
if __name__ == "__main__":
all_listings = get_candle_listing.get_listings()
earnigns = earning_helpers.get_all_earnings_dates()
res = event_helpers.get_all_valid_events('PD_BBANDS_6', all_listings, earnigns, 2, chunk_size=100)
Full Stack Trace
File "test_multiprocess.py", line 8, in <module>
res = event_helpers.get_all_valid_events('PD_BBANDS_6', all_listings, earnigns, 2, chunk_size=100)
File "/media/data/projects/ml/signal_platform/utils/event_helpers.py", line 53, in get_all_valid_events
valid_events = pool.starmap(get_valid_event_dates_by_listing, payload)
File "/home/froy001/.asdf/installs/python/3.8.12/lib/python3.8/multiprocessing/pool.py", line 372, in starmap
return self._map_async(func, iterable, starmapstar, chunksize).get()
File "/home/froy001/.asdf/installs/python/3.8.12/lib/python3.8/multiprocessing/pool.py", line 771, in get
raise self._value
File "/home/froy001/.asdf/installs/python/3.8.12/lib/python3.8/multiprocessing/pool.py", line 537, in _handle_tasks
put(task)
File "/home/froy001/.asdf/installs/python/3.8.12/lib/python3.8/multiprocessing/connection.py", line 206, in send
self._send_bytes(_ForkingPickler.dumps(obj))
File "/home/froy001/.asdf/installs/python/3.8.12/lib/python3.8/multiprocessing/reduction.py", line 51, in dumps
cls(buf, protocol).dump(obj)
TypeError: cannot pickle '_thread.lock' object
Exception ignored in: <function CommandCursor.__del__ at 0x7f46e91e21f0>
Traceback (most recent call last):
File "/home/froy001/.cache/pypoetry/virtualenvs/signal-platform-31MTNyCe-py3.8/lib/python3.8/site-packages/pymongo/command_cursor.py", line 68, in __del__
File "/home/froy001/.cache/pypoetry/virtualenvs/signal-platform-31MTNyCe-py3.8/lib/python3.8/site-packages/pymongo/command_cursor.py", line 83, in __die
File "/home/froy001/.cache/pypoetry/virtualenvs/signal-platform-31MTNyCe-py3.8/lib/python3.8/site-packages/pymongo/mongo_client.py", line 1696, in _cleanup_cursor
File "/home/froy001/.cache/pypoetry/virtualenvs/signal-platform-31MTNyCe-py3.8/lib/python3.8/site-packages/pymongo/client_session.py", line 466, in _end_session
File "/home/froy001/.cache/pypoetry/virtualenvs/signal-platform-31MTNyCe-py3.8/lib/python3.8/site-packages/pymongo/client_session.py", line 871, in in_transaction
File "/home/froy001/.cache/pypoetry/virtualenvs/signal-platform-31MTNyCe-py3.8/lib/python3.8/site-packages/pymongo/client_session.py", line 362, in active
AttributeError: 'NoneType' object has no attribute 'STARTING'
Update: 01-23
I tried using the multiprocess library using dill but it didn't help

Flask-SqlAlchemy, Bcrypt, Postgres issue with encoding

I'm writing my first API from scratch and have a /login endpoint that errors when verifying a users password with bcrypt but only when using Postgres as my DB, works correctly when using SQLite3.
Also, any assistance in better ways to structure anything in my models or route is always welcome, this is my first API in Flask / Python so I'm still learning.
Thanks in advance!
Error:
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
[2021-06-22 12:06:14,415] ERROR in app: Exception on /api/v1/login [POST]
Traceback (most recent call last):
File "C:\Users\x4c8\Projects\money_api\venv\lib\site-packages\flask\app.py", line 2070, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\x4c8\Projects\money_api\venv\lib\site-packages\flask\app.py", line 1515, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\x4c8\Projects\money_api\venv\lib\site-packages\flask\app.py", line 1513, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\x4c8\Projects\money_api\venv\lib\site-packages\flask\app.py", line 1499, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "C:\Users\x4c8\Projects\money_api\routes.py", line 47, in token_get
check = user.verify_password(password)
File "C:\Users\x4c8\Projects\money_api\models.py", line 40, in verify_password
return bcrypt.checkpw(enc_pw, self.password_hash)
File "C:\Users\x4c8\Projects\money_api\venv\lib\site-packages\bcrypt\__init__.py", line 120, in checkpw
raise TypeError("Unicode-objects must be encoded before checking")
TypeError: Unicode-objects must be encoded before checking
127.0.0.1 - - [22/Jun/2021 12:06:14] "POST /api/v1/login HTTP/1.1" 500 -
User class in Models.py:
class User(db.Model, Serializer):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(15), unique=False, nullable=True)
last_name = db.Column(db.String(20), unique=False, nullable=True)
email = db.Column(db.String(120), unique=True, nullable=False)
password_hash = db.Column(db.String(255), unique=False, nullable=False)
country = db.Column(db.String(2), unique=False, nullable=True)
subscription_level = db.Column(db.Integer, default=0)
subscription_purchase_date = db.Column(db.DateTime(), unique=False, nullable=True)
last_login = db.Column(db.DateTime(), unique=False, default=datetime.utcnow)
modified_at = db.Column(db.DateTime(), unique=False, default=datetime.utcnow)
created_at = db.Column(db.DateTime(), unique=False, default=datetime.utcnow)
# relationships
portfolios = db.relationship('StockPortfolio', foreign_keys='StockPortfolio.fk_user', backref='user',
lazy='dynamic', cascade='all, delete-orphan')
#property
def password(self):
raise AttributeError('password not readable')
#password.setter
def password(self, password):
enc_pw = password.encode('utf-8')
self.password_hash = bcrypt.hashpw(enc_pw, bcrypt.gensalt()).decode('utf-8')
def verify_password(self, password):
enc_pw = password.encode('utf-8')
return bcrypt.checkpw(enc_pw, self.password_hash)
def serialize(self):
d = Serializer.serialize(self)
del d['password_hash']
del d['modified_at']
del d['created_at']
del d['last_login']
return d
/login from routes.py
# POST /login
#routes.route(api_v1 + 'login', methods=['POST'])
def token_get():
if request.method == 'POST':
body = request.get_json()
# fail on missing params
if body.get('email') is None:
return jsonify(msg='email parameter is missing'), 422
if body.get('password') is None:
return jsonify(msg='password parameter is missing'), 422
# fail on email not in use
user = User.query.filter_by(email=body.get('email')).first()
if user is None:
return jsonify(msg='Email is not in use'), 404
else:
password = body.get('password')
check = user.verify_password(password)
if check:
# record last login
user.last_login = datetime.utcnow()
# prep and return tokens
access_token = create_access_token(identity=user.id)
refresh_token = create_refresh_token(identity=user.id)
return jsonify(msg='login successful', access_token=access_token, refresh_token=refresh_token), 200
else:
return jsonify(msg='incorrect email or password'), 409
You need just change this part of the code to convert password_hash to bytes:
def verify_password(self, password):
enc_pw = password.encode('utf-8')
return bcrypt.checkpw(enc_pw, bytes(self.password_hash, 'utf-8'))

TypeError: unsupported operand type(s) for +: 'int' and 'RowProxy'

The purpose of this view is to extract and return into JSON format after reading from goodread.com and my database by some calculation.
I tried so many ways to render the API but still no hope
I tried changing user input oneIsbn with 'oneIsbn' while querying in each listed SQL queries. what I got on my browser is just like this
{
"Error": "Invalid ISBN 0380795272"
}
My code snippet
#app.route("/api/<oneIsbn>", methods=["GET", "POST"])
#login_required
def api(oneIsbn):
"""Returns in JSON format for a single Book"""
if request.method == "GET":
check = db.execute("SELECT * FROM books WHERE isbn= :isbn",
{"isbn": oneIsbn}).fetchone()
if check is None:
return jsonify({"Error": f"Invalid ISBN {oneIsbn}"}), 405
else:
res = requests.get(
"https://www.goodreads.com/book/review_counts.json",
params={
"key": "x9fJg",
"isbns": oneIsbn})
if res.status_code != 200:
raise Exception("ERROR: API request unsuccessful.")
else:
data = res.json()
y = data["books"][0]["work_reviews_count"]
r = data["books"][0]["average_rating"]
isbn = db.execute("SELECT isbn FROM books WHERE isbn = :isbn",
{"isbn": oneIsbn}).fetchone()
title = db.execute("SELECT title FROM books WHERE isbn = :isbn",
{"isbn": oneIsbn}).fetchone()
author = db.execute("SELECT author FROM books WHERE isbn = :isbn",
{"isbn": oneIsbn}).fetchone()
year = db.execute("SELECT year FROM books WHERE isbn = :isbn",
{"isbn": oneIsbn}).fetchone()
x = db.execute("SELECT COUNT(reviews) FROM reviews WHERE isbn = :isbn",
{"isbn": 'oneIsbn'}).fetchone()
z = db.execute("SELECT rating FROM reviews WHERE isbn = :isbn",
{"isbn": oneIsbn}).fetchone()
rev = int(y)
revCount = int(x.count)
bothReviewValue = sum((revCount,rev))
# listRate = float(z)
rat = float(r)
bothRatingValue = sum([z,rat]) / 2
return jsonify(
ISBN=isbn,
TITLE=title,
AUTHOR=author,
YEAR=year,
REVIEWS=bothReviewValue,
RATING=bothRatingValue
), 422
TRACEBACK
TypeError
TypeError: unsupported operand type(s) for +: 'int' and 'RowProxy'
Traceback (most recent call last)
File "C:\Users\Beacon\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\Beacon\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\Beacon\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\Beacon\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\Beacon\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\Beacon\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\Beacon\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\Beacon\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\_compat.py", line 39, in reraise
Open an interactive python shell in this frameraise value
File "C:\Users\Beacon\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\Beacon\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\Beacon\Desktop\THINKFUL DOCS\PYTHON\PYTHON WORKSPACE\project1\application.py", line 39, in wrapped_view
return view(**kwargs)
File "C:\Users\Beacon\Desktop\THINKFUL DOCS\PYTHON\PYTHON WORKSPACE\project1\application.py", line 233, in api
bothRatingValue = sum([z,rat]) / 2
TypeError: unsupported operand type(s) for +: 'int' and 'RowProxy'
The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.
To switch between the interactive traceback and the plaintext one, you can click on the "Traceback" headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side.
You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:
dump() shows all variables in the frame
dump(obj) dumps all that's known about the object
Brought to you by DON'T PANIC, your friendly Werkzeug powered traceback interpreter.
This method I used really works great. I already missed something like
The sum method should be put in tuple not in list and the pulled string rate should cast to float.
rev = int(y)
revCount = int(x.count)
bothReviewValue = sum((revCount,rev))
listRate = float(z)
rat = float(r)
bothRatingValue = sum((listRate,rat)) / 2

Couldn't connect to host server (odoo v11)

I was working on odoo, precisely in Website builder module while I was creating a website via the host IP address 192.168.1.2:9012, suddenly it crashes and shown me an Internal server error.
I tried to have a look at the log file and got this traceback,
2018-12-06 18:14:31,432 1 INFO ? odoo.sql_db: Connection to the database failed
2018-12-06 18:14:31,436 1 INFO ? werkzeug: 192.168.1.9 - - [06/Dec/2018 18:14:31] "GET /favicon.ico HTTP/1.1" 500 -
2018-12-06 18:14:31,441 1 ERROR ? werkzeug: Error on request:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/werkzeug/serving.py", line 205, in run_wsgi
execute(self.server.app)
File "/usr/lib/python3/dist-packages/werkzeug/serving.py", line 193, in execute
application_iter = app(environ, start_response)
File "/usr/lib/python3/dist-packages/odoo/service/server.py", line 250, in app
return self.app(e, s)
File "/usr/lib/python3/dist-packages/odoo/service/wsgi_server.py", line 166, in application
return application_unproxied(environ, start_response)
File "/usr/lib/python3/dist-packages/odoo/service/wsgi_server.py", line 154, in application_unproxied
result = handler(environ, start_response)
File "/usr/lib/python3/dist-packages/odoo/http.py", line 1318, in _call_
return self.dispatch(environ, start_response)
File "/usr/lib/python3/dist-packages/odoo/http.py", line 1292, in _call_
return self.app(environ, start_wrapped)
File "/usr/lib/python3/dist-packages/werkzeug/wsgi.py", line 599, in _call_
return self.app(environ, start_response)
File "/usr/lib/python3/dist-packages/odoo/http.py", line 1455, in dispatch
self.setup_db(httprequest)
File "/usr/lib/python3/dist-packages/odoo/http.py", line 1387, in setup_db
httprequest.session.db = db_monodb(httprequest)
File "/usr/lib/python3/dist-packages/odoo/http.py", line 1539, in db_monodb
dbs = db_list(True, httprequest)
File "/usr/lib/python3/dist-packages/odoo/http.py", line 1506, in db_list
dbs = odoo.service.db.list_dbs(force)
File "/usr/lib/python3/dist-packages/odoo/service/db.py", line 369, in list_dbs
with closing(db.cursor()) as cr:
File "/usr/lib/python3/dist-packages/odoo/sql_db.py", line 634, in cursor
return Cursor(self.__pool, self.dbname, self.dsn, serialized=serialized)
File "/usr/lib/python3/dist-packages/odoo/sql_db.py", line 178, in _init_
self._cnx = pool.borrow(dsn)
File "/usr/lib/python3/dist-packages/odoo/sql_db.py", line 517, in _locked
return fun(self, *args, **kwargs)
File "/usr/lib/python3/dist-packages/odoo/sql_db.py", line 585, in borrow
**connection_info)
File "/usr/lib/python3/dist-packages/psycopg2/__init__.py", line 164, in connect
conn = _connect(dsn, connection_factory=connection_factory, async=async)
psycopg2.OperationalError: could not connect to server: No route to host
Is the server running on host "172.17.0.4" and accepting
TCP/IP connections on port 5432 ?
I believe that's a network problem, I couldn't connect to the host server. do you have any idea about this please?
Thank you.
The error is from Odoo server because it cannot connect to the PostgreSQL database. First make sure your database service is running and available.
From your ip addresses I assume you are running database locally in some kind of virtualization environment like Docker. If you are not able to connect, please describe your environment in more detail. This will make it possible for stackoverflowers to help you.