I'm working with Python to create a Google App Engine application.To test my app, i am using html forms to enter data.
In my form i have a line:
<tr><td>Age</td><td><input type="number" size="10" name="age"/></td></tr>
and in my model class, a property defined like this:
class Person(ndb.Model):
...
age = ndb.IntegerProperty()
when i test my app locally it displays the form but on entering a value for age, i get a BadValueError: Expected integer, got u '23' message.Posting image because i do not know how to copy command prompt text.I hope it's clear enough.
Edit: This is how the data is been passed from html form.
# Data taken from the registration form (above) is used to
# create a new member.
class PersonHandler(webapp2.RequestHandler):
def post(self):
# need to check this member-name does not exist
name = self.request.get('name')
callback = self.request.get('callback')
member = Member.get_by_id(name)
if member: # This member name already exists.
self.error(409) # This is the HTTP status code for 'unable to process due to conflict'
else:
...
a = self.request.get("age")
member = Member(age=a,...)
member.put()
if callback:
self.response.write(callback + '(' + member.toJSON + ')')
else:
self.response.write(member.toJSON())
Can someone tell me what am doing wrong?
You simply need to convert the retrieved value to an integer:
...
else:
...
a = int(self.request.get("age"))
Related
I am learning how to write tests in Python + Selenium based on Page Object.
In general, the test code itself looks like this:
pytest.mark.parametrize("first_name", [double_first_name, empty_form, long_first_name],
ids=["double_first_name", "empty_form", "long_first_name"])
def test_reg_form_name(browser, first_name):
passport_reg_page = RegForm(browser)
passport_reg_page.go_to_site()
passport_reg_page.reg_page()
passport_reg_page.reg_first_name(first_name)
passport_reg_page.reg_button()
passport_reg_page = RegFormExpectations(browser)
passport_reg_page.reg_expect_name()
assert rt_passport_reg_page.reg_expect_name()
browser.save_screenshot('screenshots/test_reg_1.png')
How to write and call a function so that the name of the test + parameter ids is automatically added to the name of the screenshot, or at least the name of the test + the number of each parameter run? For example:
browser.save_screenshot(f'screenshots/{"test_reg_form_name"}+"_"+{"ids"}.png')
or
browser.save_screenshot(f'screenshots/{"test_reg_form_name"}+"_"+{"001,002,003..."}.png')
I've been proposed to try:
def test_name(self, request):
testname = request.node.name
return testname
but got notice "Method 'test_name' may be 'static'"
Also the next method helps to get def name but I see no sense to write its name for further getting it:
browser.save_screenshot(f'screenshots/{test_reg_page.__name__}_1.png')
This is my UI
End user can able to update Summary or my_story one at a time, This is my endpoint URL http:localhost:3000/api/account/profile, once user update any one of the field, the URL will work
This is Request payload for summary field
If the user update the Summary field the above endpoint URL will work.
This is Request payload for my_story field
If the user update the my_story field the above endpoint URL will work.
My code(Once the user update anyone of the field. I want to check which field is updated, for this how can I check whether the user is updated Summary or my_story,after accessing the field I want to sanitize the field and send it to response below one is my code):
from lxml.html import clean
def account_update():
data = json.loads(request.data)
cleaner = clean.Cleaner()
if data['other_details']['summary']:
clean_overview = (data['other_details']['summary'])
sanitized_html = cleaner.clean_html(clean_overview)
else:
clean_overview = (data['other_details']['my_story'])
sanitized_html = cleaner.clean_html(clean_overview)
return jsonify({"account": data})
Guys , in the above code I am getting the request payload as data, after that I am accessing the summary and my_story fields as data['other_details']['summary'] and data['other_details']['summary'], here I wrote if condition to check if the user update summary field if condition will work suppose user update my_story field it will goes to else part, but in my case if I update my_story field getting error.
Error:
if data['other_details']['summary']:
KeyError: 'summary'
NOTE:
Sanitizing the field is working fine (I mean cleaner = clean.Cleaner() and sanitized_html = cleaner.clean_html(clean_overview), I just want to know which field the user is updating. Please help me guys.
Most likely, the request.data doesn't always have the summary field in data['other_details'].
This means, you have to check for it in you if-else block before trying to access it.
Best to check for other_details as well.
Here is one way of doing this:
from lxml.html import clean
def account_update():
data = json.loads(request.data)
cleaner = clean.Cleaner()
if 'other_details' in data:
other_details = data['other_details']
if 'summary' in other_details:
clean_overview = other_details['summary']
sanitized_html = cleaner.clean_html(clean_overview)
elif 'my_story' in other_details:
clean_overview = other_details['my_story']
sanitized_html = cleaner.clean_html(clean_overview)
return jsonify({"account": data})
What i see your program just can't find summary atribute.
Solution 1
Im not sure this will work but function getattr() can help you.
Change this line
data['other_details']['summary']
To this
getattr(getattr(data,'other_details'),'summary', False)
Here you can learn more about getattr()
What is getattr() exactly and how do I use it?
Solution 2
Just use some try: and except:
I'm trying to get a field from openERPs mail_message model using python code which is executed in a server action (so its not a module where I can debug! I cannot even print in this state) (when a new eMail is being fetched) but I am unable to get anything useful from it.
Basicly when someone is throwing me a email, a new Task is created by openERP. But the newely created ticket is not connected to the user which send me the mail.
When a new email is fetched, this server action gets executed.
In a table called mail_message you can then find the email (+ author_id, + email, + res_id (which is the id of the created Task), therefore I'd like to fetch the author_id from that table.
(A query would look like this:
SELECT author_id FROM mail_message WHERE type = 'email' AND res_id = '<Task.id>')
This is my current code
#Initialize object. That one points to the mail_message model.
mailMessage_obj = self.pool.get('mail.message')
#Created Id in project_task
myId = object.id
#browse whole object with that id
#message = mailMessage_obj.browse(cr,uid,[myId])
#Select field where
messageIds = mailMessage_obj.search(cr,uid,[('type','=','email'),('res_id','=',myId)],context=context)
if messageIds:
#messageRecord = mailMessage_obj.browse(cr,uid,[myId],context=context)
#object.write({'partner_id':messageRecord.author_id.id})
res = mailMessage_obj.read(messageIds, ['author_id'])
partnerId = res[0]
#Author id
#partnerId = message[0]['author_id']
#partnerId = message.author_id
#res = [(r['id'], r['author_id']) for r in messageRecord]
#partnerId = res
#partnerId = 259866
object.write({'partner_id':partnerId})
I dont know how to get my hands on the author_id properly. If I hardcode a ID and let it write to the database (last two lines) It'll work just fine, but I cant hardcode a users id. ;)
Could someone explain to me how its done correctly?
I dont know whether I should use .browse or .read or something else..
I think you have an error on you python method.
you wrote :
res = mailMessage_obj.read(messageIds, ['author_id'])
partnerId = res[0]
But read() method returns here a list of dict (because messageIds is a list). Then, you have not specified the field you wanted to retrieve from res variable, and finally, as author_id is a many2one, it returns something like this : (2, 'myusers').
You should have done :
res = mailMessage_obj.read(cr, uid, messageIds, ['author_id'])
partnerId = res[0]['author_id'][0]
Hope i helped you,
Greatings
I have the following Django Model:
class State(models.Model):
name = models.CharField(max_length=80,null=False)
latitude = models.CharField(max_length=80,null=False)
longitude = models.CharField(max_length=80,null=False)
def __unicode__(self):
return self.name
In my views.py file I've created the following method:
def getCoords(request):
if request.is_ajax():
if request.method == 'POST':
try:
state = request.POST['state'] #receives the state from JS
stateInstance = State.objects.get(name=state)
stateLat = stateInstance.latitude
stateLong = stateInstance.longitude
data = {"lat" : stateLat, "long" : stateLong}
except State.DoesNotExist:
return HttpResponse("No record")
return HttpResponse(simplejson.dumps(data)) #returns json
So I'm sending this method a param through ajax, let's say "California". The state variable gets the value (I have proved that) but the query doesn't get executed, it returns the query doesn't match message. I've tried with the following as well:
state = request.POST['state']
if state == 'California':
return HttpResponse("Yes!")
else:
return HttpResponse(state)
When this snippet returns the state it displays California which means state's value is correct but the query is not executed properly. I don't know what's going on. Any thoughts?
Make sure you're connecting to the correct database in your settings.py. Make sure the record actually does exist with plain old SQL.
SELECT * FROM [app_name]_state WHERE name = 'California';
Also, try it from the Django shell. python manage.py shell
>>> from [app_name].models import State
>>> s = State.objects.get(name='California')
>>> s
<State: California>
Make sure that what is actually being sent is sent as POST, and not accidentally a GET variable in the URL. Also, make sure that the post variable has no extra characters and that it is actually valid. A decent way to do that is to just print it to the console, or if AJAX, with Firebug.
# Single quotes added so you can see any extra spaces in the console
print "'%s'" % state
i have the following model in google app engine:
class CustomUsers(db.Model):
cuid = db.StringProperty()
name = db.StringProperty()
email = db.StringProperty()
bday = db.StringProperty()
now given a cuid i just want to check if he is present in the high replication data store.
in my views i write the following, but eventually get an 500 error:
usr_prev = CustomUsers.all().filter('cuid =', request.POST['id'])
if(not usr_prev):
logging.info("this user does not exist")
else:
logging.info("user exists")
but this gives me an error. How shall i do it?
(Do not consider any importing issues.)
"500 errors" don't exist in isolation. They actually report useful information, either on the debug page or in the logs. I'd guess that your logs show that request.POST has no element id, but that is just a guess.
I noticed that you have assigned a query object to usr_prev. You need to execute the query. I think Query.count(1) function should do it.
However, this may not be related to the 500 error.
you can go like this to see:
query = Users.all()
cnt = query.filter('id =', user_id).count()
logging.info(cnt)
return int(cnt)
once this is done, seems you are using django with app engine, as per the error you are not returning string response. you might want to return
return HttpResponse("1") instead of return HttpResponse(1)