i have a payload as shown below which is stored in mongodb
{
"_id" : ObjectId("5865fbf5558b670ac091c81e"),
"sensors" : [
{
"sensorStatus" : "green ",
"sensorName" : "s1"
},
{
"sensorStatus" : "red ",
"sensorName" : "s2"
}
],
"camera" : [
{
"cameraName" : "cam1",
"cameraStatus" : "live"
},
{
"cameraName" : "cam2",
"cameraStatus" : "live"
}
],
"checkpoints" : [
{
"checkPointName" : "chk1"
}
]
}
trying to write route to display this data as shown below
#gateway_bp.route('/gateway',methods=['GET'])
def list_gateWay():
gateways = Gateway.query.all()
print gateways
return Response(json.dumps(gateways), mimetype='application/json')
i am getting the error has
TypeError: <app.model.canvasmodel.Gateway object at 0x02E99D10> is not JSON serializable
the schema is as shown below
from app.dbconfig.extensions import db
class Sensors(db.Document):
sensorName = db.StringField()
sensorStatus = db.StringField()
class Camera(db.Document):
cameraName = db.StringField()
cameraStatus = db.StringField()
class Checkpoints(db.Document):
checkPointName = db.StringField()
class Gateway(db.Document):
sensors = db.ListField(db.DocumentField(Sensors), db_field='sensors')
camera = db.ListField(db.DocumentField(Camera), db_field='camera')
checkpoints = db.ListField(db.DocumentField(Checkpoints), db_field='checkpoints')
please help to correct the get request thanks
Related
I'm trying to get my Flask server to update to a Mongo Atlas DB on request. When a request is passed with the required arguments, it will post to a Discord webhook then attempt to update DB values.
Example: Going to https://(redacted for privacy)/(redacted for privacy)?iid=123&username=wow&price=22 with JUST the webhook code (doesn't touch DB) will do this:
(sent to discord webhook) and give a success message (outputs as 200 in the console).
But when I enable the DB code, the same link will through a 500 error. Anything I can do? The console outputs as;
balance = mycol.find_one({"UserID": uid})['balance']
TypeError: 'NoneType' object is not subscriptable
I don't understand why this won't work. Here's the code that works, but only posts to the webhook (commented stuff is DB related):
#balance = mycol.find_one({"UserID": uid})['balance']
#res = mycol.find_one({"UserID": uid})
#newvalues = { "$set": { "UserID": uid, "balance": int(balance) + int(cashback_amt)} }
#mycol.update_one(res, newvalues)
img_url = f"https://www.roblox.com/bust-thumbnail/image?userId={uid}&width=420&height=420&format=png"
data = {
"content" : "**New purchase!**",
"username" : "robate"
}
data["embeds"] = [
{
"description" : f"**ItemID**: `{item_id}`\n**Item Price**: `{price}`\n**Item Cashback**: `{cashback_amt}`",
"title" : "New purchase made",
"color": 65311,
"thumbnail": {"url": img_url}
}
]
result = requests.post(purclog, json = data)
return jsonify({"res": True})
And the non-working DB included code:
balance = mycol.find_one({"UserID": uid})['balance']
res = mycol.find_one({"UserID": uid})
newvalues = { "$set": { "UserID": uid, "balance": int(balance) + int(cashback_amt)} }
mycol.update_one(res, newvalues)
img_url = f"https://www.roblox.com/bust-thumbnail/image?userId={uid}&width=420&height=420&format=png"
data = {
"content" : "**New purchase!**",
"username" : "robate"
}
data["embeds"] = [
{
"description" : f"**ItemID**: `{item_id}`\n**Item Price**: `{price}`\n**Item Cashback**: `{cashback_amt}`",
"title" : "New purchase made",
"color": 65311,
"thumbnail": {"url": img_url}
}
]
result = requests.post(purclog, json = data)
return jsonify({"res": True})
Any help is severely appreciated. Have a good day!
EDIT: The UserID is defined here:
try:
uid = requests.get(f"https://api.roblox.com/users/get-by-username?username={username}").json()['Id']
except:
return
balance = mycol.find_one({"UserID": uid})['balance']
I am trying to update the value of project['submission']['status'] to queued for each matching version as below but running into a compilation error,any pointers on how to fix it is really appreicated?
from pymongo import MongoClient
from bson.objectid import ObjectId
import os,pymongo
dbuser = os.environ.get('muser', '')
dbpass = os.environ.get('mpwd', '')
uri = 'mongodb://{dbuser}:{dbpass}#machineip/data'.format(**locals())
client = MongoClient(uri)
db = client.data
collection = db['test']
print db.version
cursor = collection.find({})
cursor = collection.find({})
for document in cursor:
if document['version'] == '9.130.39.0.32.6.1':
for project in document['projects']:
print project
print project['name']
print project['_id']
id = project['_id']
print project['submission']['status']
if project['submission']['status'] != 'queued':
print "Inside Update.."
#project['submission']['status'] = 'queued'
collection_projects = document['projects']
#print collection_projects
for project in collection_projects:
project.update(
{ "_id": ObjectId(id) },
{
"$set": {
"sanity": "queued"
}
})
Document:
{
"_id" : ObjectId("5a95a1c32a2e2e0025e6d6e2"),
"status" : "Submitting",
"sanity" : "none",
"version" : "9.130.39.0.32.6.1",
"requestTime" : ISODate("2018-02-27T18:21:55.764Z"),
"projects" : [
{
"name" : "BCMFurm_4364_B2_ekans",
"_id" : ObjectId("5a95a1c32a2e2e0025e6d6eb"),
"submission" : {
"status" : "passed", --> this status should change to "queued"
"system" : "machine.com"
}
},
{
"name" : "BCMFurm_4364_B2_sid",
"_id" : ObjectId("5a95a1c32a2e2e0025e6d6ea"),
"submission" : {
"status" : "passed",--> this status should change to "queued"
"system" : "machine.com"
}
},
{
"name" : "BCMFurm_4364_Notes",
"_id" : ObjectId("5a95a1c32a2e2e0025e6d6e3"),
"submission" : {
"status" : "passed",--> this status should change to "queued"
"system" : "machine.com"
}
}
],
"Notes" : [],
}
Error:-
"sanity": "queued"
TypeError: update expected at most 1 arguments, got 2
UPDATE:-
'''
for document in cursor:
if document['version'] == '9.130.39.0.32.6.1':
for project in document['projects']:
print project
project_id = project['_id']
if project['submission']['status'] != 'queued':
project.update(
{ "_id" : ObjectId(project_id)},
{ "$set":
{
"submission.status": "queued"
}
}
)
'''
for document in cursor:
docId = document['_id']
print "docId"
print docId
if document['version'] == '9.130.39.0.32.6.1':
for project in document['projects']:
print "project"
print project
projectId = project['_id']
print "projectId"
print projectId
document.update({ "_id": ObjectId(docId), "projects._id": ObjectId(projectId) },
{
'$set': {
'projects.$.submission.status': 'queued'
}
}
)
Following works,it should be collection.update instead of db.update
for document in cursor:
docId = document['_id']
print "docId"
print docId
if document['version'] == '9.130.39.0.32.6.1':
for project in document['projects']:
print "project"
print project
projectId = project['_id']
print "projectId"
print projectId
collection.update({ "_id": ObjectId(docId), "projects._id": ObjectId(projectId) },
{
'$set': {
'projects.$.submission.status': 'queued'
}
}
)
Try:
for project in document['projects']:
print project
print project['name']
print project['_id']
id = project['_id']
print project['submission']['status']
if project['submission']['status'] != 'queued':
print "Inside Update.."
project.update({"sanity": "queued"})
This will add the property "sanity":"queued" to the project in the loop. Is that what you want?
The value to the key "projects" is a list, not a dictionary. You need to append your new list:
collection_projects.append([
{ "_id": ObjectId(id) },
{
"$set": {
"sanity": 'queued'
}])
And change the syntax as such.
You have to update your document.
var docId = document._id;
var projectId = project._id;
document.update({ "_id": ObjectId(docId), "projects._id": ObjectId(projectId) },
{
'$set': {
'projects.$.submission.status': 'queued'
}
}
);
This should work.
You can also iterate all the projects assign the status and at the end of iteration update the whole document at once, this will also work.
I am trying to do post request for below schema using flask-mongoAlchemy
class Sensors(db.Document):
sensorName = db.StringField()
sensorStatus = db.StringField()
class Camera(db.Document):
cameraName = db.StringField()
cameraStatus = db.StringField()
class Checkpoints(db.Document):
checkPointName = db.StringField()
class Gateway(db.Document):
sensors = db.ListField(db.DocumentField(Sensors), db_field='sensors')
camera = db.ListField(db.DocumentField(Camera), db_field='camera')
checkpoints = db.ListField(db.DocumentField(Checkpoints), db_field='checkpoints')
In the schema Gateway class contains the list of other three classes
Tried doing as shown below
#gateway_bp.route('/gateway',methods=['POST'])
def object_book():
request_data = request.get_json()
sensorsList=[]
cameraList=[]
checkList=[]
for sensorObj in request_data['GateWay1']['sensors']:
sensorsList.append(Sensors(sensorName=sensorObj['sensorName'],sensorStatus=sensorObj['sensorStatus']))
gatewayObj=Gateway(sensors=sensorsList)
for cameraObj in request_data['GateWay1']['camera']:
cameraList.append(Camera(cameraName=cameraObj['cameraName'],cameraStatus=cameraObj['cameraStatus']))
gatewayObj=Gateway(camera=cameraList)
for checkListObj in request_data['GateWay1']['checkpoints']:
checkList.append(Checkpoints(checkPointName=checkListObj['checkPointName']))
gatewayObj=Gateway(checkpoints=checkList)
gatewayObj.save()
return 'Saved :)'
getting the error has
mongoalchemy.exceptions.MissingValueException
MissingValueException: sensors
sample payload
{
"GateWay1": {
"sensors": [{
"sensorName": "s1",
"sensorStatus": "green "
}, {
"sensorName": "s2",
"sensorStatus": "red "
}],
"camera": [{
"cameraName": "cam1",
"cameraStatus": "live"
}, {
"cameraName": "cam2",
"cameraStatus": "live"
}],
"checkpoints": [{
"checkPointName": "chk1"
}, {
"checkPointName": "chk2"
}]
}
}
please help in saving the above json in mongodb using mongoAlchemy ,please point some sample repo where i can know more about flask-mongoAlchemy
Does anyone know, how I can implement the following MongoDB query using a MongoEngine Raq-Query?
db.getCollection('subscribers').find({
'_id': ObjectId("579e60b0c525fd2037e8dd31"),
'history.content.read_process_msg': {
'$exists':true
},
'history.content.read_processed': {
'$exists':true
},
'history.content.read_processed': false
},
{'history.$':1})
I read, that the raw-query doesn't support projections and that one should use .only() instead. But the problem here is, that it returns all the empty documents also…
Any advice?
Edit: Here are my models and a sample document:
class Subscriber(Document):
service = StringField()
history = EmbeddedDocumentListField('SubscriberHistory')
def __str__(self):
return self.service
class SubscriberHistory(EmbeddedDocument):
action = StringField()
content = DictField()
def __str__(self):
return self.action
And the sample:
{
"_id" : ObjectId("579e60b0c525fd2037e8dd31"),
"service" : "foo",
"history" : [
{
"action" : "outbound",
"content" : {
"read_processed" : false,
"message_data" : {
"text" : "w00t?"
},
"read_process_msg" : {
"$ref" : "bots_messages",
"$id" : ObjectId("57a6529dc525fd8066ee25b3")
}
},
"created_at" : ISODate("2016-08-06T21:12:00.986Z")
}
]
}
I am trying to figure out how to show all endpoints from an API I've written. In browsing to the root of the API, I see a list of resources and a single get endpoint. How do I generate a list to show all endpoints? I tried django-tastypie-swagger but had the same results. It only listed a few GET methods for each resource and didn't show all the prepend_urls that I added to the resource. Any help is appreciated!
Edit:
I have some helper methods in the get_manufacturer_wedges to help with the response. Side note, I'm very new to python and this whole stack. I come from a c#.net background. I am building a golf app.
class ManufacturerResource(BaseMongoResource):
class Meta:
max_limit = 0
queryset = Manufacturer.objects.all().order_by('id')
allowed_methods = ('get')
resource_name = 'manufacturers'
include_resource_uri = False
def prepend_urls(self):
return [
url(r"^(?P<resource_name>%s)/(?P<pk>[\w\d_.-]+)/wedges/$" % self._meta.resource_name,
self.wrap_view('get_manufacturer_wedges'), name="api_get_manufacturer_wedges"),
]
def get_manufacturer_wedges(self, request, **kwargs):
prim_key = kwargs['pk'] + "|Wedge"
wedges = Club.objects(_id__startswith=prim_key).order_by('name')
return self.create_response(request, HelperMethods.obj_to_list(wedges))
Here is the output when I go to the root of the api (/api/v1/):
{
"file_upload" : {
"schema" : "/api/v1/file_upload/schema/",
"list_endpoint" : "/api/v1/file_upload/"
},
"members" : {
"schema" : "/api/v1/members/schema/",
"list_endpoint" : "/api/v1/members/"
},
"manufacturers" : {
"schema" : "/api/v1/manufacturers/schema/",
"list_endpoint" : "/api/v1/manufacturers/"
},
"courses" : {
"schema" : "/api/v1/courses/schema/",
"list_endpoint" : "/api/v1/courses/"
},
"clubs" : {
"schema" : "/api/v1/clubs/schema/",
"list_endpoint" : "/api/v1/clubs/"
}
}