Access variable of nested Class in python - python

I'm using Peewee and bottle.py for a very small WebApp. Once in a while I get a MySQLDatabase has gone away Error, which my script doesn't seem to recover from.
According to this answer, I should simply try-catch the error and recover myself.
An example of what I have:
def create_db_con():
return peewee.MySQLDatabase("db_name", host="host", user="user", passwd="pass")
class ModelObj(peewee.Model):
#some member ommited
class Meta:
database=create_db_con()
#route("/")
def index_htm():
try:
mo = ModelObj.filter(foo="bar")
catch OperationalError, oe:
ModelObj.Meta.database = create_db_con()
gives me the AttributeError in case of the OperationalError:
AttributeError: type object 'OrderProdukt' has no attribute 'Meta'
How am I supposed to recover from this situation?
EDIT:
As univerio pointed out, I can access it via ModelObj._meta.database, but it doesn't seem to work to just create it new.
Is this a default python behavior for nested classes?

Related

Cannot (always) fetch an attribute in an object even though it exists

I'm currently developing locally an Azure function that communicates with Microsoft Sentinel, in order to fetch the alert rules from it, and more specifically their respective querys :
credentials = AzureCliCredential()
alert_rules_operations = SecurityInsights(credentials, SUBSCRIPTION_ID).alert_rules
list_alert_rules = alert_rules_operations.list(resource_group_name=os.getenv('RESOURCE_GROUP_NAME'), workspace_name=os.getenv('WORKSPACE_NAME'))
The issue is that when I'm looping over list_alert_rules, and try to see each rule's query, I get an error:
Exception: AttributeError: 'FusionAlertRule' object has no attribute 'query'.
Yet, when I check their type via the type() function:
list_alert_rules = alert_rules_operations.list(resource_group_name=os.getenv(
'RESOURCE_GROUP_NAME'), workspace_name=os.getenv('WORKSPACE_NAME'))
for rule in list_alert_rules:
print(type(rule))
##console: <class 'azure.mgmt.securityinsight.models._models_py3.ScheduledAlertRule'>
The weirder issue is that this error appears only when you don't print the attribute. Let me show you:
Print:
for rule in list_alert_rules:
query = rule.query
print('query', query)
##console: query YAY I GET WHAT I WANT
No print:
for rule in list_alert_rules:
query = rule.query
...
##console: Exception: AttributeError: 'FusionAlertRule' object has no attribute 'query'.
I posted the issue on the GitHub repo, but I'm not sure whether it's a package bug or a runtime issue. Has anyone ran into this kind of problems?
BTW I'm running Python 3.10.8
TIA!
EDIT:
I've tried using a map function, same issue:
def format_list(rule):
query = rule.query
# print('query', query)
# query = query.split('\n')
# query = list(filter(lambda line: "//" not in line, query))
# query = '\n'.join(query)
return rule
def main(mytimer: func.TimerRequest) -> None:
# results = fetch_missing_data()
credentials = AzureCliCredential()
alert_rules_operations = SecurityInsights(
credentials, SUBSCRIPTION_ID).alert_rules
list_alert_rules = alert_rules_operations.list(resource_group_name=os.getenv(
'RESOURCE_GROUP_NAME'), workspace_name=os.getenv('WORKSPACE_NAME'))
list_alert_rules = list(map(format_list, list_alert_rules))
I have tried with same as you used After I changed like below; I get the valid response.
# Management Plane - Alert Rules
alertRules = mgmt_client.alert_rules.list_by_resource_group('<ResourceGroup>')
for rule in alertRules:
# Try this
test.query = rule.query //Get the result
#print(rule)
if mytimer.past_due:
logging.info('The timer is past due!')
Instead of this
for rule in list_alert_rules:
query = rule.query
Try below
for rule in list_alert_rules:
# Try this
test.query = rule.query
Sorry for the late answer as I've been under tons of work these last few days.
Python has an excellent method called hasattr that checks if the object contains a specific key.
I've used it in the following way:
for rule in rules:
if hasattr(rule, 'query'):
...
The reason behind using this is because the method returns object of different classes, however inherited from the one same mother class.
Hope this helps.

no value for argument self in unbound method call

Thanks for reading this. I've spent the past 48 hours trying to get this code to work. First of all I must disclose that this is for a college assignment. I'm not looking for any assistance or comment on how I might 'gain' in the assignment, I just need to figure out what I'm doing wrong. I have googled the issue and I've read through tutorials on classes and I do feel like I understand them and have got the examples to work. This one issue is stumping me.
So, I have a class which will read a database as follows:
import mysql.connector
import pandas as pd
class DAOdv:
#dbConn=mysql.connector.connect()
def __init__(self):
# import the config file
config=pd.read_csv('./files/config.ini')
dbName=config.iloc[int(config[config['item']=='databaseName'].index[0])]['setting']
uname=config.iloc[int(config[config['item']=='username'].index[0])]['setting']
hst=config.iloc[int(config[config['item']=='host'].index[0])]['setting']
prt=config.iloc[int(config[config['item']=='port'].index[0])]['setting']
# create the connection
self.dbConn=mysql.connector.connect(
host=hst,
database=dbName,
port=prt,
username=uname,
password='' # no password on Server as yet
)
def allClients(self):
cursor=self.dbConn.cursor()
sSQL = 'SELECT * FROM clients'
cursor.execute(sSQL)
results=cursor.fetchall()
return results
daoDV=DAOdv()
and the 'server' code which is:
from flask import Flask
from daoDV import DAOdv
app=Flask(__name__, static_url_path='',static_folder='')
# curl "http://127.0.0.1:5000/clients"
#app.route('/clients')
def getAll():
results=DAOdv.allClients()
return results
In python, the second last line above, DAOdv is underlined in red and hovering over it produces the message "no value for argument self in unbound method call"
What am I doing wrong? I'm assuming the error is in the class?? but I can't figure out what.
Many thanks for your help with this.
Seamus
DAOdv is the class itself, not the instantiated object which you create at the end with: daoDV=DAOdv().
Change your server code to:
from daoDV import daoDV # note the capitalization - we're importing the object here
#(...)
results = daoDV.allClients()
Your method allClients() is an instance method, not a class method.
That's why you should call it like:
results=DAOdv().allClients()
Methods can be an instance or class method.
Class methods are methods which have #classmethod decorator.

'WSGIRequest' object has no attribute 'flash'

I badly need your help. I am currently trying to pass a string value using flash but I am not sure if I got it correctly.
This is my code:
def first_view(request):
request.flash['message'] = 'Operation succeeded!'
return HttpResponseRedirect(reverse(second_view))
def second_view(request):
print request.flash['message']
request.flash.keep('message')
return HttpResponseRedirect(reverse(third_view))
I'd like to pass the message "Operation Succeeded" to second_view() through HttpResponseRedirect however I got this error message. I am new to python and django so this does not really make a clear sense to me. Your help is so much appreciated. Thanks
By default the django HttpRequest object doesn't have an attribute named flash. That's why you are getting this error. You can see available attributes here: https://docs.djangoproject.com/en/1.9/ref/request-response/#httprequest-objects
But there's no reason why you can't add one.
def first_view(request):
request.flash = {'message'] : 'Operation succeeded!'}
return HttpResponseRedirect(reverse(second_view))
def second_view(request):
try:
print request.flash['message']
request.flash.keep('message')
except:
pass
return HttpResponseRedirect(reverse(third_view))
But from where your flash.keep comes from i have no idea!! As pointed out by wtower it's more usual to rely on the django messages framework for this sort of thing.

Advanced model validation in sqlalchemy

I have following following model:
class Foo(DeclarativeBase):
code = Column(u'code', String(length=255))
ctype = Column(u'ctype', String(length=255))
I need to validate one field, with respect to another one.
For example
if ctype == "bar" and code == "buzz": raise ValueError
Do not create object and record in db on commit. And if no exception was raised create all as usual.
I've tried to use. Simple validators
and tried to setup 'before_insert' event using before_insert mapper event
and wrote such code:
def validate_foo(mapper, connection, target):
if target.ctype == "bar" and target.code == "buzz":
raise ValueError
event.listen(Foo, 'before_insert', validate_foo)
When ctype == "bar" and code == "buzz", it does not create any object in DB. It does not raise any exception. But it creates Foo object instance(without db).
What is the best way to do such validation?
I've ended up with creating trigger in DB(I use postgresql). And catching integrity error in python code.

"AttributeError: 'NoneType' object has no attribute 'get'" when calling `to_mongo` in MongoEngine

I have the following Python code to connect to a MongoDB (2.0.1 installed through MacPorts) database using MongoEngine (0.7.9 installed through pip):
import datetime
from mongoengine import *
connect('mydb')
class Post(EmbeddedDocument):
title = StringField(required=True)
description = StringField(required=True)
author = StringField(required=True)
pub_date = DateTimeField(required=True, default=datetime.datetime.now)
p = Post()
p.author = "genba"
p.title = "Test post"
p.description = "This is a test post"
When calling the method to_mongo on the objet p, I get the following traceback:
env/lib/python2.7/site-packages/mongoengine/base.pyc in to_mongo(self)
1040 # Only add _cls and _types if allow_inheritance is not False
1041 if not (hasattr(self, '_meta') and
-> 1042 self._meta.get('allow_inheritance', ALLOW_INHERITANCE) == False):
1043 data['_cls'] = self._class_name
1044 data['_types'] = self._superclasses.keys() + [self._class_name]
AttributeError: 'NoneType' object has no attribute 'get'
As you may notice, the error is produced by a line of code in MongoEngine's code, installed in the virtual environment env with virtualenv.
This error actually arises both when I embed the document Post into another document by using an EmbeddedDocumentField, and when I just paste the previous code into the Python interpreter (until now, I've just used IPython instead of the vanilla Python interpreter).
I've tried debugging with pdb and searching the internet, but I haven't got to find any useful information on this issue. The only thing I can tell is that self._meta is None and that causes the exception to be raised. But why it is None or what that should mean… I don't know.
Why do I get this error? It's definitely in MongoEngine's code, but is it cause by MongoEngine or by my code/data? How can I solve it?
Thanks in advance.
PS: As additional information, I plan to use this with Django, but the previous code can be run apart from Django, and I've done my tests like that (without Django, just with IPython, like I mentioned before).

Categories

Resources