Python NDB: pass variable as parameter - python

When I run the following code
class Userx(ndb.Model):
username = ndb.StringProperty()
password = ndb.StringProperty()
date = ndb.DateTimeProperty(auto_now_add=True)
class adduser(BaseHandler):
def get(self):
user=self.request.get("email")
o=Userx(parent=ndb.Key("users","key"),password="123",username=user)
o.put()
I get the error message
o=Userx(parent=ndb.Key("users","key"),password="123",username=user)
NameError: name 'user' is not defined

I don't see anything wrong with that Code Sample, maybe the problem is caused by another part? Indirectly maybe? For example, the following code, which is similar to yours, runs without any problem.
class myc1:
def __init__(self,y=0,q=1,t="Spam Eggs"):
print y,q,t
class myc2:
def get(self):
name1 = "Sweeney Todd"
myobj1 = myc1(q=5,t=name1)
myobj2 = myc2()
myobj2.get()
outputs 0 5 Sweeney Todd
Can you post more of your code?
(p.s I cannot write this as a comment since I don't have sufficient privilege)

Related

How can I pass data into a class in python?

I am using django to create a blog editing page. However, my struggles do not involve django, rather just python. I have a class:
class EditForm(forms.Form):
def __init__(self, initcontent):
self.initcontent = initcontent
title = forms.CharField(max_length=100, label='Post Title')
short_description = forms.CharField(widget=forms.Textarea(attrs={"rows":3, "cols":100}))
content = forms.CharField(widget=CKEditorWidget(), initial=Post.objects.get(pk=initcontent).content)
and I am initialising it like this:
form = EditForm()
form.initcontent = post.pk
however I get the error:
File "C:\Users\Rayyan Admin\Documents\GitHub\shaista-s-cooking-blog\blogger\forms.py", line 34, in EditForm
content = forms.CharField(widget=CKEditorWidget(), initial=Post.objects.get(pk=initcontent).content)
NameError: name 'initcontent' is not defined
How do i pass initcontent into the class?
Hi your indenting is off so I'm not sure if that's a mistake in formatting here or causing issues with your code.
Anyways I think what you want is:
class EditForm():
def __init__(self, initcontent):
self.initcontent = initcontent
form = EditForm(post.pk)
Whenever you make an instance of a class, you can pass your data into it if you have defined a constructor. That is the role of a constructor. In your case, you have defined a constructor with initcontent as a parameter. So you can do it like this -
form = EditForm(whatever you need to pass)
This will do.

Why do I need a value for self here?

Hey there I'm new to python and try to program a simple login module which salts a password
When I use this class I get the following error:
TypeError: salting() missing 1 required positional argument: 'password'
class Login():
def salting(self, username, password):
self.password = password
self.username = username
print(self.username + self.password)
Login.salting("user1","pw1")
My Only Solutions were to use Login.salting("","user1","pw1") with an empty string for self or calling self as username end reuse it like this, but I think that I ran in an error, can someone help me :D
But when I compare that with my previous code which was like this (I learned that with this code) - the error doesn't appear...
class car():
name = "BMW"
color = "red"
def redesign(self, color):
self.color = color
c = car()
print(c.name)
print(c.color)
c.redesign("blue")
print(c.color)
THANKS
salting is an object method, not a class method. Each object has its own username and password attributes. You need to create a Login object, and then call the method on that.
s = Login()
s.salting("user1", "pw2")
This is analogous to using c = car() in the second block of code.

Graphene Mutation error, fields must be a mapping (dict / OrderedDict)

I'm starting to wrap my head around with GraphQl/Graphene. I'm building a schema connected to a MongoDB. All seems to work so far except mutations. I've been following the example here and here without luck. Can someone point me towards what I'm doing wrong? Thanks in advance.
import graphene
class GeoInput(graphene.InputObjectType):
lat = graphene.Float(required=True)
lng = graphene.Float(required=True)
#property
def latlng(self):
return "({},{})".format(self.lat, self.lng)
class Address(graphene.ObjectType):
latlng = graphene.String()
class CreateAddress(graphene.Mutation):
class Arguments:
geo = GeoInput(required=True)
Output = Address
def mutate(self, info, geo):
return Address(latlng=geo.latlng)
class Mutation(graphene.ObjectType):
create_address = CreateAddress.Field()
class Query(graphene.ObjectType):
address = graphene.Field(Address, geo=GeoInput(required=True))
def resolve_address(self, info, geo):
return Address(latlng=geo.latlng)
schema = graphene.Schema(query=Query, mutation=Mutation)
The code above generates this error:
AssertionError: CreateAddress fields must be a mapping (dict /
OrderedDict) with field names as keys or a function which returns such
a mapping.
The problem is in the import.
I've had same issue when I used:
from graphene import ObjectType
I've found how to import it properly in next example from docs. Here it is:
from graphene_django.types import DjangoObjectType
The issue was with the version of graphene I had installed, installing graphene 2.0 solved the issue.
My problem was that I had declared all of my fields incorrectly. This is my Type:
class EventDateRangeType(DjangoObjectType):
class Meta:
model = EventDateRange
fields = ('start', 'end')
But my Model was:
class EventDateRange(models.Model):
event = models.ForeignKey(Event, on_delete=models.CASCADE)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
So start & end don't match start_time & end_time. Making them the same fixed my issue.
In your mutation:
Output = Address
Should be a graphene object:
Output = graphene.Field(Address)
Had a similar error for a class that inherited from "InputObjectType". The solution was to import "InputObjectType" from graphene instead of from graphql.type.tests.test_definition (don't know why it was imported from that library in the first place)
It can even happen if no output is specified in graphene.Mutation inheriting class.
But that is not case for DevilWarior.

Python, get the value of self.request.get() inside __init__

I wanted to get the values of self.request.get('foo') and etal everytime I create an instance of a class, so I decided to use __init__ constructor. Here's my code:
class archive(handler):
d = dict(title='',author= '')
def __init__(self):
self.d['title'] = self.request.get('title')
self.d['author'] = self.request.get('author')
class compose(handler):
def get(self):
self.render('compose.html')
def post(self):
a = archive()
My purpose is, to get rid the repetition of:
title = self.request.get('title')
author = self.request.get('author')
in every def post(self). But the problem is I get a NoneType error:
AttributeError: 'NoneType' object has no attribute 'get'
Obviously, self.request.get('title') returned None. I am just new with Python and Google Appengine.
Thank you guys.
This is how I managed to fix the problem:
class Archive(object):
d = dict(title='',author= '')
def load_d(self):
r = webapp2.get_request()
self.d['title'] = r.get('title')
self.d['author'] = r.get('author')
class Compose(Handler):
def get(self):
self.render('compose.html')
def post(self):
a = Archive()
a.load_d()
I assume you use webapp2.
Your init overrides the init of the webapp2 request handler (super). You can read in the webapp2 docs how to to this:
http://webapp-improved.appspot.com/guide/handlers.html#overriding-init
Take care when you use variables (self.variable) because you can also override variables of the request handler. You can use the request registry.

Python pass instance of itself as an argument to another function

I have a UserModel class that will essentially do everything like login and update things.
I'm trying to pass the instance of itself (the full class) as an argument to another function of another class.
For example: (obviously not the code, but you get the idea)
from Car import CarFactory
class UserModel:
def __init__(self,username):
self.username = username
def settings(self,colour,age,height):
return {'colour':colour,'age':age,'height':height}
def updateCar(self,car_id):
c = CarFactory(car_id, <<this UserModel instance>>)
So, as you can see from the very last line above I would like to pass an instance of UserModel to the CarData class, so when within the CarData class I can access the UserModel.settings(), however, I am unsure of the syntax. I could of course just do:
c = CarFactory(car_id,self.settings)
Any help would be grateful appreciated.
Thanks
c = CarFactory(car_id, self)
doesnt work?
on a side note it would be self.settings() not self.settings ... unless you define settings to be a property

Categories

Resources