I'm new to Python. I can't understand why a variable is None at a certain point in my code:
class UsersInRoom(webapp.RequestHandler):
def get(self):
room_id = self.request.get("room_id")
username = self.request.get("username")
UserInRoom_entities = UserInRoom.gql("WHERE room = :1", room_id).get()
if UserInRoom_entities:
for user_in_room in UserInRoom_entities:
if user_in_room.username == username:
user_in_room.put() # last_poll auto updates to now whenenever user_in_room is saved
else:
user_in_room = UserInRoom()
user_in_room.username = username
user_in_room.put()
// error here, on line 160
UserInRoom_entities = []
UserInRoom_entities.append(user_in_room)
# name is `user_at_room` intead of `user_in_room` to avoid confusion
usernames = [user_at_room.username for user_at_room in UserInRoom_entities]
self.response.out.write(json.dumps(usernames))
The error is:
Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 507, in __call__
handler.get(*groups)
File "path\to\chat.py", line 160, in get
AttributeError: 'NoneType' object has no attribute 'append'
How is this possible? I'm setting UserInRoom_entities = [] immediately before that call. Or is something else the None in question?
UPDATE: This code works:
class UsersInRoom(webapp.RequestHandler):
def get(self):
room_id = self.request.get("room_id")
username = self.request.get("username")
UserInRoom_entities = UserInRoom.gql("WHERE room = :1", room_id).get()
if UserInRoom_entities:
for user_in_room in UserInRoom_entities:
if user_in_room.name == username:
user_in_room.put() # last_modified auto updates to now whenenever user_in_room is saved
else:
user_in_room = UserInRoom(room=Key(room_id), name=username)
user_in_room.put()
UserInRoom_entities = []
UserInRoom_entities.append(user_in_room)
# name is `user_at_room` intead of `user_in_room` to avoid confusion
usernames = [user_at_room.name for user_at_room in UserInRoom_entities]
self.response.out.write(json.dumps(usernames))
class ChatRoom(db.Model):
name = db.StringProperty()
last_modified = db.DateTimeProperty(auto_now=True)
message_contents = db.StringListProperty()
message_users = db.StringListProperty()
class UserInRoom(db.Model):
room = db.ReferenceProperty(ChatRoom)
name = db.StringProperty()
last_modified = db.DateTimeProperty(auto_now=True)
Since it appears that my comment to the question had the answer to this, I'll repeat it as an answer, with the hope of gaining some reputation points:
Is the UserInRoom instance initialized properly? I am not familiar with the GAE data model, but I could imagine that the put() ing the instance would require that the room attribute was set, if there is a relationship between UserInRoom and Room (assuming a Room class exists).
To make sure that you're not the one raising exception, you can do something like:
UserInRoom_entities = []
# raised? then your .append is missing otherwise something else is wrong
UserInRoom_entities.append
UserInRoom_entities.append(user_in_room)
Related
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.
Im trying to understand why I cannot access the methods on an object that is instantiated inside of a class. For example i'm attempting to build a script that utilizes the python-pptx library and I want to wrap the entire slide creation within a class to abstract it and make it a bit more reusable based on my configuration.
class Builder():
def __init__(self, template='template.pptx', output_file='out.pptx'):
self.cust_name = ''
self.author = ''
self.job_title = ''
self.present_date = ''
self.assessment_type = ''
self.template = template
self.agenda = ['Overview','Resources']
self.outfile = output_file
self.prs = Presentation('template.pptx') <--- This is what im referring to.
def addAgendaSlide(self):
agenda_slide = self.prs.add_slide(self.prs.slide_layouts[AGENDA]) <-- When trying to access this
agenda_slide.shapes.title.text = 'Agenda'
agenda_slide.placeholders[10].text = 'A test Agenda slide'
agenda_slide.placeholders[15].top = STANDARD_TOP
agenda_slide.placeholders[15].left = STANDARD_LEFT
agenda_slide.placeholders[15].width = 8229600
agenda_slide.placeholders[15].height = 4572000
for para in self.agenda:
p = agenda_slide.placeholders[15].text_frame.add_paragraph()
p.text = para
Traceback (most recent call last):
File "test.py", line 19, in <module>
test.addAgendaSlide()
File "/dev/pythonpptx/DocMaker/Slides.py", line 89, in addAgendaSlide
agenda_slide = self.prs.add_slide(self.prs.slide_layouts[AGENDA])
AttributeError: 'Presentation' object has no attribute 'add_slide'
If I use the same bits of code outside the class it works fine. I do have other methods in the class that are fine, it seems to be my implementation of the Presentation() bit that is messing me up.
The following works fine:
prs = Presentation('template.pptx')
agenda_slide = prs.slides.add_slide(prs.slide_layouts[AGENDA])
agenda_slide.shapes.title.text = 'Agenda'
agenda_slide.placeholders[15].top = STANDARD_TOP
agenda_slide.placeholders[15].left = STANDARD_LEFT
agenda_slide.placeholders[15].width = 8229600
agenda_slide.placeholders[15].height = 4572000
prs.save('out.pptx')
I think your problem is you are forgetting to add slides as follows:
agenda_slide = self.prs.slides.add_slide(self.prs.slide_layouts[AGENDA])
instead of
agenda_slide = self.prs.add_slide(self.prs.slide_layouts[AGENDA])
I have the following functions, that are working within the boundaries on the Python script
The loop_vcenters function will return a dictinary with cluster: host
subs_per_socket function will return the number of sockets for esx
def loop_vcenters(vcenters):
#------------------------- connect to vcenter ----------------------------------------
si = SmartConnect(host = vcenters,user = 'username',pwd = 'password' ,sslContext=context)
# disconnect from vcenter one done
atexit.register(Disconnect, si)
#get the object content from vcenter
content = si.RetrieveContent()
#list clusters
cluster_host_dic_list=[]
cluster_name = ""
for cluster_obj in get_obj(content, vim.ComputeResource):
cluster=cluster_obj.name
hosts=[]
for host in cluster_obj.host:
hosts.append(host.name)
#create dictinary ,key=cluster value=esx
cluster_dic={cluster:hosts}
cluster_host_dic_list.append(cluster_dic)
return cluster_host_dic_list
def subs_per_socket(host):
shost = content.searchIndex.FindByDnsName(dnsName=host, vmSearch=False)
socket_count = shost.summary.hardware.numCpuPkgs
sub_per_socket = socket_count/2
return sub_per_socket
I want to put both functions into a class, but I cannot figure out how
class loop_vcenters:
def hosts_dic(self,name):
si = SmartConnect(host = vcenters,user = 'username',pwd = 'password' ,sslContext=context)
atexit.register(Disconnect, si)
content = si.RetrieveContent()
cluster_host_dic_list=[]
cluster_name = ""
for cluster_obj in get_obj(content, vim.ComputeResource):
cluster=cluster_obj.name
hosts=[]
for host in cluster_obj.host:
hosts.append(host.name)
cluster_dic={cluster:hosts}
cluster_host_dic_list.append(cluster_dic)
return cluster_host_dic_list
I am unable to get the host dictionary like the loop_vcenters function returned.
d = loop_vcenters('vcenters')
Traceback (most recent call last):
File "", line 1, in
File "", line 5, in __init__
NameError: global name 'vcenters' is not defined
How can I add the subs_per_socket(host) function to the class?
d = loop_vcenters('vcenters')
You are calling the class loop_vcenters with an argument when no init is defined.
File "", line 5, in __init__
NameError: global name 'vcenters' is not defined
If you want to pass the argument to host_dic, you should be calling
d = loop_vcenters.host_dic('vcenters')
which will return cluster_host_dic_list to the variable d.
To add subs_per_socket(host), just define it under the class just as you did the other function.
I'm trying to get the names of my top 3 artists of last week with pylast (https://github.com/pylast/pylast) but I run into an error or get I get None as a result and I don't see what I'm doing wrong. pylast is a Python interface to Last.fm.
My code:
import pylast
API_KEY = ""
API_SECRET = ""
username = ""
password_hash = pylast.md5("")
network = pylast.LastFMNetwork(api_key=API_KEY, api_secret=API_SECRET, username=username, password_hash=password_hash)
user = network.get_authenticated_user();
weekly_artists = user.get_weekly_artist_charts();
# Keep the first three artists.
del weekly_artists[3:]
# Print the artist name and number of songs(weight).
for weekly_artist in weekly_artists:
artist,weight = weekly_artist
print (artist.get_name())
print (artist.get_correction())
artist.get_name() returns
None
artist.get_correction() returns
Traceback (most recent call last):
File "G:\projects\python\lastfm_weekly\lastfm-weekly.py", line 28, in <module>
print (artist.get_correction())
File "C:\Users\..\Python\Python36-32\lib\site-packages\pylast\__init__.py", line 1585, in get_correction
self._request(self.ws_prefix + ".getCorrection"), "name")
File "C:\Users\..\Python\Python36-32\lib\site-packages\pylast\__init__.py", line 1029, in _request
return _Request(self.network, method_name, params).execute(cacheable)
File "C:\Users\..\Python\Python36-32\lib\site-packages\pylast\__init__.py", line 744, in __init__
network._get_ws_auth()
AttributeError: 'str' object has no attribute '_get_ws_auth'
What am I doing wrong?
Here is a quick and dirty solution, i'm sure someone will provide something better but i just installed the package to test and it works.
network = pylast.LastFMNetwork(api_key=API_KEY, api_secret=API_SECRET)
artists = network.get_top_artists()
del artists[:3]
for i in artists:
artist, weight = i
print('Artist = {}. Weight = {}'.format(artist, weight))
I'm not really familiar with the package, I just installed it to help out with this but I do wonder what "get_name()" and "get_correction()" are as they're not in your provided code.
If they're not functions you created / are defined within your code then I'd look there for the problem.
Also, you're authenticating the user but the documentation explicitly states you don't need to unless you're writing data.
I am trying to write a CSV helper that reads the CSV file and updates or creates fields in the model. The create_or_update query is working fine, but it is only creating not updating. On changing the create_or_update to update it throws an error. The code of the CSV helper is :
def insert_books_from_dictionary(data):
category, created = Category.objects.update_or_create(name=data['category'])
sub_category = None
if data['sub_category'].decode('utf-8') != '':
sub_category, created = SubCategory.objects.update_or_create(name=data['sub_category'], category=category)
publisher, created = Publisher.objects.update_or_create(name=data['publishers'])
# convert strings to float
# ToDo : Fix constraints and create a function
# to handle data check and conversion
try:
price = float(data['mrp_price'])
except ValueError:
price = 0.0
pass
try:
pages = float(data['pages'])
except ValueError:
pages = None
pass
isbn_13_str = str(data['isbn_13'])
isbn_10_str = str(data['isbn_10'])
image_url_str = str(data['image_url'])
binding = 1 if data['binding'] == 'Hardboard' else 2
book, created = Book.objects.update(title=data['title'],description=data['description'], pages=pages, binding=binding, price=price, category=category,sub_category=sub_category, edition_and_year=data['edition_and_year'],
isbn_10=isbn_10_str, isbn_13=isbn_13_str,image_url=image_url_str)
book.publishers.add(publisher)
authors = re.split(",", data['authors'].decode('utf-8'))
for author in authors:
author, created = Author.objects.update_or_create(name=author.strip())
book.authors.add(author)
return dict(book_id=book.id)
It throws the following error:
Traceback (most recent call last):
File "common/util/upload.py", line 18, in <module>
uploadbooks = book_upload(old_file, newfile)
File "common/util/upload.py", line 12, in book_upload
insert_seller_books_from_dictionary(req_data)
File "/home/subhajit/textnook/common/util/csv_helper.py", line 132, in insert_seller_books_from_dictionary
book_id = insert_books_from_dictionary(data)
File "/home/subhajit/textnook/common/util/csv_helper.py", line 167, in insert_books_from_dictionary
isbn_10=isbn_10_str, isbn_13=isbn_13_str,image_url=image_url_str)
TypeError: 'long' object is not iterable
On changing update to create the error is no more. How do i resolve this issue?
in
book, created = Book.objects.update(title=data['title'],description=data['description'], pages=pages, binding=binding, price=price, category=category,sub_category=sub_category, edition_and_year=data['edition_and_year'],
isbn_10=isbn_10_str, isbn_13=isbn_13_str,image_url=image_url_str)
you are using update, not update_or_create
Book.objects.update updates only and returns the number of rows affected, which is the 'long' object is not iterable python complains about, since it has to assign its elements to the tuple book, created