I found here a nice template for a pagination. However, this example is done with
SQLlite.
It seems that it is possible to do pagination with flask-mongoengine,
flask-mongoalchemy
and pymongo.
I created a little code with PyMongo:
from pymongo import MongoClient
#mongod --dbpath /home/mic/databases/
def fill_data(users_no):
for i in range(users_no):
doc = {
'_id': str(i),
'uname': "name_" + str(i),
}
sDB.insert(doc)
if __name__ == "__main__":
db = MongoClient().test
sDB = db.users
fill_data(10)
users_no = sDB.find().count()
Which of three MongoDB drivers would work best and is most efficient for above Flask template?
For a simple operation like that they're extremely likely to do the same underlying command. I can tell you that MongoAlchemy just does a call out to mongo as you would expect to get the count.
Related
I'd like to know what call I can make from a python MongoEngine instance to get a list of collection names from my mongodb database? If I were using pymongo directly I could call db.list_collection_names(), but I can't find a similar call from MongoEngine. Specifically I'm using flask-mongoengine if that matters.
MongoEngine
from mongoengine import connect
db_name = 'test'
connection = connect(db_name)
connection.get_database(db_name).list_collection_names()
Flask-MongoEngine
from flask import Flask
from flask_mongoengine import MongoEngine
app = Flask(__name__)
db = MongoEngine(app)
#app.config.from_pyfile('the-config.cfg')
#app.config['MONGODB_SETTINGS'] = {}
db.get_db().list_collection_names()
The documentation example for a simple restful api is:
from flask import Flask, request
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
todos = {}
class TodoSimple(Resource):
def get(self, todo_id):
return {todo_id: todos[todo_id]}
def put(self, todo_id):
todos[todo_id] = request.form['data']
return {todo_id: todos[todo_id]}
api.add_resource(TodoSimple, '/<string:todo_id>')
if __name__ == '__main__':
app.run(host="0.0.0.0",port="80",debug=True)
However, suppose I made a put request with a nested dictionary,ie {'data':{'fruit':'orange'}}. The TodoSimple would have request.form.to_dict() = {'data':'fruit'}. How can I work with the full nested dictionary?
You should probably use Schemas to achieve this goal. Take a good look at this first example of marshmallow docs:
https://marshmallow.readthedocs.io/en/3.0/
As flask-restful docs says:
The whole request parser part of Flask-RESTful is slated for removal
and will be replaced by documentation on how to integrate with other
packages that do the input/output stuff better (such as marshmallow).
I have one mongodb database and I have connected that db with pymongo in django. I am new to django, I am trying to get if the entered data present in the collection or not, if present return that record using get method
import pymongo
from pymongo import MongoClient
db_name = 'student_db'
client = MongoClient('localhost', 27017)
db_obj = client[db_name]
collection=db_obj['mongo_app_student']
#api_view(['GET'])
def test(request):
data = request.data
for x in collection.find():
if data in x:
print('entered a right value')
return Response(data)
TypeError at /test
unhashable type: 'dict'
I am getting this error when i am trying to get the output in postman. please help
First you Should use a POST request for that and since find() return a cursor, you're trying to iterate on a cursor. I'm not sure that's a good idea. And assuming request.data is a dict() try using == for comparison with x
Also Try casting what you get from mongo in a list like this :
import pymongo
from pymongo import MongoClient
db_name = 'student_db'
client = MongoClient('localhost', 27017)
db_obj = client[db_name]
collection=db_obj['mongo_app_student']
#api_view(['GET', 'POST'])
def test(request):
response_data = None
if request.method == 'POST':
for x in list(collection.find()):
if data == x:
print('entered a right value')
response_data = data
return Response(response_data )
Let me know how it goes.
I would really appreciate if someone can help me with this. I need Django (Python) function to inject some parameters into a pipeline script, pass it to MongoDB Atlas and receive the result in a cursor.
from bson import ObjectId
import pymongo
conn = "connection string"
client = pymongo.MongoClient(conn)
pipeline = [
<<pipeline script>>
]
out = client.db.mycollection.aggregate(pipeline)
If you're using Djongo to connect the Django ORM to MongoDB, you could use the provided DjongoManager as the manager for your Model, and use PyMongo functions using the mongo_ prefix. Here's a quick example:
models.py
from djongo import models
class Message(models.Model):
text = models.CharField(max_length=150)
objects = models.DjongoManager()
Then in the shell you could do something like:
>>> from core.models import *
>>> cursor = Message.objects.mongo_aggregate('pipeline')
I want to use meta ID field to add a new index/field based on the searched data, but I cannot access meta.id field. What should I do? Here is the code below -
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search
es = Elasticsearch(Host="http://localhost", PORT=9200)
request = Search(using=es, index='internal', doc_type="doc")
response = request.scan()
for each in response:
....alert = each.to_dict()
....print(alert["id"])
What do you mean by cannot access? What happens if you do each.meta.id in your for loop?