syntax error when inserting into database [Google app engine] - python

I get a syntax error when trying to insert into a datastore, the exact same line of code worked in another project
B = db_Person(nafn='Alex')
Here is the rest of the code:
http://pastebin.com/bW37aUuT

def post(self):
q = db.Query(db_Person)
message = "Innsetning tokst"
in_kennitala = int(self.request.get('p_kennitala'))
in_nafn = self.request.get('p_nafn')
in_heimili = self.request.get('p_heimili')
in_postnumer = self.request.get('p_postnumer')
in_stadur = self.request.get('p_stadur')
in_land = self.request.get('p_land')
in_simi = int(self.request.get('p_simi'))
in_gsm = int(self.request.get('p_gsm') # <- missing right parenthesis
B = db_Person(nafn='Alex') # <- parser gets confused here
B.put()
template_values = {
'message': message
}
template = jinja_environment.get_template('breyta.html')
self.response.out.write(template.render(template_values))
This is the fixed code:
def post(self):
q = db.Query(db_Person)
message = "Innsetning tokst"
in_kennitala = int(self.request.get('p_kennitala'))
in_nafn = self.request.get('p_nafn')
in_heimili = self.request.get('p_heimili')
in_postnumer = self.request.get('p_postnumer')
in_stadur = self.request.get('p_stadur')
in_land = self.request.get('p_land')
in_simi = int(self.request.get('p_simi'))
in_gsm = int(self.request.get('p_gsm'))
B = db_Person(nafn='Alex')
B.put()
template_values = {
'message': message
}
template = jinja_environment.get_template('breyta.html')
self.response.out.write(template.render(template_values))

Related

Pulumi azure-native missing required property 'resourceGroupName'

in a pulumi script i get the following error running pulumi up
azure-native:sql:DatabaseSecurityAlertPolicy (sap_primary):
error: azure-native:sql:DatabaseSecurityAlertPolicy resource 'sap_primary' has a problem: missing required property 'resourceGroupName'
Here is the relevant part of the code:
resource_group = resources.ResourceGroup(
resource_name = <rg-name>,
tags={
<tags> # placeholder for the real tags
},
opts=pulumi.ResourceOptions(import_=<rg id>))
sql_server = sql.Server(
resource_name = str(app_stage) + '-' + str(app_key) + '-sql',
resource_group_name = resource_group.name,
location = resource_group.location,
administrator_login = sql_server_admin_user,
administrator_login_password = sql_server_admin_password,
version = sql_version,
tags = resource_group.tags,
identity = sql.ResourceIdentityArgs(type=sql.IdentityType.SYSTEM_ASSIGNED)
)
sql_database_primary = sql.Database(
resource_name = sql_database_name,
resource_group_name = resource_group.name,
location = resource_group.location,
server_name = sql_server.name,
sku = sql.SkuArgs(
name = 'GP_Gen5_2',
tier = sql_edition),
zone_redundant = sql_zone_redundancy,
tags = resource_group.tags,
)
database_security_alert_policy = sql.DatabaseSecurityAlertPolicy(
resource_name = 'sap_primary',
resource_group_name = sql_server.resource_group_name,
database_name = sql_database_name,
server_name = sql_server.name,
state = sql.SecurityAlertsPolicyState.ENABLED,
)
I don't understand why does it say resourceGroupName is missing but it is set as you can see. What am I missing?
To avoid questions like: Where is e.g. sql_server_admin_user coming from, they are set in the Pulumi.dev.yaml file and imported in the script like config.get('sql_server_admin_user')
sql_server.resource_group_name does not exist. Use resource_group.name instead.

onSnapshot() Firestore sending changes multiple times with Flask-Sockets

I'm trying to develop a web chat with Flask and Firestore. I set a flow to receive new messages from firestore (when something changes at the database) and send through websockets to UI. Something like that:
Python:
#sockets.route('/messages')
def chat_socket(ws):
message = None
def callback_snapshot(col_snapshot, changes, read_time):
with app.app_context():
Messages = []
for change in changes:
if change.type.name == 'ADDED':
Messages.append(change.document)
conversation = render_template(
'conversation.html',
Messages = Messages,
)
numberID = None
if len(col_snapshot) > 0:
for i in col_snapshot:
a = i
numberID = a.reference.parent.parent.id
response = json.dumps({
'conversation': conversation,
'numberID': numberID
})
ws.send(response)
while not ws.closed:
response = json.loads(ws.receive())
newNumberID = response['newNumberID'].strip()
query_snapshot = fn.GetMessages(newNumberID)
doc_watch = query_snapshot.on_snapshot(callback_snapshot)
if message is None:
continue
Javascript:
function messages(numberID) {
var scheme = window.location.protocol == "https:" ? 'wss://' : 'ws://';
var webSocketUri = scheme
+ window.location.hostname
+ (location.port ? ':'+location.port: '')
+ '/messages';
/* Get elements from the page */
var form = $('#chat-form');
var textarea = $('#chat-text');
var output = $('.messages');
var status = $('.messages');
var websocket = new WebSocket(webSocketUri);
websocket.onopen = function() {};
websocket.onclose = function() {};
websocket.onmessage = function(e) {
numberID = JSON.parse(e.data).numberID
conversation = JSON.parse(e.data).conversation
output.append(conversation);
if (numberID == null){
output.empty();
}};
websocket.onerror = function(e) {console.log(e);};
websocket.onopen = () => websocket.send(numberID);
};
The problem is: When I use col_snapshot as Messages, everything is ok besides I get the whole firestore Collection sent every time to the user when a message is sent. So it's totally not efficient. When I set callback only for changes, as described above, if I trigger the function more than one time, somehow I set multiple listeners for the same collection, so I get multiple "changes updates" in UI. How I can keep track of those listeners so I only set one listener per Collection?
As you can see from the documentation, you should only call GetMessages and on_snapshot once per document.
#sockets.route('/messages')
def chat_socket(ws):
message = None
def callback_snapshot(col_snapshot, changes, read_time):
with app.app_context():
# Rest of the function ...
ws.send(response)
response = json.loads(ws.receive())
numberID = response['newNumberID'].strip()
query_snapshot = fn.GetMessages(numberID)
doc_watch = query_snapshot.on_snapshot(callback_snapshot)
while not ws.closed:
newNumberID = response['newNumberID'].strip()
response = json.loads(ws.receive())
if newNumberID != numberID:
numberID = newNumberID
query_snapshot = fn.GetMessages(numberID)
doc_watch = query_snapshot.on_snapshot(callback_snapshot)

TypeError: Model constructor takes no positional arguments

While creating an answer for a question in the API (see code below), I got the following error:
TypeError: Model constructor takes no positional arguments
Can someone tell me how to solve this? I am using ndb model
import webapp2
import json
from google.appengine.ext import ndb
class AnswerExchange(ndb.Model):
answer=ndb.StringProperty(indexed=False,default="No Message")
class AnswerHandler(webapp2.RequestHandler):
def create_answer(self,question_id):
try:
query = StackExchange.query(StackExchange.questionId == question_id)
questions = query.fetch(1)
ans_json = json.loads(self.request.body)
answerObj = AnswerExchange(answer=ans_json["answer"])
answerObj.put()
questions.answerName=answerObj
questions.put()
except:
raise webapp2.exc.HTTPBadRequest()
class StackExchange(ndb.Model):
questionId=ndb.StringProperty(indexed=True)
questionName=ndb.StringProperty(indexed=False)
#answerID=ndb.StringProperty(indexed=True)
answerName=ndb.StructuredProperty(AnswerExchange,repeated=True)
class StackHandler(webapp2.RequestHandler):
def get_questions(self):
#p = self.request.get('p') #get QueryString Parameter
#self.response.write(p)
query = StackExchange.query()
questions = query.fetch(6)
self.response.content_type = 'application/json'
self.response.write(json.dumps([d.to_dict() for d in questions]))
def get_question(self, question_id):
query = StackExchange.query(StackExchange.questionId == question_id)
questions = query.fetch(1)
self.response.content_type = 'application/json'
self.response.write(json.dumps([d.to_dict() for d in questions]))
def create_question(self):
try:
question_json = json.loads(self.request.body)
# if id in dept_json:
questionNo = question_json["questionId"]
questionToUpdate = StackExchange.query(StackExchange.questionId == questionNo);
#print deptToUpdate.count()
if questionToUpdate.count() == 0:
question = StackExchange(questionId=question_json["questionId"], questionName=question_json["questionName"])
else:
question = questionToUpdate.get()
question.questionName = question_json["questionName"]
#key = dept.put()
question.put()
except:
raise webapp2.exc.HTTPBadRequest()
self.response.headers['Location'] = webapp2.uri_for('get_question', question_id=questionNo)
self.response.status_int = 201
self.response.content_type = 'application/json'
#self.response.write(json.dumps())
def create_answer(self,question_id):
#try:
question_json = json.loads(self.request.body)
questionNo = question_json["questionId"]
query = StackExchange.query(StackExchange.questionId == questionNo)
questions = query.fetch(1)
ans_json = json.loads(self.request.body)
answerObj = AnswerExchange(ans_json["answer"])
#answerObj.put()
#self.response.write(ans_json["answerName"])
questions.answerName = answerObj
questions.put();
#except:
# raise webapp2.exc.HTTPBadRequest()
def get_answer(self, question_id):
query = StackExchange.query(StackExchange.questionId == question_id)
questions = query.fetch(1)
self.response.content_type = 'application/json'
self.response.write(json.dumps([d.to_dict() for d in questions]))
app = webapp2.WSGIApplication([
webapp2.Route(r'/api/v1/questions/<question_id>', methods=['GET'], handler='api.StackHandler:get_question', name='get_question'),
webapp2.Route(r'/api/v1/questions', methods=['GET'], handler='api.StackHandler:get_questions', name='get_questions'),
webapp2.Route(r'/api/v1/questions', methods=['POST'], handler='api.StackHandler:create_question', name='create_question'),
webapp2.Route(r'/api/v1/questions/<question_id>/answers', methods=['POST'], handler='api.StackHandler:create_answer', name='create_answer'),
webapp2.Route(r'/api/v1/questions/<question_id>/answers', methods=['GET'], handler='api.StackHandler:get_answer', name='get_answer')
], debug=True)
Change,
answerObj = AnswerExchange(ans_json["answer"])
in create_answer method StackHandler class
to
answerObj = AnswerExchange(answer=ans_json["answer"])

DoesNotExist: [Model] matching query does not exist at id (ObjectId)

I am trying to query a unique document using its ObjectId. However the error comes up:
DoesNotExist: Route matching query does not exist
When, upon passing this to my view as request, it prints out the corresponding ObjectId in ObjectId typeform. Therefore there shouldn't be a problem with the line route_test = Route.objects.get(id=_id).
I have the following code:
views.py
def update(request):
if request.method == "POST":
_id = request.POST.get('_id',ObjectId())
print(_id)
route_id = request.POST.get('route_id','')
geometry = request.POST.get('geometry', '')
properties = request.POST.get('properties','')
#r = Route.objects.get(route_id='LTFRB_PUJ2616') --> I cannot use this
#because it has 5 instances (Not Unique)
#print (r["id"],r["properties"])
test = Route.objects.get(id = ObjectId('587c4c3b203ada19e8e0ecf6'))
print (test["id"], test["properties"])
try:
route_test = Route.objects.get(id=_id)
print(route_test)
Route.objects.get(id=_id).update(set__geometry=geometry, set__properties=properties)
return HttpResponse("Success!")
except:
return HttpResponse("Error!")
ajax
var finishBtn = L.easyButton({
id:'finish',
states: [{
icon:"fa fa-check",
onClick: function(btn){
selectedFeature.editing.disable();
layer.closePopup();
var editedFeature = selectedFeature.toGeoJSON();
alert("Updating:" + editedFeature.route_id);
$.ajax({
url: "/update/",
data: {id:editedFeature.id,
route_id: JSON.stringify(editedFeature.route_id),
geometry: JSON.stringify(editedFeature.geometry),
properties: JSON.stringify(editedFeature.properties)
},
type: 'POST'
});
}
model.py
from __future__ import unicode_literals
from mongoengine import *
class Route(Document):
type = StringField(required=True)
route_id = StringField(required=True)
geometry = LineStringField()
properties = DictField()
meta = {'collection':'routes'}
What should be done? Even the line test = Route.objects.get(id = ObjectId('587c4c3b203ada19e8e0ecf6')) where I directly supplied the incoming _id has the same error...

Syntax error with database search

I'm creating a product review website through web2py and have encountered difficulty whilst adding a search feature. Here's the code I have so far:
def index():
rows = db(db.reviews).select()
name_default = request.vars.name
body_default = request.vars.body
objects_default = request.vars.objects
form = SQLFORM.factory(
Field("Item Name", default = name_default),
Field("Body", default = body_default),
Field("Objects", default = objects_default),
formstyle = 'divs'
submit_button = "Search"
)
query = db.db1.id_user == auth.user_id
if form.process().accepted:
name = form.vars.name
body = form.vars.body
objects = form.vars.objects
count = db(query).count()
results = db(query).select(orderby=~db.db1.data)
msg = T("%s registers" % count)
return dict(form=form, msg=msg, results=results)
return locals()
The error I'm getting is a syntax error on line 23 character 28 (the submit_button = "Search" line).

Categories