cobrateam / flask-mongoalchemy Goto Github PK
View Code? Open in Web Editor NEWFlask support for MongoDB using MongoAlchemy.
Home Page: https://pythonhosted.org/Flask-MongoAlchemy/
License: BSD 2-Clause "Simplified" License
Flask support for MongoDB using MongoAlchemy.
Home Page: https://pythonhosted.org/Flask-MongoAlchemy/
License: BSD 2-Clause "Simplified" License
Add docs and examples showing how to customize the query_class of a document by extending BaseQuery
class.
Hi
I want to make tests to my webapp but i cannot find to mock or have a dummy db connection to run the tests. Thanks
I don't know exactly if it is in Flask-MongoAlchemy or in MongoAlchemy, but the filtering for mongo_id does not work correctly.
To get a single object referenced by it's id, one would use:
SomeDocument.get_or_404( 'mongoidstring')
This query does always return 'None' (doesn't exists a test for this?)
Internally the get method is mapped to .filter( { 'mongo_id': 'mongoidstring'} ).first()
This does somehow not work, not even with pure MongoAlchemy.
What actually works is .filter( SomeDocument.mongo_id == 'mongoidstring' )
I'm using MongoAlchemy 0.8 and Flask-MongoAlchemy 0.3
Both installed with easy_install.
For authentication reasons, the MongoDB URI should include the database.
Details, extracted from Flask mailing list:
On Tue, Aug 23, 2011 at 8:41 AM, Ishbir Singh <...> wrote:
Hey,
This throws the same error, but when I try host='mongodb://user:[email protected]:27017/database', then it works.. I created a user for the database, not for the entire server, because, that would be insecure otherwise.
On 23 August 2011 02:51, Francisco Souza <...> wrote:
Can you execute this code below in the Python interactive console?
>>> import pymongo
>>> conn = pymongo.connection.Connection(host='mongodb://user:[email protected]:27017') # place your data here
>>> conn.database
Cheers,
Chico (a.k.a Francisco Souza)
@franciscosouza
On Mon, Aug 22, 2011 at 11:21 AM, Ishbir Singh <...> wrote:
Hey, here you go-
Traceback (most recent call last):
File "manage.py", line 3, in <module>
from lulzimg import app
File "/var/script/script/__init__.py", line 25, in <module>
db.init_app(app)
File "/usr/local/lib/python2.7/dist-packages/flaskext/mongoalchemy.py", line 108, in init_app
host=uri,
File "/usr/local/lib/python2.7/dist-packages/mongoalchemy/session.py", line 83, in connect
conn = Connection(*args, **kwds)
File "/usr/local/lib/python2.7/dist-packages/pymongo/connection.py", line 333, in __init__
raise ConfigurationError("authentication failed")
pymongo.errors.ConfigurationError: authentication failed
On 22 August 2011 18:42, Francisco Souza <...> wrote:
Hey there,
On Mon, Aug 22, 2011 at 8:57 AM, Ishbir Singh <...> wrote:
Hey there,
I realize that this might not be related to Flask in anyway, but I still wanted to get some help. What I have are 2 servers, one running MongoDB server and the other is the client. Now, I'm trying to access the server from the client by using appropriate credentials and port numbers. The connection is successful via the command-line mongo tool but while using the exact same settings with Flask-MongoAlchemy, it says that authentication failed.
Could you please paste the stack trace here?
Cheers,
Chico (a.k.a Francisco Souza)
@franciscosouza
On Mon, Aug 22, 2011 at 8:57 AM, Ishbir Singh <...> wrote:
Hey there,
I realize that this might not be related to Flask in anyway, but I still wanted to get some help. What I have are 2 servers, one running MongoDB server and the other is the client. Now, I'm trying to access the server from the client by using appropriate credentials and port numbers. The connection is successful via the command-line mongo tool but while using the exact same settings with Flask-MongoAlchemy, it says that authentication failed.
I know that the settings are valid, I know that the firewall is not blocking requests. What could be the fault?
config.py in the client server-
MONGOALCHEMY_DATABASE = 'database'
MONGOALCHEMY_SERVER = '188.88.88.2'
MONGOALCHEMY_USER = 'user'
MONGOALCHEMY_PASSWORD = 'password'
I'm using Flask-MongoAlchemy by the way.
--
Regards,
Ishbir Singh
--
Regards,
Ishbir Singh
--
Regards,
Ishbir Singh
The get()
method should be on BaseQuery
class, not Document
.
Make Flask-MongoAlchemy compatible with MongoAlchemy 0.8.
Add support to remove queries
Add support to update queries: http://mongoalchemy.org/api/expressions/update_expressions.html
Is it possible to define the collection names in Lowercase
Hello guys,
I am having issues with using flask-mongoalchemy to query my database and get results that are close to the longitude and latitude I passed.
My Model:
class Event(db.Document):
meta = {
'indexes': [
("*location.coordinates", "2dsphere")
]
}
user_id = db.StringField()
uuid = db.StringField()
name = db.StringField()
address = db.StringField()
start_time = db.DateTimeField(required=True, default=datetime.datetime.now())
end_time = db.DateTimeField(required=True, default=datetime.datetime.now())
location = db.DictField(db.AnythingField())
When an event is created this is how the document is meant to look like:
{
"address": "Surulere",
"end_time": "2019-10-13T00:00:00",
"location": {
"coordinates": [
-119.3996898,
19.6255545
],
"type": "Point"
},
"name": "Amazonss__",
"start_time": "2019-10-12T00:00:00",
"user_id": "3b15b5f9d6d1ab93d14db52cabe6ac",
"uuid": "baa75b69047369a48342e6939c56d3"
}
And My Code for Querying is:
event = Event.query.filter({"location" :
{ "$near" :
{
"$geometry" : {
"type" : "Point",
"coordinates" : [longitude, latitude] },
"$maxDistance" : 4000
}
}
}).first()
flask-mongoalchemy does not work with Flask 0.8. It must be updated.
Versions are too out of date and incompatible.
Mongoengine's latest version (0.23.1, the only one installable) requires pymongo 3.4->4.0, Mongoengine's current version is 3.11.4
But flask-mongoalchemy 0.7.2 requires pymongo 2.8.1
This is an irresolvable conflict
Mongoalchemy is now 0.21, but flask-mongoalchemy 0.7.2 requires Mongoalchemy 0.19.
Please bring the dependencies up to date
Refactor some tests code and remove some duplicated or triplicated code on setup's.
Flask-MongoAlchemy==0.7.2
from flask_mongoalchemy import Document
my class
class User(Document):
id = db.StringField()
email = db.StringField()
password = db.StringField()
name = db.StringField()
`from flask import request, make_response, jsonify, current_app
from time import time
from app.models import User
from app.security import bp
@bp.route('/freeman/login', methods=['POST'])
def login():
email = request.json['email']
password = request.json['password']
user = User.query.filter(User.email == email)
if user is None or not user.check_password(password):
return make_response(jsonify({'error': 'Unauthorized access'}), 401)
expires_in = time() + current_app['EXPIRATION_TIME']
secret_key = current_app['SECRET_KEY']
token = user.login(secret_key, expires_in)
return make_response(jsonify({'type': 'bearer', 'token': token, 'expireIn': expires_in}), 200)
@bp.route('/freeman/api/users', methods=['GET'])
def get_users():
users = User.query.all()
return make_response(jsonify({'users': users}), 200)`
I debugged and I don know what's happens, but my query object has no instance and looking the documentation it's OK
I installed flask-mongoalchemy today but keep getting the error:
ImportError: No module named mongoalchemy.
I saw that this issue was fixed in one of the previous releases but I am still getting this.
This is not really issue, but a question. I'm seriously confused, or I'm getting old.. Through all documentation I've found about MongoAlchemy and flask-mongoalchemy, I just don't understand how to remove from DB something simple as for example this:
class User(db.Document):
username = db.StringField()
password_hash = db.HashField()
and let's say there's already one row in db where username is 'holms'.
How can I remove it?? I mean completely delete whole row with password_hash too. In real system I usually avoid to remove users, but this is for unit testing.
My attempt:
users = User.query.filter(User.username=="holms")
----> 1 users.remove_all(User.username, ['holms'])
/var/www/msgapp/backend/lib/python2.7/site-packages/mongoalchemy/query.pyc in remove_all(self, qfield, *value)
387 def remove_all(self, qfield, *value):
388 ''' Refer to: :func:`~mongoalchemy.update_expression.UpdateExpression.remove_all`'''
--> 389 return UpdateExpression(self).remove_all(qfield, *value)
390
391 def add_to_set(self, qfield, value):
/var/www/msgapp/backend/lib/python2.7/site-packages/mongoalchemy/update_expression.pyc in remove_all(self, qfield, *value)
123 def remove_all(self, qfield, *value):
124 ''' Atomically remove each value in ``value`` from ``qfield``'''
--> 125 return self._atomic_list_op_multivalue('$pullAll', qfield, *value)
126
127 def add_to_set(self, qfield, value):
/var/www/msgapp/backend/lib/python2.7/site-packages/mongoalchemy/update_expression.pyc in _atomic_list_op_multivalue(self, op, qfield, *value)
147 qfield = resolve_name(self.query.type, qfield)
148 if op not in qfield.valid_modifiers:
--> 149 raise InvalidModifierException(qfield, op)
150 wrapped = []
151 for v in value:
InvalidModifierException: Invalid modifier for QueryField field: $pullAll
users = User.query.filter(User.username=='holms')
users.remove()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-74-4b66f4960b06> in <module>()
----> 1 users.remove()
TypeError: remove() takes exactly 3 arguments (1 given)
In [6]: from testUsers import Comments, Users
In [7]: comment = Comments(title='test', text='testing mongo linking', _id='bob')
In [8]: comment.save()
...
AttributeError: mongo_id
Thanks
Hi, in requirements.txt you have >= for versions, but in setup.py the version numbers are absolute.
It would be cool if you could change it there as well, otherwise Flask gets downgraded if you do pip install from pypi.
Thanks and Best Regards,
Jesaja Everling
Use the new pagination features on examples.
Thanks for this great package!
On object creation, where:
the object is created with this attribute value set to the Field.default.
For ListField attributes, this causes a problem, because list operations such as
append() will modify the Field.default and subsequent object creations will
behave unexpectedly.
I have included a code illustration below.
The obvious fix is to always initialize an object with a COPY of the Field.default.
from flask import Flask
from flask_mongoalchemy import MongoAlchemy
# Setup Flask
app = Flask(__name__)
# Setup MongoAlchemy
app.config.update(MONGOALCHEMY_DATABASE='issue_db')
db = MongoAlchemy(app)
# Define Item Document
class Item(db.Document):
name = db.StringField(default='')
colors = db.ListField(db.StringField(), default=[])
# Clear Item collection
db.session.clear_collection(Item)
# Create Documents
item1 = Item(name='Item One')
db.session.add(item1)
# item1.colors.append() modifies the Field default
item1.colors.append('red')
item1.colors.append('blue')
item2 = Item(name='Item Two')
db.session.add(item2)
db.session.flush()
# item2 is created with the modified Field default
assert item2.colors==[], 'item2.colors='+str(item2.colors)+' instead of []'
If users are looking for a temporary workaround:
item1.colors = item1.colors + ['red'] # this ensures a copy is assigned
item1.colors = item1.colors + ['blue'] # this ensures a copy is assigned
Hello,
There seems to be a small bug in the book collections code. Here is the diff that fixed it. I tried to commit and push the change, but was denied with a 403. Anyway, thank you for these great examples!
--- a/examples/books_collection/collection/forms.py
+++ b/examples/books_collection/collection/forms.py
@@ -4,7 +4,7 @@
-from flaskext import wtf
+from flask.ext import wtf
Hi,
Is that possible to add the Standard Connection String Format (http://docs.mongodb.org/manual/reference/connection-string/#standard-connection-string-format)
I am writing this issue at http://stackoverflow.com/questions/29030257/flask-mongoalchemy-with-multi-hosts-urls
Cheers
This would allow setting connection properties, e.g. serverSelectionTimeMS
, on the Mongo connection created.
Should provide methods like get_or_404
, first_or_404
and paginate
on BaseQuery class.
There is minimal information provided in the documentation pertaining to the types of fields which can be used in flask-mongoalchemy. Please provide information about IntField, ListFIeld, BoolField etc...
I am attempting to connect with a mongolab uri provided by heroku. I store it as an evironment variable.
MONGOLAB_URI="mongodb://heroku_tchBR549:[email protected]:57934/heroku_tchBR549"
In my config.py, I declare it like so:
MONGOALCHEMY_CONNECTION_STRING = os.environ["MONGOLAB_URI"]
... whch results in the following:
File "/home/clownshoes/project/venv/local/lib/python2.7/site-packages/flask_mongoalchemy/__init__.py", line 116, in init_app
"(the %s setting)." % key('DATABASE'))
flask_mongoalchemy.ImproperlyConfiguredError: You should provide a database name (the MONGOALCHEMY_DATABASE setting).
The database name is the final value after the port number in the URI.
When I actually put the database name in like so:
MONGOALCHEMY_CONNECTION_STRING = os.environ["MONGOLAB_URI"]
MONGOALCHEMY_DATABASE="heroku_tchBR549"
I can successfully connect.
init_app actually gets the uri at line 119. It seems that the DATABASE variable check might do it's job in _get_mongo_uri just as well, and avoid this problem by declaring DATABASE by snipping it off the end of CONNECTION_STRING. (unless I'm reading it wrong, and brother, I am prone to that . . .)
Provide on example directory a sample Flask application with a "real" CRUD.
Because the Document class is mangled during the init_app, if I create 2 MongoAlchemy instances, one of them will no longer work properly because it's attached to the wrong session.
Changes on MongoAlchemy
API need to be reflected on Flask-MongoAlchemy
.
This seems not working anymore:
class Person(db.Document):
name = db.StringField()
Person.query.filter({'name' : 'Mary'}).one()
There are some changes on Query
API.
Since the support for DB based authentication was introduced (version 0.4.3), server based authentication stopped working.
In below code I want to fetch only the values of User1 in descending order of Item values.
but I'm unable to fetch it using below query.
op = Output()
op.data = {"User1": {"Item2": 2, "Item3": -1, "Item4": 3}, "User2": {"Item4": 2, "Item5": 1, "Item6": 2}}
r = op.query.filter({Output.data:{"User1":{'$exists':True}}})
result = r.all()
Expected result:
["Item4","Item2","Item3"]
Would it not be better to let this work:
books = Book.query.filter(Book.author == author).first()
rather than:
books = Book.query.filter(Book.author.mongo_id == author.mongo_id).first()
How do I use MpngoAlchemy with Flask-Admin which needs a ModelView?
Flask_admin has a class of backend Modelview contributors (flask_admin.contrib) and Mongoengine & SQLAlchemy are in there but MA is not.
This may be a mongoalchemy list question, but I thought I'd work my way up from here.
I am running flask-mongoalchemy on an Ubuntu server with several different wsgi applications. Each has a different MongoAlchemy(app) instance, and each runs perfectly... Until one of the others runs. At that point, one or both generates an error (in the apache log):
[error] class 'mongoalchemy.exceptions.BadValueException'
[error] Bad value for field of type "mongo_id". Reason: "Value is not an instance of <class 'bson.objectid.ObjectId'> (got: ObjectId)".
The only option is to touch the broken app's .wsgi file, at which point the broken app works, but the other one breaks. I have been able to find very little online about this error.
Suspecting it might be a question of wsgi processes, I've restricted my wsgi daemon processes to 1 process per app, with 25 threads, also tried 2 processes, but the error is so terse I'm having trouble even figuring out what to do next. Thoughts? Thanks,
Chris.
Since MongoAlchemy has timezone support, I'd like to be able to work with timezones. MongoDb stores all datetime using timezone and my queries using the driver are not working properly.
When installing the last version of flask-mongoalchemy (0.5), the code is not installed and thus the module cannot be found.
from flaskext.mongoalchemy import MongoAlchemy
ImportError: No module named mongoalchemy
Here is an example:
db = MongoAlchemy()
def init_app():
app = Flask(__name__)
db.init_app(app)
return app
In this case, db.Document.query is None
.
Nowadays extensions should live in a package/module named flask_foo
, i.e. flask_mongoalchemy
.
keyword 'safe' is not expected in save operations since 3.0 version of pymongo
File "/usr/local/lib/python2.7/dist-packages/flaskext/mongoalchemy/__init__.py", line 264, in save self._session.insert(self, safe=safe) File "/usr/local/lib/python2.7/dist-packages/mongoalchemy/session.py", line 172, in insert self.add(item, safe=safe) File "/usr/local/lib/python2.7/dist-packages/mongoalchemy/session.py", line 188, in add return self.flush() File "/usr/local/lib/python2.7/dist-packages/mongoalchemy/session.py", line 414, in flush result = op.execute() File "/usr/local/lib/python2.7/dist-packages/mongoalchemy/ops.py", line 97, in execute return self.collection.save(self.data, safe=self.safe) File "/usr/local/lib/python2.7/dist-packages/pymongo/collection.py", line 1898, in save write_concern = WriteConcern(**kwargs) TypeError: __init__() got an unexpected keyword argument 'safe'
I'm running into a strange bug -- my classes and objects will periodically forget their attributes, with the attributes being replaces with the relevant query fields.
For example,
>>> object.name
>>> 'name'
Becomes
>>>object.name
>>>QueryField(name)
I can fix the problem by re-importing the class, but that seems like a pretty bad solution. I haven't been able to pin this to any specific behavior on my end -- it happens every time, after some irregular length of time.
File "/usr/local/lib/python2.7/dist-packages/flaskext/mongoalchemy/init.py", line 278, in cmp
return self.mongo_id.__cmp(other.mongo_id)
AttributeError: 'ObjectId' object has no attribute 'cmp'
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.