for p in db.collection.find({"test_set":"abc"}):
posts.append(p)
thejson = json.dumps({'results':posts})
return HttpResponse(thejson, mimetype="application/javascript")
Run Code Online (Sandbox Code Playgroud)
在我的Django/Python代码中,由于"ObjectID",我无法从mongo查询返回JSON.错误说"ObjectID"不可序列化.
我需要做什么?一种hacky方式是循环:
for p in posts:
p['_id'] = ""
Run Code Online (Sandbox Code Playgroud) 我正在尝试学习python,mongodb和flask,并且正在使用来自Miguel Grinberg的非常优秀的博客,他在blog.miguelgrinberg.com上提供了一系列精彩的教程.
我有一个小的RESTful服务器工作正常,但现在想从mongo而不是mysql中提取东西
我可以使用下面的代码拉出mongo记录,但我很难让它渲染.
我在下面的代码中使用了箭头来显示我在哪里挣扎,我认为缺乏经验.任何想法将不胜感激.
#!flask/bin/python
from flask import Flask, jsonify, abort, make_response, url_for
from pymongo import MongoClient
# connect to mongo database hosted on AWS
# the script expects the host name to be in /etc/hosts file
'''
Set up global variables here
'''
mongo_server = "mongo_api"
mongo_port = "27017"
mongo_user = "admin"
mongo_passwd = ":mysecretpassword@"
connect_string = "mongodb://"+ mongo_user
+ mongo_passwd
+ mongo_server
+ ":"
+ mongo_port
app = Flask(__name__)
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify( { 'error': 'Notfound' …Run Code Online (Sandbox Code Playgroud) 我正在尝试将集合转储到 .json 文件,但在查看 pymongo 教程后,我找不到任何与之相关的内容。
我试图在烧瓶中返回这个列表。教师是一个类并返回对象。
@app.route('/v1/teachers', methods=['GET'])
def getTeachers():
teachers = []
for teacher in Teacher.objects:
teachers.append(teacher)
return teachers
Run Code Online (Sandbox Code Playgroud)
此代码返回的典型错误
TypeError: 'list' object is not callable The view function did not return a valid response.
我快疯了,我不知道发生了什么。有人知道吗?
谢谢!!
编辑:
我已经解决了。问题不在于如何返回列表,问题在于对象的 JSON 序列化。
@app.route('/v1/teachers', methods=['GET'])
def getTeachers():
teachers = []
for teacher in Teacher.objects:
teacherJson = teacher.to_json()
teacherData = json.loads(teacherJson)
teachers.append(teacherData)
return jsonify({'teachers': teachers})
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助。
我正在尝试在我的HTTP响应中发回一个JSON编码的MongoDB对象.我跟着其他几个类似的问题,但我仍然遗漏了一些东西.没有异常被抛出,但我<api.views.MongoEncoder object at 0x80a0c02c>在浏览器中得到了一个神秘的回应.我相信这很简单,但任何帮助都会受到赞赏.
功能:
from django.utils.simplejson import JSONEncoder
from pymongo.objectid import ObjectId
class MongoEncoder( JSONEncoder ):
def _iterencode( self, o, markers = None ):
if isinstance( o, ObjectId ):
return """ObjectId("%s")""" % str(o)
else:
return JSONEncoder._iterencode(self, o, markers)
Run Code Online (Sandbox Code Playgroud)
views.py:
user = User({
's_email': request.GET.get('s_email', ''),
's_password': request.GET.get('s_password', ''),
's_first_name': request.GET.get('s_first_name', ''),
's_last_name': request.GET.get('s_last_name', ''),
'd_birthdate': request.GET.get('d_birthdate', ''),
's_gender': request.GET.get('s_gender', ''),
's_city': request.GET.get('s_city', ''),
's_state': request.GET.get('s_state', ''),
})
response = {
's_status': 'success',
'data': user
}
return HttpResponse(MongoEncoder( …Run Code Online (Sandbox Code Playgroud) 我遇到了一个常见问题,但到目前为止,我还没有找到适用于我的解决方案。我想我只是想念一些小东西,但我已经崩溃寻求帮助了。我正在尝试使用flask和pymongo获取json输出。
这是控制台中使用print(results)的对象:
[{'_id': ObjectId('598b5de38161a821188f1a7c'), 'first name': 'first name', 'last Name': 'last name'}]
Run Code Online (Sandbox Code Playgroud)
当我尝试返回该错误时,我收到错误:TypeError:“ ObjectId”类型的对象不是JSON可序列化的
类Contacts(资源):
def get(self):
results =[]
connect = MongoClient("<REMOVED>")
db = connect['<REMOVED>']
collection = db['contact']
contacts = collection.find()
if collection:
number_of_contacts = collection.count()
for document in contacts:
results.append(document)
print(results)
return {'results': results, 'count': number_of_contacts}
Run Code Online (Sandbox Code Playgroud)
我已经尝试了bson.json_util建议。它确实通过双重编码json对象清除了可序列化的错误。似乎这不是我正在做的事情的好解决方案。
我在通过 FastAPI 插入 MongoDB 时遇到一些问题。
下面的代码按预期工作。请注意该response变量尚未在 中使用response_to_mongo()。
这model是一个 sklearn ElasticNet 模型。
app = FastAPI()
def response_to_mongo(r: dict):
client = pymongo.MongoClient("mongodb://mongo:27017")
db = client["models"]
model_collection = db["example-model"]
model_collection.insert_one(r)
@app.post("/predict")
async def predict_model(features: List[float]):
prediction = model.predict(
pd.DataFrame(
[features],
columns=model.feature_names_in_,
)
)
response = {"predictions": prediction.tolist()}
response_to_mongo(
{"predictions": prediction.tolist()},
)
return response
Run Code Online (Sandbox Code Playgroud)
但是,当我predict_model()这样写并将response变量传递给response_to_mongo():
@app.post("/predict")
async def predict_model(features: List[float]):
prediction = model.predict(
pd.DataFrame(
[features],
columns=model.feature_names_in_,
)
)
response = {"predictions": prediction.tolist()} …Run Code Online (Sandbox Code Playgroud) 嗨,我刚刚开始尝试使用python和龙卷风以及mongodb(我是新手).我编写了一个简单的get函数来获取我的mongodb中的所有值并以JSON格式返回它.问题是当我尝试将输出写为JSON字符串时,我在集合的最后一条记录之后得到一个尾随逗号(,).
class TypeList(APIHandler):
@gen.coroutine
def get(self):
cursor = db.vtype.find()
self.write("{"'"success"'": 1, "'"data"'":[")
while (yield cursor.fetch_next):
document = cursor.next_object()
self.write(format(JSONEncoder().encode(document)))
self.write(",")
self.write("]}")
class JSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o,ObjectId):
return str(o)
return json.JSONEncoder.default(self, o)
Run Code Online (Sandbox Code Playgroud)
我的输出就像
{"success": 1, "data":[{"_id": "55a5e988545779f35d3ecdf4", "name": "fgkd", "city": "fghj"},{"_id": 12345.0, "name": "adfs", "city": "asd"},]}
Run Code Online (Sandbox Code Playgroud)
任何人都可以告诉我如何在我的最后一条记录之后摆脱那个尾随的逗号(,),因为那个逗号我收到错误的JSON字符串错误
我尝试过使用json转储
@gen.coroutine
def get(self):
cursor = db.vtype.find({"brand": "Tata"})
while (yield cursor.fetch_next):
document = cursor.next_object()
self.write(json.dumps(document,default=json_util.default))
Run Code Online (Sandbox Code Playgroud)
把输出作为
{"Reg": "11ts", "_id": {"$oid": "55a5e988545779f35d3ecdf4"}, "Name": "Alex"}{"Reg": "12ts", "_id": {"$oid": "55a5eac6545779f35d3ecdf5"}, "Name": "asdf"}
使用时 dumps[{ "data": …
python ×6
mongodb ×5
json ×3
pymongo ×3
django ×2
flask ×2
api ×1
database ×1
fastapi ×1
list ×1
pymongo-3.x ×1
python-3.x ×1
simplejson ×1