简体   繁体   English

在 pymongo 中具体查询并在 flask app 中显示数据

[英]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.我正在做一个项目,在 pymongo 的 mongodb 数据库中查询特定文档,并将其显示在 flask 应用程序上。

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因此,当我在 flask App.py 中输入“http://127.0.0.1:5000/user/phone=9331828671”之类的输入时

I get errors like:我收到如下错误:

UnboundLocalError: local variable 'x' referenced before assignment. UnboundLocalError:分配前引用的局部变量“x”。

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.使用您指定的 for 循环,您将经历一个可迭代的,检索每个匹配的x并打印它。 This value x is discarded directly after this for-loop.这个值 x 在这个 for 循环之后被直接丢弃。

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)例如,如果您想检索最后匹配的x ,请尝试以下操作:(如果没有 x 匹配,则返回null

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)如果您想要所有匹配的x ,请尝试以下操作:(如果没有 x 匹配,则返回[]

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. PS:注意你的缩进,你正在工作的是 python。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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