I am trying to use Pymongo for my project, I want to view the data by using for loop, forEach, or Map to expand my array in my search query but I don't know how to do this.
my question:
How to for loop represent [postLike[0],postLike[1] in my search query?
Here is my code which can function normally but not in for loop.
#app.route("/user/addlikevideo", methods=["POST","GET"])
#jwt_required()
def add_like_video():
if request.method =="GET":
try:
getTokenEmail = get_jwt()["sub"] //Get the email by Token
existing_user = user_collection.find_one({"email": getTokenEmail}) //Find the user
postLike = existing_user["likeVideos"] // the data like [4,25]
// *** I want to use map or for loop something like that function to represent [postLike[0],postLike[1]....]
thePostLike = post_collection.find({ "idCount": { "$in": [postLike[0],postLike[1]]}})
listThePostLike = list(thePostLike)
json_data = dumps(listThePostLike, indent = 4)
return json_data
except:
return "no liked post"
If you want to find all the objects which have an idCount equals to one of the postLike array elements, you can directly use the array in your query:
#app.route("/user/addlikevideo", methods=["POST","GET"])
#jwt_required()
def add_like_video():
if request.method =="GET":
try:
getTokenEmail = get_jwt()["sub"] //Get the email by Token
existing_user = user_collection.find_one({"email": getTokenEmail}) //Find the user
postLike = existing_user["likeVideos"] // the data like [4,25]
thePostLike = post_collection.find({ "idCount": { "$in": postLike}})
listThePostLike = list(thePostLike)
json_data = dumps(listThePostLike, indent = 4)
return json_data
except:
return "no liked post"
And if you want to filter the elements:
thePostLike = post_collection.find({ "idCount": { "$in": [ele for ele in postLike if (ele > 10)]}}) # you can use any filter
Related
I have been trying to intergrate mpesa API and make my payment dynamically I manage to see the correct value in my cart on my phone stk push but on the web browser I get an error local variable 'order' referenced before assignment and the console gives me a success message without me incorrectly putting in my pin, thank you.
Please please help me solve this I am still a newbie in PYTHON.
def mpesaToken(request):
ckey = 'hOdosm1nU1tXMsT0yPTGjnHDgIUSxx8z'
csecret = 'mrgGSIdbDOZaVrZl'
apiurl = 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials'
r = requests.get(apiurl, auth=HTTPBasicAuth(ckey, csecret))
mptoken = json.loads(r.json)
valida = mptoken['access_token']
return HttpResponse(valida)
def lipaOnline(request):
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
items = order.orderitem_set.all()
cartItems = order.get_cart_items
else:
items = []
accesstoken = MpesaToken.valida
apiurl = "https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest"
headers = {"Authorization":"Bearer %s" % accesstoken}
request = {
"BusinessShortCode": Lipa.bscode,
"Password": Lipa.decode_pass,
"Timestamp": Lipa.lipatime,
"TransactionType": "CustomerPayBillOnline",
"Amount": order.get_cart_total,
"PartyA": 25471234567,
"PartyB": Lipa.bscode,
"PhoneNumber": 25471234567,
"CallBackURL": "https://sandbox.safaricom.co.ke/mpesa/",
"AccountReference": "HAC",
"TransactionDesc": "testeltd"}
response = requests.post(apiurl, json=request, headers=headers)
return HttpResponse('Success')
print(request)
The problem is you are trying to pick a value from a computed value, it doesn't understand that it's supposed to retrieve that query(order.get_cart_total) before it assigns that value into your other variable Amount so what works for me is that I set the variable first before invoking it and to be sure you can also put it as a global variable.
so simply do
global totalcart = order.get_cart_total
first then
"Amount" : totalcart'
...
My code looks like this :
def rssfeeds(request):
reqdata = request.GET['url']
if reqdata == '':
d = "https://github.com/rudrasingh99.private.atom?token=MYPRIVATETOKEN"
data = []
for post in d.entries:
data.append(post.title)
my_context = {
"my_list" : data,
}
else:
d = feedparser.parse(reqdata)
data = []
for post in d.entries:
data.append(post.title)
my_context = {
"my_list" : data,
}
return render(request,"base.html",my_context)
def home_view(request):
return render(request,"index.html",{})
while whenever i try with empty url parameter it gives me 500 error.
Thanks in advance
It gives you a 500 error because the request.GET is a dictionary. It's really a KeyError under the hood; set DEBUG=True to find this.
Use .get to get terms with default values and handle appropriately.
reqdata = request.GET.get('url', 'mydefaultvalue')
If url is required for the page to load properly, maybe consider returning a human readable error?
reqdata = request.GET.get('url', '')
if reqdata == '':
return HttpResponse("Specify a url!")
The API returns both JSON and also render the template and when i call $.getJSON it will only return that render template but not JSON value. I have tried this
if request.args['type'] == 'json':
return json.dumps(group)
else:
return render_template("/c.., summary=json.dumps(group))
but it says
bad request
Is there any way I can get that JSON value whenever I need it?
This is my view
#cms.route('/add/asset/<client_id>', methods=["GET"])
#login_required
def asset_add(client_id):
if int(current_user.id_) == int(client_id):
group = {}
group['id'] = []
group['pid'] = []
group['name'] = []
for index in range(len([r.id_ for r in db.session.query(Assetgroup.id_)])):
for asset in (Assetgroup.query.filter_by(parent_id=(index or ''))):
group['id'].append(asset.id_)
group['pid'].append(asset.parent_id)
group['name'].append(asset.name)
if request.args['type'] == 'json':
return json.dumps(group)
else:
return render_template("/cms/asset_add.html", action="/add/asset", asset=None,
client_id=client_id,
types=Type.query.all())
else:
return 'permission denied'
and this is my ajax request
$(document).ready(function () {
$('#group_id').click(function () {
$.getJSON(
'/add/asset/' + {{ client_id }},
function (data) {
$('#group_id').find('option').remove();
var len = data.id.length;
for (var i = 0; i < len; i++) {
var option_item = '<option value="' + data.id[i] + '">' + data.name[i] + "</option>";
$('#group_id').append(option_item);
}
}
);
});
});
You can add parameter in html call to get the json result...
i.e)
const Endpoint = '/add/asset/?'
$.getJSON(Endpoint, {type: 'json'}).done(function(data...)
I believe this is what you are looking for
http://flask.pocoo.org/docs/0.12/api/#flask.Request.is_json
That is a flask method that checks if the request is json
Then you can use jsonify still in flask to return json (you need to import it though)
from flask import jsonify
so your code becomes
if request.is_json:
return jsonify(group)
Hope you find that useful and more elegant
One of the easier ways to debug is just return json alone for a start to see how the response looks in a browser. So you can remove login required (assuming you are not yet in production), do not check if the request is_json, then call the api and see what it returns. So assuming your client id is 1
#cms.route('/add/asset/<client_id>', methods=["GET"])
def asset_add(client_id):
if int(current_user.id_) == int(client_id):
group = {}
group['id'] = []
group['pid'] = []
group['name'] = []
for index in range(len([r.id_ for r in db.session.query(Assetgroup.id_)])):
for asset in (Assetgroup.query.filter_by(parent_id=(index or ''))):
group['id'].append(asset.id_)
group['pid'].append(asset.parent_id)
group['name'].append(asset.name)
return jsonify(group)
Now you can visit http://yoursite.com/add/asset/1 to see your response
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...
views.py
def json(request):
defaultnumber = []
phoneinfo = PhoneInfo.objects.filter(user = user_id)
for phone in phoneinfo:
phone_no = {'id':some.id,
'name1':phone.name1,
'number1':phone.number1,
'name2':phone.name2,
'number2':phone.number2,
} }
defaultnumber.append(phone_no)
result = { 'phone':defaultnumber}
return HttpResponse(json.dumps(result), mimetype="application/json")
I need to send the data into json format.
Use model_to_dict instead:
from django.forms.models import model_to_dict
def json_view(request):
phoneinfo = PhoneInfo.objects.filter(user = user_id)
phones = [model_to_dict(phone) for phone in phoneinfo]
result = {'phoneinfo': phones}
return HttpResponse(json.dumps(result), mimetype="application/json")
And, don't call view json - you are overriding json module name.
And, it's unclear from where user_id variable comes.