no value for argument self in unbound method call - python

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.

Related

Create activities for an user with Stream-Framework

I'm trying to setup stream-framework the one here not the newer getstream. I've setup the Redis server and the environment properly, the issue I'm facing is in creating the activities for a user.
I've been trying to create activities, following the documentation to add an activity but it gives me an error message as follows:
...
File "/Users/.../stream_framework/activity.py", line 110, in serialization_id
if self.object_id >= 10 ** 10 or self.verb.id >= 10 ** 3:
AttributeError: 'int' object has no attribute 'id'
Here is the code
from stream_framework.activity import Activity
from stream_framework.feeds.redis import RedisFeed
class PinFeed(RedisFeed):
key_format = 'feed:normal:%(user_id)s'
class UserPinFeed(PinFeed):
key_format = 'feed:user:%(user_id)s'
feed = UserPinFeed(13)
print(feed)
activity = Activity(
actor=13, # Thierry's user id
verb=1, # The id associated with the Pin verb
object=1, # The id of the newly created Pin object
)
feed.add(activity) # Error at this line
I think there is something missing in the documentation or maybe I'm doing something wrong. I'll be very grateful if anyone helps me get the stream framework working properly.
The documentation is inconsistent. The verb you pass to the activity should be (an instance of?*) a subclass of stream_framework.verbs.base.Verb. Check out this documentation page on custom verbs and the tests for this class.
The following should fix the error you posted:
from stream_framework.activity import Activity
from stream_framework.feeds.redis import RedisFeed
from stream_framework.verbs import register
from stream_framework.verbs.base import Verb
class PinFeed(RedisFeed):
key_format = 'feed:normal:%(user_id)s'
class UserPinFeed(PinFeed):
key_format = 'feed:user:%(user_id)s'
class Pin(Verb):
id = 5
infinitive = 'pin'
past_tense = 'pinned'
register(Pin)
feed = UserPinFeed(13)
activity = Activity(
actor=13,
verb=Pin,
object=1,
)
feed.add(activity)
I quickly looked over the code for Activity and it looks like passing ints for actor and object should work. However, it is possible that these parameters are also outdated in the documentation.
* The tests pass in classes as verb. However, the Verb base class has the methods serialize and __str__ that can only be meaningfully invoked if you have an object of this class. So I'm still unsure which is required here. It seems like in the current state, the framework never calls these methods, so classes still work, but I feel like the author originally intended to pass instances.
With the help of great answer by #He3lixxx, I was able to solve it partially. As the package is no more maintained, the package installs the latest Redis client for python which was creating too many issues so by installation redis-2.10.5 if using stream-framework-1.3.7, should fix the issue.
I would also like to add a complete guide to properly add activity to a user feed.
Key points:
If you are not using feed manager, then make sure to first insert the activity before you add it to the user with feed.insert_activity(activity) method.
In case of getting feeds with feed[:] throws an error something like below:
File "/Users/.../stream_framework/activity.py", line 44, in get_hydrated
activity = activities[int(self.serialization_id)]
KeyError: 16223026351730000000001005L
then you need to clear data for that user using the key format for it in my case the key is feed:user:13 for user 13, delete it with DEL feed:user:13, In case if that doesn't fix the issue then you can FLUSHALL which will delete everything from Redis.
Sample code:
from stream_framework.activity import Activity
from stream_framework.feeds.redis import RedisFeed
from stream_framework.verbs import register
from stream_framework.verbs.base import Verb
class PinFeed(RedisFeed):
key_format = 'feed:normal:%(user_id)s'
class UserPinFeed(PinFeed):
key_format = 'feed:user:%(user_id)s'
class Pin(Verb):
id = 5
infinitive = 'pin'
past_tense = 'pinned'
register(Pin)
feed = UserPinFeed(13)
print(feed[:])
activity = Activity(
actor=13,
verb=Pin,
object=1)
feed.insert_activity(activity)
activity_id = feed.add(activity)
print(activity_id)
print(feed[:])

Overwriting a method from another module

I am working with jira-python and want to overwrite the existing method Issue.update() method. However, my code is never calling the modification.
from jira import JIRA
from jira.resources import Issue
class Issue(Issue):
def update(self):
print("overwritten")
super(Issue, self).update() # I also tried super().update()
jira = JIRA("...") # holds a reference to the JIRA instance
issues = jira.search_issues("") # holds a list of JIRA Issues
for issue in issues:
// I would expect this call to print "overwritten"
issue.update()
You can monkey-patch the method with a wrapper like this:
from jira.resources import Issue
def my_update(self):
print('overwritten')
original_update(self)
original_update = Issue.update
Issue.update = my_update

Why do I get TypeError: get() takes exactly 2 arguments (1 given)? Google App Engine

I have been trying and trying for several hours now and there must be an easy way to retreive the url. I thought this was the way:
#from data.models import Program
import basehandler
class ProgramViewHandler(basehandler.BaseHandler):
def get(self,slug):
# query = Program.all()
# query.filter('slug =', fslug)
self.render_template('../presentation/program.html',{})
Whenever this code gets executed I get this error on the stacktrace:
appengine\ext\webapp__init__.py", line 511, in call
handler.get(*groups)
TypeError: get() takes exactly 2 arguments (1 given)
I have done some debugging, but this kind of debugging exceeds my level of debugging. When I remove the slug from def get(self,slug) everything runs fine.
This is the basehandler:
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
class BaseHandler(webapp.RequestHandler):
def __init__(self,**kw):
webapp.RequestHandler.__init__(BaseHandler, **kw)
def render_template(self, template_file, data=None, **kw):
path = os.path.join(os.path.dirname(__file__), template_file)
self.response.out.write(template.render(path, data))
If somebody could point me in the right direction it would be great! Thank you! It's the first time for me to use stackoverflow to post a question, normally I only read it to fix the problems I have.
You are getting this error because ProgramViewHandler.get() is being called without the slug parameter.
Most likely, you need to fix the URL mappings in your main.py file. Your URL mapping should probably look something like this:
application = webapp.WSGIApplication([(r'/(.*)', ProgramViewHandler)])
The parenthesis indicate a regular expression grouping. These matched groups are passed to your handler as arguments. So in the above example, everything in the URL following the initial "/" will be passed to ProgramViewHandler.get()'s slug parameter.
Learn more about URL mappings in webapp here.
If you do this:
obj = MyClass()
obj.foo(3)
The foo method on MyClass is called with two arguments:
def foo(self, number)
The object on which it is called is passed as the first parameter.
Maybe you are calling get() statically (i.e. doing ProgramViewHandler.get() instead of myViewHandlerVariable.get()), or you are missing a parameter.

importing class and its function from another file

I am having little problem with importing classes in python. My work flow goes like this
index.py
class Template:
def header():
def body():
def form():
def footer():
display.py
I want to call function header(), body() and footer () in my display.py page. Will anyone make me clear about this issue in python. Thanks for your concern.
Index file--- [Index.py][1]
[1]: http://pastebin.com/qNB53KTE and display.py -- "http://pastebin.com/vRsJumzq"
What have you tried? The following would be normal way of using methods of Template class after import.
from index import Template
t = Template()
t.header()
t.body()
t.footer()
ETA: at the end of your index.py file (lines 99-105) you're calling all the functions from the above-defined Template class. That's why you're seeing duplicates.
At the bottom of your index file you create a HtmlTemplate object and call all the methods on it. Since this code is not contained in any other block, it gets executed when you import the module. You either need to remove it or check to see if the file is being run from the command line.
if __name__ == "__main__":
objx=HtmlTemplate()
objx.Header()
objx.Body()
objx.Form()
objx.Footer()
objx.CloseHtml()
Edit: Okay, I see what your problem is, given your code.
You're calling the following:
## Calling all the functions of the class template with object (objx)
objx=HtmlTemplate()
objx.Header()
objx.Body()
objx.Form()
objx.Footer()
objx.CloseHtml()
And then in your display.py:
t = HtmlTemplate()
t.Header()
t.Body()
See how Body() gets called twice?
As a footnote, you should use lowercase for method names, and Capital words for classes as you're doing now. It's a good convention. I greatly recommend it.
You should simply construct the object once in display.py and call all the methods.
I am not sure if I understand you correctly, but I believe you are asking how to import the template class in another script. The import statement is what you need:
from index import template
foo = template()
foo.header()
foo.body()
foo.footer()
You have the following code at the top and the bottom of index.py:
cgitb.enable()
print 'Content-type: text/html\n\n'
print "<link rel=\"stylesheet\" type=\"text/css\" href=\"css/msa.css\" >"
# [...]
## Calling all the functions of the class template with object (objx)
objx=HtmlTemplate()
# [...]
objx.CloseHtml()
This will be called each time you import index.
To prevent this happening, put it in a block thus:
if __name__ == '__main__':
cgitb.enable()
print 'Content-type: text/html\n\n'
print "<link rel=\"stylesheet\" type=\"text/css\" href=\"css/msa.css\" >"
# [...]
## Calling all the functions of the class template with object (objx)
objx=HtmlTemplate()
# [...]
objx.CloseHtml()
...or better still put this code functions that can be called from elsewhere.
The below solution worked for me:
class1(unittest.TestCase):
def method1(self)
class2(unittest.TestCase):
def method2(self):
instance_name = class1("method1")
instance_name.method1()

Importing Model / Lib Class and calling from controller

I'm new to python and pylons although experienced in PHP.
I'm trying to write a model class which will act as a my data access to my database (couchdb). My problem is simple
My model looks like this and is called models/BlogModel.py
from couchdb import *
class BlogModel:
def getTitles(self):
# code to get titles here
def saveTitle(self):
# code to save title here
My controller is called controllers/main.py
import logging
from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to
from billion.lib.base import BaseController, render
log = logging.getLogger(__name__)
from billion.model import BlogModel
class MainController(BaseController):
def index(self):
return render('/main.mako')
In my index action, how do I access the method getTitles() in BlogModel?
I've tried
x = BlogModel()
x.getTitles()
But i get
TypeError: 'module' object is not callable
Also
BlogModel.getTitles() results in
AttributeError: 'module' object has no attribute 'getTitles'
Is this down to the way I'm including the class ? Can someone tell me the best way to do this ?
thanks
x = BlogModel.BlogModel()
Or, more verbosely:
After you did the import, you have an object in your namespace called 'BlogModel'. That object is the BlogModel module. (The module name comes from the filename.) Inside that module, there is a class object called 'BlogModel', which is what you were after. (The class name comes from the source code you wrote.)
Instead of:
from billion.model import BlogModel
You could use:
from billion.model.BlogModel import BlogModel
then your
x = BlogModel()
would work.

Categories

Resources