I don't know why I am having this error. Please enlighten me. Here's my code:
filename: sqlfunc.py
from sqlalchemy import create_engine
class SQL:
def __init__(self):
self.connection_string = ''
self.sql = ''
def exec_nonquery(connection_string, sql):
self.connection_string = connection_string
self.sql = sql
self.__connection = self.__mydb(self.connection_string)
self.__transaction = self.__connection.begin()
try:
self.__connection.execute(self.sql).fetchall()
self.__transaction.commit()
except:
self.__transaction.rollback()
raise
_connection.close()
def exec_query(self, connection_string, sql):
self.connection_string = connection_string
self.sql = sql
self.__connection = self.__mydb(self.connection_string)
self.__result = None
self.query_result = []
try:
self.__result = self.__connection.execute(sql)
self.query_result = list(self.__result)
except:
raise
self.__connection.close()
return self.query_result
Now, I tried:
from sqlfunc import SQL
SQL.exec_nonquery('mssql+pyodbc://scott:tiger#mydsn','select * from table1')
and I got this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "./sqlfunc.py", line 25, in exec_nonquery
self.connection_string = connection_string
NameError: global name 'self' is not defined
Is there anything I did wrong or missing?
I changed exec_nonquery to
def exec_nonquery(self, connection_string, sql)
But it leads me to this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: exec_nonquery() missing 1 required positional argument: 'sql'
"Is there anything I did wrong or missing?" - yes, you failed to include self as the first positional argument to your method:
def exec_nonquery(connection_string, sql):
should be
def exec_nonquery(self, connection_string, sql):
# ^ see here
You are also trying to call this instance method on the class. The minimal fix is:
sql = SQL() # create instance
sql.exec_nonquery('mssql+pyodbc://scott:tiger#mydsn',
'select * from table1') # call method
but as Martijn points out you really should refactor the class to make the most of OOP.
Related
I have a subclassed Course class as follows:
# course.py
class Course:
"""Represent a single Course"""
kind = 'Gen Ed'
def __init__(self, name, number) :
self._name = name # 'private' instance variable\
self._number = number
self.__display()
def display(self):
print(self.kind,"Course:" , self._name, self._number, sep=" ")
__display = display # private copy
class CSCourse(Course):
"""Represent a single CS Course"""
kind = 'CS' # class variable shared by all CSCourses
def __init__(self, name, number, language, numberOfPrograms):
Course.__init__(self, name, number)
self._language = language
self._numberOfPrograms = numberOfPrograms
def display(self):
Course.display(self)
print('Language', self._language,
'Number Of programs:', self._numberOfPrograms, sep = ' ')
I import the module as follows:
>>>from course import *
This does not throw any exception, but then when I issue the following to call the constructor, I get the error below?
>>> cs360=CSCourse("Special Topics", 360, "python", 21)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'CSCourse' is not defined
What am I doing wrong please? I did also try to see what methods are available in the classes imported. It seems nothing is being imported!
>>> import inspect
>>> inspect.getmembers(Course, lambda a:not(inspect.isroutine(a)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Course' is not defined
>>> inspect.getmembers(CSCourse, lambda a:not(inspect.isroutine(a)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'CSCourse' is not defined
For anyone else having this problem, check if you have circular imports (in file a.py from b import * and in file b.py from a import *). Python doesn't seem to raise an exception when that happens, but the import doesn't work. Restructuring the code to remove the circular import fixed the problem for me.
I need to use the googlemaps/google-maps-services-python for a project, and there is the problem.
I want to use find_place():
def find_place(client, input, input_type, fields=None, location_bias=None,
language=None):
But when I launch my script
import googlemaps
from datetime import datetime
class Place:
def __init__(self, words):
self.words = words
self.key = 'Key'
self.gmaps = googlemaps.Client(key=self.key)
place = Place(['place to find'])
print(place.key)
loca = place.gmaps.find_place(self.key,"place to find","textquery",['place_id','formatted_address'])
print(loca)
there is a problem:
Traceback (most recent call last):
File "gpbapp/program/place.py", line 15, in <module>
loca = place.gmaps.find_place(place.key,place.words[0],"textquery",['place_id','formatted_address'])
File "C:\Users\krfou\Documents\OPENCLASSROOMS\p7\env\lib\site-packages\googlemaps\client.py", line 365, in wrapper
result = func(*args, **kwargs)
File "C:\Users\krfou\Documents\OPENCLASSROOMS\p7\env\lib\site-packages\googlemaps\places.py", line 94, in find_place
"the given value is invalid: '%s'" % input_type)
ValueError: Valid values for the `input_type` param for `find_place` are 'textquery' or 'phonenumber', the given value is invalid: 'disneyland, paris'
(env)
If I do
loca = place.gmaps.find_place(place.key,"textquery",['place_id','formatted_address'])
it works but I get no result (because input is not there anymore).
{'candidates': [], 'status': 'ZERO_RESULTS'}
There is a confusion between the positional arguments, as if there was a hidden argument ... what happens?
Won't it work if you do
loca = place.gmaps.find_place(client=place.key,input="place to find", input_type="textquery",fields=['place_id','formatted_address'])
lambda from getattr getting called with "connection" as a keyword argument? Am I misusing the code or is there a bug?
Code and traceback: https://github.com/bigcommerce/bigcommerce-api-python/issues/32
#!/usr/bin/env python2
import bigcommerce
import bigcommerce.api
BIG_URL = 'store-45eg5.mybigcommerce.com'
BIG_USER = 'henry'
BIG_KEY = '10f0f4f371f7953c4d7d7809b62463281f15c829'
api = bigcommerce.api.BigcommerceApi(host=BIG_URL, basic_auth=(BIG_USER, BIG_KEY))
def get_category_id(name):
get_request = api.Categories.get(name)
try:
cat_list = api.Categories.all(name=name)
if cat_list:
return cat_list[0]['id']
else:
return None
except:
return None
def create_category(name):
rp = api.Categories.create(name)
if rp.status == 201:
return rp.json()['id']
else:
return get_category_id(name)
create_category('anothertestingcat')
Gives this traceback:
Traceback (most recent call last):
File "./bigcommerceimporter.py", line 50, in
create_category('anothertestingcat')
File "./bigcommerceimporter.py", line 44, in create_category
rp = api.Categories.create(name)
File "/home/henry/big_test_zone/local/lib/python2.7/site-packages/bigcommerce/api.py", line 57, in
return lambda args, *kwargs: (getattr(self.resource_class, item))(args, connection=self.connection, *kwargs)
TypeError: create() got multiple values for keyword argument 'connection'
Line in api.py that the traceback refers to: https://github.com/bigcommerce/bigcommerce-api-python/blob/master/bigcommerce/api.py#L57
According to the examples, create should be used like this:
api.Categories.create(name = 'anothertestingcat')
Note: You should generate a new API KEY, since you published the current one in this question.
Anyone come across this before?
import boto
conn = boto.dynamodb.connect_to_region('eu-west-1', aws_access_key_id=aws_key, aws_secret_access_key=aws_secret)
table = conn.get_table('TweetSample')
print table.scan(limit=1)
error:
Traceback (most recent call last):
File "test.py", line 9, in <module>
print table.scan(limit=1)
File "table.py", line 518, in scan
return self.layer2.scan(self, *args, **kw)
TypeError: scan() got an unexpected keyword argument 'limit'
[Finished in 0.4s with exit code 1]
I don't even know...
According to the documentation, scan method of boto.dynamodb.table.Table (which is returned by boto.dynamodb.layer2.Layer2.get_table) does not accepts limit, but max_results.
And the result is a generator. So, if you want to print it you should iterate it:
import boto.dynamodb
conn = boto.dynamodb.connect_to_region(
'eu-west-1',
aws_access_key_id=aws_key,
aws_secret_access_key=aws_secret)
table = conn.get_table('TweetSample')
for row in table.scan(max_results=1):
print row
or convert it to a sequence:
print list(table.scan(max_results=1))
I've learn some basics about python-mysqldb ,when I want to define anther function for query,I have to write (connect ,cursor...try ..) repeatedly
so I want to design a template like jdbcTemplate (Java EE, Spring)
my code is:
def DBV():
def templateFN(fn):
logging.basicConfig(level=logging.INFO)
log = logging.getLogger('DB')
conn = MySQLdb.connect(user='root',passwd='247326',db='lucky',charset="utf8",cursorclass=MySQLdb.cursors.DictCursor);
cursor = conn.cursor()
def wrap(data=None):
try:
return fn(cursor=cursor,data=data)
#conn.commit()
except Exception ,e:
conn.rollback()
log.error('%s, transaction rollback',e)
finally:
cursor.close()
conn.close()
return wrap
class DB():
#templateFN
def insertTest(self,cursor,data=None):
data = {
'field':'this is a test',
'name':'this is a name'
}
return cursor.execute('insert into test(field,name) values(%(field)s,%(name)s)',data)
return DB()
db = DBV()
print 'return value',db.insertTest(data="ok")
Traceback (most recent call last):
File "D:\WorkSpaces\Aptana Studio 3 Workspace\VLuck\src\com\test.py", line 164, in
print 'return value',db.insertTest(data="ok")
TypeError: wrap() got multiple values for keyword argument 'data'
but failed,how should I do it right
Here's a solution I came up with, inspired by another answer:
def connect_mysql(func):
# Assign value of 'self' to be default func
func.func_defaults = func.func_defaults[:-1] + (func,)
func._cnx = mysql.connector.connect(**CONFIG)
func._cursor = func._cnx.cursor()
return func
#connect_mysql
def test(data, self=None):
self._cursor.execute("SELECT %(c1)s", data)
print(self._cursor.fetchall())
test({'c1': 1})