简体   繁体   中英

Specific query in pymongo and displaying the data in flask app

I am working on a project, to query for a particular document in mongodb database in pymongo and showing it on flask app.

Here is the Code:

from flask import Flask
from flask_pymongo import PyMongo
import pymongo
import json

app = Flask(__name__)



@app.route("/")
def home_page():

    return "hello world" 


@app.route("/user/<string:phone>")
def user_profile(phone):

client = pymongo.MongoClient("mongodb+srv://Diligent:Diligent1234@cluster0.1pnpt.mongodb.net/test")
db = client["MyDatabase"]
col = db["UserID"]
for x in col.find({"Contact No": phone}, {"_id":0, "UserID": 1, "User": 1, "Contact No": 1, "Designation": 1 }):
    print(x)
return x

So when I enter input like "http://127.0.0.1:5000/user/phone=9331828671" in flask App.py

I get errors like:

UnboundLocalError: local variable 'x' referenced before assignment.

So How should I solve this to get detailed data for particular queries?

I really appreciate any help you can provide.

With the for-loop you have specified, you are going through an iterable, retrieving every matching x and printing this. This value x is discarded directly after this for-loop.

Now it's up to you what you want to get. If you, for example, want to retrieve the last matching x , try this: (This returns null if no x matches)

last_element = None
for x in col.find({"Contact No": phone}, {"_id":0, "UserID": 1, "User": 1, "Contact No": 1, "Designation": 1 }):
    last_element = x
    print(x)
return {"data": last_element}

If you want all matching x 's, try this: (this returns [] if no x matches)

elements = []
for x in col.find({"Contact No": phone}, {"_id":0, "UserID": 1, "User": 1, "Contact No": 1, "Designation": 1 }):
    elements.append(x)
    print(x)
return {"data": elements}

PS: watch your indentation, it is python you are working in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM