AttributeError: 'builtin_function_or_method' object has no attribute 'translate' - python

I am using Ubuntu as OS, pymysql, flask, sqlalchemy frameworks. Then I do GET request I have this error:
File "/srv/MSH/venv/local/lib/python2.7/site-packages/pymysql/converters.py", line 73, in _escape_unicode
return value.translate(_escape_table)
AttributeError: 'builtin_function_or_method' object has no attribute 'translate'
My routes.py code:
#app.route('/device/<dev_id>/<name>/<dev_type>/<state>', methods=['GET'])
def device(dev_id, state, dev_type, name):
# This function communicates with device
dev_state = 0
device = Devices.query.filter_by(dev_id=id).first()
# Check state
if state == "0":
state = False
if state == "1":
state = True
if device is None:
# if we don't know device write to database
dev = Devices(dev_id=dev_id, type=dev_type, prev_state=state, name=name)
db.session.add(dev)
db.session.commit()
return "hi"
else:
# Write data to database and return wanted state
device.prev_state = state
if device.state:
dev_state = 1
if not device.state:
dev_state = 0
db.session.commit()
return str(dev_state)

Wrong line here:
device = Devices.query.filter_by(dev_id=id).first()
You are query sql with something identical to internal python function. I think correct string is:
device = Devices.query.filter_by(dev_id=dev_id).first()

Related

Alembic autogenerate not working for table modifications when run programmatically

I'm trying to create automatic tests for alembic, specifically to test that the revision --autogenerate command provides the expected migrations. Instead of running from the command line, I want to obtain the suggested revisions programmatically and run them to confirm that the effect on the test database is as expected.
I have two models - initial_model_base and removed_column_base, the idea is that when I run an autogenerated revision for the second time, alembic should detect that the second model has 1 less column and create a revision to remove it. However, I'm getting ValueError: no dispatch function for object: <alembic.operations.ops.ModifyTableOps. Here is the full stack trace:
File "C:\Users\Ronel\Desktop\repos\test_alembic\tests\tests.py", line 152, in
test_removing_column()
File "C:\Users\Ronel\Desktop\repos\test_alembic\tests\tests.py", line 109, in test_removing_column
ops.invoke(op)
File "C:\Users\Ronel\AppData\Roaming\Python\Python310\site-packages\alembic\operations\base.py", line 396, in invoke
fn = self._to_impl.dispatch(
File "C:\Users\Ronel\AppData\Roaming\Python\Python310\site-packages\alembic\util\langhelpers.py", line 258, in dispatch
raise ValueError("no dispatch function for object: %s" % obj)
ValueError: no dispatch function for object: <alembic.operations.ops.ModifyTableOps object at 0x0000028C0FBC1ED0>
The table I use for testing is test_alembic_schema.employees so to prevent other tables getting affected I provided an include_object function to the config kwargs.
def include_object(object, name, type_, reflected, compare_to):
if type_ == "table":
if object.schema == "test_alembic_schema" and object.name == 'employees':
return True
else:
return False
else:
return True
mc = MigrationContext.configure(
connection=DB_DEV.connection,
opts={
'compare_type': True,
'include_schemas': True,
'include_object': include_object
}
)
ops = Operations(mc)
def test_creation():
diff_ops = produce_migrations(
context=mc,
metadata=initial_model_base.metadata
)
with DB_DEV.transaction(autocommit=True):
for op in diff_ops.upgrade_ops.ops:
ops.invoke(op)
employees = DB_DEV.get_table(table_name='employees', schema_name='test_alembic_schema')
assert len(employees.c) == 8
assert employees.c.id.primary_key
assert not employees.c.first_name.primary_key
def test_removing_column():
diff_ops = produce_migrations(
context=mc,
metadata=removed_column_base.metadata
)
with DB_DEV.transaction(autocommit=True):
for op in diff_ops.upgrade_ops.ops:
ops.invoke(op)
employees = DB_DEV.get_table(table_name='employees', schema_name='test_alembic_schema')
col_found = False
for col in employees.columns:
if col.name == 'created':
col_found = True
if col_found:
assert True
else:
assert False
I am confused as to why the operation to create a table succeeds but to amend it fails. Do you have ideas how this can be fixed so both operations work as expected?

Spotify voice assistant attribute error __enter__

Hi there so I wanted to make a spotify voice assistant so I found a video on youtube and the guy just went through his code and how it works and left the source code on his github so I used that and configured it to work on my settings but i'm getting an attribute error enter with one of his lines and theres 3 files "main.py" "setup.txt" and "pepper.py" but the problem is in main so im gonna drop the code down below
main.py:
import pandas as pd
from speech_recognition import Microphone, Recognizer, UnknownValueError
import spotipy as sp
from spotipy.oauth2 import SpotifyOAuth
from pepper import *
# Set variables from setup.txt
setup = pd.read_csv(r'C:\Users\Yousif\Documents\Python spotify\setup.txt', sep='=', index_col=0, squeeze=True, header=None)
client_id = setup['client_id']
client_secret = setup['client_secret']
device_name = setup['device_name']
redirect_uri = setup['redirect_uri']
scope = setup['scope']
username = setup['username']
# Connecting to the Spotify account
auth_manager = SpotifyOAuth(
client_id=client_id,
client_secret=client_secret,
redirect_uri=redirect_uri,
scope=scope,
username=username)
spotify = sp.Spotify(auth_manager=auth_manager)
# Selecting device to play from
devices = spotify.devices()
deviceID = None
for d in devices['devices']:
d['name'] = d['name'].replace('’', '\'')
if d['name'] == device_name:
deviceID = d['id']
break
# Setup microphone and speech recognizer
r = Recognizer()
m = None
input_mic = 'Voicemod Virtual Audio Device (WDM)' # Use whatever is your desired input
for i, microphone_name in enumerate(Microphone.list_microphone_names()):
if microphone_name == input_mic:
m = Microphone(device_index=i)
while True:
"""
Commands will be entered in the specific format explained here:
- the first word will be one of: 'album', 'artist', 'play'
- then the name of whatever item is wanted
"""
with m as source:
r.adjust_for_ambient_noise(source=source)
audio = r.listen(source=source)
command = None
try:
command = r.recognize_google(audio_data=audio).lower()
except UnknownValueError:
continue
print(command)
words = command.split()
if len(words) <= 1:
print('Could not understand. Try again')
continue
name = ' '.join(words[1:])
try:
if words[0] == 'album':
uri = get_album_uri(spotify=spotify, name=name)
play_album(spotify=spotify, device_id=deviceID, uri=uri)
elif words[0] == 'artist':
uri = get_artist_uri(spotify=spotify, name=name)
play_artist(spotify=spotify, device_id=deviceID, uri=uri)
elif words[0] == 'play':
uri = get_track_uri(spotify=spotify, name=name)
play_track(spotify=spotify, device_id=deviceID, uri=uri)
else:
print('Specify either "album", "artist" or "play". Try Again')
except InvalidSearchError:
print('InvalidSearchError. Try Again')
the exact error is:
Traceback (most recent call last):
File "c:/Users/Yousif/Documents/Python spotify/main.py", line 49, in <module>
with m as source:
AttributeError: __enter__
__enter__ is a python method that allows you to implement objects that can be used easily with the with statement. A useful example could be a database connection object (which then automagically closes the connection once the corresponding 'with'-statement goes out of scope):
class DatabaseConnection(object):
def __enter__(self):
# make a database connection and return it
...
return self.dbconn
def __exit__(self, exc_type, exc_val, exc_tb):
# make sure the dbconnection gets closed
self.dbconn.close()
...
The error here is caused because m = None, and None cannot be used in a with statement.
>>> with None as a:
... print(a)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: __enter__

Flask current_user is None type

My code that was previously working is now causing my main flask app to not run.
The error is coming from my forms.py file.
class selectClass(FlaskForm):
a = current_user.database
conn = sqlite3.connect("C:\\Users\\Lenovo\\PycharmProjects\\spacedonline\\"+a)
c = conn.cursor()
c.execute("SELECT Class FROM Students ")
data = c.fetchall()
listofclasses = []
for clas in data:
if clas[0] not in listofclasses:
listofclasses.append(clas[0])
finallist = []
for clas in listofclasses:
finallist.append((clas, clas))
nameofclass=SelectField(u"Name of Class", choices=finallist)
submit= SubmitField("Select")
On trying to launch the main.py file I get the message:
Traceback (most recent call last):
File "C:/Users/Lenovo/PycharmProjects/spacedonline/forms.py", line 102, in <module>
class selectClass(FlaskForm):
File "C:/Users/Lenovo/PycharmProjects/spacedonline/forms.py", line 104, in selectClass
a = current_user.database
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\werkzeug\local.py", line 347, in __getattr__
return getattr(self._get_current_object(), name)
AttributeError: 'NoneType' object has no attribute 'database'
As I said, it was not returning this error before, I am at a loss.
you are probably not logged in. so current_user is NoneType. Try:
if current_user: # or current_user.is_active:
a = current_user.database
...
else:
return redirect('/login')
I have been logged in and when the problem code is commented out it, my page shows me as logged on.
I have worked around the problem by creating a function which creates the class:
'''
def selectclassform():
class SelectClass(FlaskForm):
a = current_user.database
conn = sqlite3.connect("C:\\Users\\Lenovo\\PycharmProjects\\spacedonline\\"+a)
c = conn.cursor()
c.execute("SELECT Class FROM Students ")
data = c.fetchall()
listofclasses = []
for clas in data:
if clas[0] not in listofclasses:
listofclasses.append(clas[0])
finallist = []
for clas in listofclasses:
finallist.append((clas, clas))
nameofclass=SelectField(u"Name of Class", choices=finallist)
submit= SubmitField("Select")
return (SelectClass)
'''
And then calling the function in the main apps.py file:
'''
#app.route("/select", methods=["GET", "POST"])
def selectclass():
if current_user.is_authenticated:
form = selectclassform()()
print(form)
if form.validate_on_submit():
print("valid")
session ["nameofclass"]=form.nameofclass.data
#return printtable(form.nameofclass.data, current_user.database)
return redirect(url_for("validate"))
else:
print("bye")
return render_template("select.html", form=form)
else:
return redirect(url_for("login"))
'''
I've had the same issue, and this was actually due to the security keys.
I have set different app security keys and it works now.
app.config['SECRET_KEY'] = 'new key 1'
app.config['SECURITY_PASSWORD_SALT'] = 'new key 2'
It is probably due to a security control that fails when creating a new instance.

How to access the instance variable?

I have used a 'class' named 'CMS'. Also,i have defined a method def ConnectDB(),Where i have loaded the driver and created a cursor object to execute a query.Whenever i try to access the cursor object,it's giving me an attribute error.
obj.cursor.execute(sql,v)
AttributeError: CMS instance has no attribute 'cursor'
How do I resolve it?Refer the code below to understand the problem statement clearly.Thanks in advance.
class CMS:
def ConnectDB(self):
server = '192.121.063.012'
database = 'fghr_db'
username = 'abcdef'
password = 'zzzzzzz'
connStr = 'DRIVER=/opt/microsoft/msodbcsql17/lib64/libmsodbcsql- 17.2.so.0.1;SERVER='+server+';DATABASE='+database+';'+ 'UID='+username+'; PWD='+ password+';Port=1270'
cnxn = pyodbc.connect(connStr)
cursor = cnxn.cursor()
def ReadCsv(self,filepath):
data = csv.reader(open(filepath))
print data
h=data.next()
result=[]
for x in data:
c=list(x)
result.append(c)
return result
obj=CMS()
obj.ConnectDB()
sql="INSERT INTO StudentCsv VALUES (?,?,?,?,?)"
z=obj.ReadCsv("Student.csv")
for v in z:
print v
obj.cursor.execute(sql,v)
obj.cnxn.commit()
ERROR getting like below:
obj.cursor.execute(sql,v) AttributeError: CMS instance has no
attribute 'cursor'

how to return a collection from mongodb using pymongo

I'm trying to create a Collection Class in Python to access the various collections in my db. Here's what I've got:
import sys
import os
import pymongo
from pymongo import MongoClient
class Collection():
client = MongoClient()
def __init__(self, db, collection_name):
self.db = db
self.collection_name = collection_name
# self.data_base = getattr(self.client, db)
# self.collObject = getattr(self.data_base, self.collection_name)
def getCollection(self):
data_base = getattr(self.client, self.db)
collObject = getattr(data_base, self.collection_name)
return collObject
def getCollectionKeys(self, collection):
"""Get a set of keys from a collection"""
keys_list = []
collection_list = collection.find()
for document in collection_list:
for field in document.keys():
keys_list.append(field)
keys_set = set(keys_list)
return keys_set
if __name__ == '__main__':
print"Begin Main"
agents = Collection('hkpr_restore','agents')
print "agents is" , agents
agents_collection = agents.getCollection
print agents_collection
print agents.getCollectionKeys(agents_collection)
I get the following output:
Begin Main
agents is <__main__.Collection instance at 0x10ff33e60>
<bound method Collection.getCollection of <__main__.Collection instance at 0x10ff33e60>>
Traceback (most recent call last):
File "collection.py", line 52, in <module>
print agents.getCollectionKeys(agents_collection)
File "collection.py", line 35, in getCollectionKeys
collection_list = collection.find()
AttributeError: 'function' object has no attribute 'find'
The function getCollectionKeys works fine outside of a class. What am I doing wrong?
This line:
agents_collection = agents.getCollection
Should be:
agents_collection = agents.getCollection()
Also, you don't need to use getattr the way you are. Your getCollection method can be:
def getCollection(self):
return self.client[self.db][self.collection_name]

Categories

Resources