Giter VIP home page Giter VIP logo

flask-mongoalchemy's Introduction

Flask-MongoAlchemy

https://travis-ci.org/cobrateam/flask-mongoalchemy.png?branch=master

Flask support for MongoDB using MongoAlchemy.

Documentation

If you want to get started, check the example sourcecode out.

For full documentation, see the online docs at: https://pythonhosted.org/Flask-MongoAlchemy/.

Development

Bootstraping the development environment

If you are using a virtualenv, bootstrap your development environment by running:

$ make bootstrap

Running tests

With all dependencies installed (after bootstrap development env), just run:

$ make test

Community

#cobrateam on chanel irc.freenode.net

Changelog

Flask-MongoAlchemy 0.7.2

  • Pin pymongo version to ensure driver compatibility.

Flask-MongoAlchemy 0.7.1

  • Support for specifying the full connection string, via the MONGOALCHEMY_CONNECTION_STRING configuration value.

Flask-MongoAlchemy 0.7.0

  • Multiple database support (thanks Misja Hoebe)

Flask-MongoAlchemy 0.6.1

  • Replica set support, via the MONGOALCHEMY_REPLICA_SET configuration value.

Flask-MongoAlchemy 0.6.0

  • Use the not-so-new extension scheme for Flask, users now should import the extension using the flask.ext metapackage
  • Some fixes in the docs, regarding other extensions usage in examples

Flask-MongoAlchemy 0.5.4

  • [bugfix] fix compatibility with pymongo 2.2

Flask-MongoAlchemy 0.5.3

  • [bugfix] fixed a bug on setup.py

Flask-MongoAlchemy 0.5.2

  • added a configuration flag for user authentication based either on database or server
  • [bugfix] fixed server based authentication

Flask-MongoAlchemy 0.5.1

  • [bugfix] fixed the subpackage structure

Flask-MongoAlchemy 0.5

  • Support for multiple MongoDB sessions

Flask-MongoAlchemy 0.4.3

  • [bugfix] added database to MongoDB URI for authenticated connectinos

Flask-MongoAlchemy 0.4.2

  • Fixed pymongo dependency in setup.py

Flask-MongoAlchemy 0.4.1

  • MongoAlchemy 0.9 as dependency
  • [bugfix] safe session operations on connect, save and remove

Flask-MongoAlchemy 0.4

  • Documentation improvements
  • Support for safe or unsafe sessions and operations

Flask-MongoAlchemy 0.3.3

  • Fixed dependencies on setup.py

Flask-MongoAlchemy 0.3.2

  • Compatibility with Flask 0.7

Flask-MongoAlchemy 0.3.1

  • [bugfix] method get on Query objects was never returning the object

Flask-MongoAlchemy 0.3

  • Introduced update queries support

Flask-MongoAlchemy 0.2

  • Reverse compatibility broken on Document class. The get() method was moved to BaseQuery class. Here the old code, on version 0.1:

    >>> Document.get(mongo_id)
    

    And the new code, on version 0.2:

    >>> Document.query.get(mongo_id)
    
  • Added get_or_404, first_or_404 and paginate methods on BaseQuery class. Check the documentation to know how to use them :)

flask-mongoalchemy's People

Contributors

arturhoo avatar barroca avatar chimeracoder avatar fsouza avatar jeverling avatar marcopg avatar matthewhartstonge avatar misja avatar tresbailey avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flask-mongoalchemy's Issues

How to use remove()?

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)

get and get_or_404 do never return object

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.

mongoalchemy import error

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.

Versioning conflicts

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

No module named mongoalchemy

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

update pymongo2.2

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'

How to query document using key

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"]

Incompatible with the latest pymongo

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'

Documentation for field types

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...

Multiple wsgi apps cause BadValue / ObjectID exception

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.

Flask-MongoAlchemy downgrades my Flask

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

MongoDB URI should include the database

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

calling append() on a ListField changes the default value

Thanks for this great package!

On object creation, where:

  • an attribute's Field.default has been defined, and
  • an attribute value is not specified in **kwargs

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

Enable Timezone on driver

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.

Flask-Admin possible?

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.

'NoneType' object has no attribute 'filter'

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

Connection URI string still requires setting of a DATABASE variable.

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 . . .)

Bug Fix for Book Collections

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 @@

Use of this source code is governed by a BSD-style

license that can be found in the LICENSE file.

-from flaskext import wtf
+from flask.ext import wtf

Unable to use $near

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()

suggestion for query simplification

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()

Bug on query methods

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.

Refactor tests code

Refactor some tests code and remove some duplicated or triplicated code on setup's.

Objects lose attributes?

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.