GithubHelp home page GithubHelp logo

mongoengine / flask-mongoengine Goto Github PK

View Code? Open in Web Editor NEW
842.0 29.0 253.0 1.16 MB

MongoEngine flask extension with WTF model forms support

License: Other

Python 96.89% HTML 2.95% Dockerfile 0.16%
flask mongondb mongoengine wtforms

flask-mongoengine's Introduction

MongoEngine

Info:MongoEngine is an ORM-like layer on top of PyMongo.
Repository:https://github.com/MongoEngine/mongoengine
Author: Harry Marr (http://github.com/hmarr)
Maintainer:Stefan Wójcik (http://github.com/wojcikstefan)
https://travis-ci.org/MongoEngine/mongoengine.svg?branch=master https://coveralls.io/repos/github/MongoEngine/mongoengine/badge.svg?branch=master https://pepy.tech/badge/mongoengine/month

About

MongoEngine is a Python Object-Document Mapper for working with MongoDB. Documentation is available at https://mongoengine-odm.readthedocs.io - there is currently a tutorial, a user guide, and an API reference.

Supported MongoDB Versions

MongoEngine is currently tested against MongoDB v3.6, v4.0, v4.4, v5.0, v6.0 and v7.0. Future versions should be supported as well, but aren't actively tested at the moment. Make sure to open an issue or submit a pull request if you experience any problems with a more recent MongoDB versions.

Installation

We recommend the use of virtualenv and of pip. You can then use python -m pip install -U mongoengine. You may also have setuptools and thus you can use easy_install -U mongoengine. Another option is pipenv. You can then use pipenv install mongoengine to both create the virtual environment and install the package. Otherwise, you can download the source from GitHub and run python setup.py install.

The support for Python2 was dropped with MongoEngine 0.20.0

Dependencies

All of the dependencies can easily be installed via python -m pip. At the very least, you'll need these two packages to use MongoEngine:

  • pymongo>=3.4

If you utilize a DateTimeField, you might also use a more flexible date parser:

  • dateutil>=2.1.0

If you need to use an ImageField or ImageGridFsProxy:

  • Pillow>=2.0.0

If you need to use signals:

  • blinker>=1.3

Examples

Some simple examples of what MongoEngine code looks like:

from mongoengine import *
connect('mydb')

class BlogPost(Document):
    title = StringField(required=True, max_length=200)
    posted = DateTimeField(default=datetime.datetime.utcnow)
    tags = ListField(StringField(max_length=50))
    meta = {'allow_inheritance': True}

class TextPost(BlogPost):
    content = StringField(required=True)

class LinkPost(BlogPost):
    url = StringField(required=True)

# Create a text-based post
>>> post1 = TextPost(title='Using MongoEngine', content='See the tutorial')
>>> post1.tags = ['mongodb', 'mongoengine']
>>> post1.save()

# Create a link-based post
>>> post2 = LinkPost(title='MongoEngine Docs', url='hmarr.com/mongoengine')
>>> post2.tags = ['mongoengine', 'documentation']
>>> post2.save()

# Iterate over all posts using the BlogPost superclass
>>> for post in BlogPost.objects:
...     print('===', post.title, '===')
...     if isinstance(post, TextPost):
...         print(post.content)
...     elif isinstance(post, LinkPost):
...         print('Link:', post.url)
...

# Count all blog posts and its subtypes
>>> BlogPost.objects.count()
2
>>> TextPost.objects.count()
1
>>> LinkPost.objects.count()
1

# Count tagged posts
>>> BlogPost.objects(tags='mongoengine').count()
2
>>> BlogPost.objects(tags='mongodb').count()
1

Tests

To run the test suite, ensure you are running a local instance of MongoDB on the standard port and have pytest installed. Then, run pytest tests/.

To run the test suite on every supported Python and PyMongo version, you can use tox. You'll need to make sure you have each supported Python version installed in your environment and then:

# Install tox
$ python -m pip install tox
# Run the test suites
$ tox

Community

Contributing

We welcome contributions! See the Contribution guidelines

flask-mongoengine's People

Contributors

9nix00 avatar almogcohen avatar alysivji avatar andrewelkins avatar anemitz avatar atroche avatar denny0223 avatar idocyabra avatar insspb avatar itsnauman avatar jcass77 avatar joeshaw avatar lafrech avatar losintikfos avatar lucasvo avatar mapio avatar mrjoes avatar mtsgrd avatar noirbizarre avatar peterkharchenko avatar rodcloutier avatar rozza avatar sdayu avatar sibelius avatar stephenbrown2 avatar thomasst avatar timgates42 avatar touilleman avatar wojcikstefan avatar xintron 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flask-mongoengine's Issues

Trouble with form customization through model_form

Not sure if bug: I have trouble with customization of complex fields through model_form

field_args = {'myfield': {'label': 'Custom label'}} works with db.StringField(), but have no effect with db.ListField(db.StringField())

import flask
from flask.ext.mongoengine import MongoEngine
from flask.ext.mongoengine.wtf import model_form
from wtforms import widgets

app = flask.Flask(__name__)
app.config.from_object(__name__)
app.config['MONGODB_SETTINGS'] = {'DB': 'testing'}
app.config['SECRET_KEY'] = "foo"
app.debug = True
db = MongoEngine()
db.init_app(app)

class TestModel(db.Document):
    text = db.StringField()
    lst = db.ListField(db.StringField())

GenericForm = model_form(TestModel)
CustomForm = model_form(TestModel, field_args = {'text': {'label': 'Custom label', 'widget': widgets.TextInput()}, 
                                                 'lst':  {'label': 'Custom label', 'widget': widgets.HiddenInput()}})

@app.route('/')
def index():    
    document = TestModel.objects().first()
    generic_form = GenericForm(obj=document)
    custom_form  = CustomForm(obj=document)
    return flask.render_template_string("""
            Generic form: <br><br>
                {{ generic_form.text.label }} {{ generic_form.text }}  <br>
                {{ generic_form.lst.label }} {{ generic_form.lst }} 

            <br><br>

            Custom form: <br><br>
            This one has custom label and widget: <br>
                {{ custom_form.text.label }} {{ custom_form.text }}  <br><br>
            But this - same as generic <br>
                {{ custom_form.lst.label }} {{ custom_form.lst }}
        """, generic_form=generic_form, custom_form=custom_form)

if __name__ == "__main__":
    TestModel.objects().delete()
    TestModel(text="foo", lst=["bar"]).save()    
    app.run(host="0.0.0.0", port=4000)

Broken model_form with only

class FFF(db.Document):
    a = IntField()
    b = StringField()
    c = BooleanField()


FFForm = model_form(FFF, only=['b'])

    FFForm = model_form(FFF, only=['b'])
  File "C:\Python27\lib\site-packages\flask_mongoengine\wtf\orm.py", line 269, in model_form
    field_dict = model_fields(model, only, exclude, field_args, converter)
  File "C:\Python27\lib\site-packages\flask_mongoengine\wtf\orm.py", line 235, in model_fields
    for name in field_names:
  File "C:\Python27\lib\site-packages\flask_mongoengine\wtf\orm.py", line 230, in <genexpr>
    field_names = (x for x in only if x in field_names)
ValueError: generator already executing

model_form doesn't validate StringField's inside ListField

I have the following inside a document class

tags = db.ListField(db.StringField(max_length=30, min_length=1), required=True)

I use the model_form to create the form.

If I send back a tag field with no content the form.validate() function should return False.
Instead, the function is returning True.
It is then left to Mongo to pick up the validation error and throw an exception.

ValidationError (Post:51ad4c74c47f3e07507984f4) (3.String value is too short: ['tags'])

The form.validate() function should validate the contents of ListField's.

IndexError: list index out of range with mongoengine 0.8 RC2

When

Traceback (most recent call last):
File "C:\Users\choffman\Desktop\venv\lib\site-packages\flask\app.py", line 170
1, in call
return self.wsgi_app(environ, start_response)
File "C:\Users\choffman\Desktop\venv\lib\site-packages\flask\app.py", line 168
9, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Users\choffman\Desktop\venv\lib\site-packages\flask\app.py", line 168
7, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\choffman\Desktop\venv\lib\site-packages\flask\app.py", line 136
0, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\choffman\Desktop\venv\lib\site-packages\flask\app.py", line 135
8, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\choffman\Desktop\venv\lib\site-packages\flask_debugtoolbar__in
it__.py", line 101, in dispatch_request
return view_func(*_req.view_args)
File "C:\Users\choffman\Desktop\configurator\application\views.py", line 7, in
index
users = Setting.objects.all()
File "C:\Users\choffman\Desktop\venv\lib\site-packages\mongoengine\queryset\ma
nager.py", line 37, in get
queryset = queryset_class(owner, owner._get_collection())
File "C:\Users\choffman\Desktop\venv\lib\site-packages\mongoengine\document.py
", line 157, in _get_collection
cls.ensure_indexes()
File "C:\Users\choffman\Desktop\venv\lib\site-packages\mongoengine\document.py
", line 544, in ensure_indexes
drop_dups=drop_dups, *_opts)
File "C:\Users\choffman\Desktop\venv\lib\site-packages\pymongo\collection.py",
line 916, in ensure_index
return self.create_index(key_or_list, cache_for, *_kwargs)
File "C:\Users\choffman\Desktop\venv\lib\site-packages\pymongo\collection.py",
line 823, in create_index
*_self._get_wc_override())
File "C:\Users\choffman\Desktop\venv\lib\site-packages\flask_mongoengine\opera
tion_tracker.py", line 67, in _insert
'size': response_sizes[-1],
IndexError: list index out of range

Debugtoolbar misses query and double inheritance=dobule save and object doesn't save

import flask
import datetime
from flask.ext.mongoengine import MongoEngine
from flask_debugtoolbar import DebugToolbarExtension
from mongoengine import *
from mongoengine.queryset import QuerySet

app = flask.Flask(__name__)
app.config['SECRET_KEY']       = 'not so secret'
app.config['DEBUG_TB_PANELS']  = ('flask.ext.mongoengine.panels.MongoDebugPanel',)
app.debug = True

db = MongoEngine()
db.init_app(app)
DebugToolbarExtension(app)

class AwesomerQuerySet(QuerySet):
    pass
    def filter_project(self, project_id):
        gt = int(str(project_id)+"000000000000")
        lt = int(str(project_id)+"999999999999")
        return self.__call__(pk__gte=int(str(project_id)+"000000000000")).filter(pk__lte=int(str(project_id)+"999999999999"))
    def filter_date(self,project_id,date,gt=False):
        date_int = int(str(project_id)+str(int(time.mktime(date.timetuple()) * 100 + random.randrange(99))))
        return self.__call__(pk__gt=date_int) if gt else self.__call__(pk__lt=date_int)


class PP(db.Document):
    theid= SequenceField(primary_key=True)

class Parent(object):
    updated = DateTimeField(db_field="2")
    created = IntField(primary_key=True)

    meta = {'cascade': False, 'allow_inheritance': False, 'queryset_class': AwesomerQuerySet}

    @classmethod
    def pre_save(cls, sender, document, **kwargs):
        document.gen_pk()
        print "pre_save"

    def gen_pk(self):
        self.created = str(self.project.pk)+str(int(time.mktime(datetime.datetime.utcnow().timetuple()) * 100 + random.randrange(99)))

class One(Parent,db.Document):
    related_videos = ListField(ReferenceField('Video',dbref=False),db_field="r")
    ssss = StringField()
    title = StringField(db_field="t")
    meta = {'cascade': False, 'allow_inheritance': False, 'queryset_class': AwesomerQuerySet}

signals.pre_save.connect(One.pre_save, sender=One)

@app.route('/test/')
def domain_testing():
    pp = PP()
    pp.save()
    one = One(project=pp)
    one.save()


    return render_template("empty.html")

The problems:

Save is triggered twice on the One class.
There should be 3 queries in the toolbar:
1.PP created
2.One create
3.One updated.
Only 3 is in the toolbar. PP object is not saved in the db. Ignore the queryset.

Debugtoolbar error when inserting using Class._get_collection().insert ()

from flask import Flask
from mongoengine import *
from flask_debugtoolbar import DebugToolbarExtension
from flask_mongoengine import MongoEngine

db = MongoEngine()

app = Flask(__name__)
app.config['MONGODB_DB'] = 'test'
app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False
app.config['DEBUG_TB_PANELS'] = (
    'flask.ext.debugtoolbar.panels.versions.VersionDebugPanel',
    'flask.ext.debugtoolbar.panels.timer.TimerDebugPanel',
    'flask.ext.debugtoolbar.panels.headers.HeaderDebugPanel',
    'flask.ext.debugtoolbar.panels.request_vars.RequestVarsDebugPanel',
    'flask.ext.debugtoolbar.panels.template.TemplateDebugPanel',
    'flask.ext.debugtoolbar.panels.logger.LoggingPanel',
    'flask_debugtoolbar.panels.profiler.ProfilerDebugPanel',
    'flask.ext.mongoengine.panels.MongoDebugPanel',
    )
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'

app.debug = True
db.init_app(app)
DebugToolbarExtension(app)

class Projection(db.Document):
    sequence = StringField()

@app.route('/')
def testing():
    Projection._get_collection().insert({'a':1234})

    return ''

if __name__ == '__main__':
    app.run()

.save() does not work

flask 0.10.1, python 2.7.5, mogoengine 0.8.3, mongoDB v2.4.5,
I'm trying to save User with schema
class User(Document):
email = StringField(required=True)
first_name = StringField(max_length=50)
last_name = StringField(max_length=50)

ross = User(email='[email protected]', first_name='Ross', last_name='Lawley').save()
and happen nothing, after save(),nothing is stored in the mongodb, db is empty

1

1

Cannot Install flask-mongoengine through pip

I'm using pycharm on windows 7 64bit and I'm able to install other packages as I want to, except flask-mongoengine (through pypi.python.org/pypi repos).

Error returned quite much as yet I don't know how to solve it all. But I saw this at the end:

distutils.errors.DistutilsError: Setup script exited with error: Unable to find vcvarsall.bat

I've tested to manually install under my windows env (include reinstall setup-tools, easy_install and pip), and another try under Linux Mint. There's no luck neithe, with the same error.

Is there any problem with the package at the moment?

Thanks.

Debug toolbar panel does not work on Python 3

Trying to get the debug toolbar panel work with Python 3.3 needs a couple of small code tweaks.

Many tests fail then though, but that might be more generally a problem with Python 3 and Flask-MongoEngine?

See arsgeografica/flask-mongoengine@bf9d237202a62f73c2a0ec90383e26bd40a13187 for my changes.

NoneBlankField does not work with flask-admin (i.e. prevents validation of EmailField)

The fix described in #9 seems to break flask-admin.

More precisely, given the following test case

from flask import Flask

from flask.ext import admin
from flask.ext.admin.contrib.mongoengine import ModelView
from flask.ext.mongoengine import MongoEngine

db = MongoEngine()

class TestDocument( db.Document ):
    email = db.EmailField( required = False )

app = Flask( __name__ )
app.config[ 'SECRET_KEY' ] = '123456790'
app.config['MONGODB_SETTINGS'] = {'DB': 'testing'}

db.init_app( app )
adm = admin.Admin( app, 'TestCase' )
adm.add_view( ModelView( TestDocument ) )

if __name__ == '__main__':
    app.run()

If one tries to create a new record None appears as the default value for the email field – this is a first bug.

If a save is attempted a form validation error happens (since, of course, None is not a valid email address):

dece3c02-b331-11e2-8d5d-888356aa6e42

In the case the field is first cleaned (leaving it empty) and then saved, a model validation happens – this is a second bug, given that if the forms validate, the model should also:

screen shot 2013-05-02 at 4 04 40 pm

(observe that in the screenshot None reappeared as the field value, even if it was empty before the save button was hit).

Connection by MongoDB URI

I think it would be cleaner to enable configuration using a MongoDB URI, which can be parsed to fill in the required environment variables.

For example, storing a simple 1-variable URI in the environment

MONGODB_URI = 'mongodb://test:[email protected]/testdb'

Which is then parsed and used for the connection, if present.

Is there a design choice to not enable this feature, or is it something you'd consider a patch for?

How I must overriding update method in ORM class

Example code not working:

class PaymentSystem(db.Document):
    title = db.StringField(min_length=3, max_length=40)
    module_name = db.StringField(min_length=3, max_length=40)
    comission_type = db.IntField(choices=COMMISSION_TYPES)
    commission_value = db.FloatField(default=0.0)
    config = db.StringField(max_length=1024)

    def update(self, **kwargs):
        print 'update', kwargs

    def __unicode__(self):
        return self.title

mongoengine 0.8.0RC4
flask-mongoengine 0.7.0RC1

maybe it not working because I change update with Flask-Admin

UnicodeDecodeError in MongoDebugPanel

This error occurs when MongoDebugPanel trying to build a stack trace and there are non-ascii comments in source code

# coding: utf-8

import flask
from flask.ext.mongoengine import MongoEngine
from flask.ext.debugtoolbar import DebugToolbarExtension
from mongoengine import StringField, ListField, Document

app = flask.Flask(__name__)
app.config.from_object(__name__)
app.config['MONGODB_SETTINGS'] = {'DB': 'testing'}
app.config['SECRET_KEY'] = "foo"
app.config['DEBUG_TB_PANELS'] = ('flask.ext.mongoengine.panels.MongoDebugPanel',)

app.debug = True
db = MongoEngine()
db.init_app(app)
DebugToolbarExtension(app)

class TestModel(Document):
    text = StringField()

@app.route('/')
def index():    
    TestModel(text="foo").save() # ПЫЩЬ! - this comment triggers UnicodeDecodeError
    return flask.render_template_string("<html><body></body></html>")

if __name__ == "__main__":     
    app.run(host="0.0.0.0", port=4000)

So, we need something like this in operation_tracker.py:_tidy_stacktrace()

try:
    text = ''.join(text).strip().decode('utf-8').strip()
except UnicodeDecodeError:
    text = "[BAD UNICODE DATA] %s:%s" % (path, line_no)
    # it would be better to display this as string-escape
    # but I've lost with this unicode mess

Not working select by ObjectId

Not working those code:

class Currency(db.Document):
    title = db.StringField(max_length=40, min_length=3)

class ExchangeRate(db.Document):
    in_currency = db.ReferenceField(Currency)
    out_currency = db.ReferenceField(Currency)

ExchangeRate.objects(in_currency=in_currency)

in result empty list
in_currency - ObjectId string like '5188a1deb071b651323d7e89'
few days before all worked ok
mongoengine 0.8RC2
can`t downgrade by pip for testing
flask-mongoenigne latest from github

Broken model_form with field:ListField(IntField(choices))

class FFF(db.Document):
    choices666 = ((1, 'choice1'), (2, 'choice2'))
    d = ListField(IntField(choices=choices666))

FFForm = model_form(FFF)

  File "C:/djang/flaskConvert/some.py", line 20, in <module>
    FFForm = model_form(FFF)
  File "C:\Python27\lib\site-packages\flask_mongoengine\wtf\orm.py", line 269, in model_form
    field_dict = model_fields(model, only, exclude, field_args, converter)
  File "C:\Python27\lib\site-packages\flask_mongoengine\wtf\orm.py", line 237, in model_fields
    field = converter.convert(model, model_field, field_args.get(name))
  File "C:\Python27\lib\site-packages\flask_mongoengine\wtf\orm.py", line 78, in convert
    return self.converters[ftype](model, field, kwargs)
  File "C:\Python27\lib\site-packages\flask_mongoengine\wtf\orm.py", line 158, in conv_List
    return self.convert(model, field.field, **kwargs)
TypeError: convert() got an unexpected keyword argument 'multiple'

You have not defined a default connection

How I can resolve this error?

  File "/usr/local/lib/python2.7/dist-packages/mongoengine/connection.py", line 95, in get_connection
    raise ConnectionError(msg)
mongoengine.connection.ConnectionError: You have not defined a default connection

model.py:

from flask.ext.mongoengine import MongoEngine

db = MongoEngine()

class Currencies(db.Document):
    # meta = {"db_alias": "currencies"}
    name = db.StringField(max_length=40, min_length=3)
    def __unicode__(self):
        return self.name

mongo engine config in app.py:

from models import db

app = Flask(__name__)
app.config['MONGODB_SETTINGS'] = {'DB':'testing'}
db.init_app(app)

views.py:

from models import Currencies

print Currencies.objects.find()

Flask-Admin normally work

TypeError: __init__() got an unexpected keyword argument

I am using flask-mongoengine extension and I have a User class like this:

class User(db.Document, UserMixin):     
    email = db.StringField(max_length=120, required=True, unique=True)
    password_hash = db.StringField(max_length=80, required=True)   
    active = db.BooleanField()
    fb_id = db.StringField(max_length=120, required=False)

    def __init__(self, email, password, fb_id=None, active=True):           
        hashp = md5.md5(password).hexdigest()        
        self.email=email
        self.password_hash=hashp
        self.fb_id=fb_id
        self.active=active

But when I do a simple get: User.objects.get(email = email)

I get the error:

TypeError: __init__() got an unexpected keyword argument 'password_hash'

but I am setting the password_hash in my init though. Surprisingly, if I delete the whole __init__ and pass in everything by args, it works fine.

So I recon I am doing something wrong in the __init__, maybe something due the document super class? I am quite stuck on this, would appreciate your help.

Unique flag not reflected in WTForms validation

It seems like the unique flag in MongoEngine is not reflected properly in the WTForms validation. I have a model like this (where the email is unique):

class User(database.Document):
    """ User model """
    email = database.EmailField(required=True, unique=True)
    first_name = database.StringField(required=True, max_length=30)
    last_name = database.StringField(required=True, max_length=30)
    password = database.StringField(required=True)
    is_active = database.BooleanField(default=False)
    is_authenticated = database.BooleanField(default=False)

But when I save this I get a mongoengine.errors.NotUniqueError from MongoEngine. I expected to get an error message from the form validation instead.

You have not defined a default connection

How I can resolve this error?

  File "/usr/local/lib/python2.7/dist-packages/mongoengine/connection.py", line 95, in get_connection
    raise ConnectionError(msg)
mongoengine.connection.ConnectionError: You have not defined a default connection

model.py:

from flask.ext.mongoengine import MongoEngine

db = MongoEngine()

class Currencies(db.Document):
    # meta = {"db_alias": "currencies"}
    name = db.StringField(max_length=40, min_length=3)
    def __unicode__(self):
        return self.name

mongo engine config in app.py:

from models import db

app = Flask(__name__)
app.config['MONGODB_SETTINGS'] = {'DB':'testing'}
db.init_app(app)

views.py:

from models import Currencies

print Currencies.objects.find()

Flask-Admin normally work

BinaryField does not work with flask-admin

The following small testcase

from flask import Flask

from flask.ext import admin
from flask.ext.admin.contrib.mongoengine import ModelView
from flask.ext.mongoengine import MongoEngine

db = MongoEngine()

class TestDocument( db.Document ):
    blob = db.BinaryField()

app = Flask( __name__ )
app.config[ 'SECRET_KEY' ] = '123456790'
app.config['MONGODB_SETTINGS'] = {'DB': 'testing'}

db.init_app( app )
adm = admin.Admin( app, 'TestCase' )
adm.add_view( ModelView( TestDocument ) )

if __name__ == '__main__':
    app.run()

gives the error you see in the snapshot below (nothing changes if the field is not left empty)

image

improve pagination example:

Great example code, however maybe it's nice to show in the example how to get to the actual paginated items:

(view)
paginated_comments = post.paginate_field('comments', page, per_page=3)

(template)
{% for comment in paginated_comments.items %} ..

unique_with not enforced

I'm referencing an issue from MongoEgine, since it seems to be related to Flask: MongoEngine/mongoengine#205

Here is the original issue, I have the same problem with mongoengine==0.7.9:

I'm able to create multiple documents with the same values in the fields I've defined using unique_with. I'm using mongoengine in conjunction with flask-mongoengine in my flask app.

Here's my document definition:

class Item (db.Document):

    owner_id = db.ObjectIdField(required=True)
    owner_item_id = db.StringField(required=True, unique_with = 'owner_id')

Using the above document definition, I'm able to create multiple Items using the same owner_id and owner_item_id combination. The only time the NotUniqueError exception is thrown is the first time time I insert a duplicate document after I restart my local flask app. Every time after that, I can create as many duplicate documents as I wish.

Versions:
flask-mongoengine==0.6
mongoengine==0.7.8

Password field support and automatic submit button in forms

I'm using the form generator to avoid creating forms and having redundant code.

I've got two suggestions that could be useful:

  1. When using jinja2 and WTForms {{ form.submit }} works when the class is declared in the usual way with a SubmitField. I think the point of a form is to do a POST or PUT request but adding HTML manually to a template seems pretty lame. I think adding it would be much better.
  2. PasswordField for variable names such as password or pass would be useful to say the least. For example:
#Declaration in model
class User(Document):
    #other fields
    password = StringField(required=True, max_length=50)
    #other fields

#Form
class UserForm():
    #other fields
    password = PasswordField("Password",  [validators.Required()])
    #other fields
    submit = SubmitField("Send") 

It's lackluster comparing it to the original WTForms package... they're key points, at least for me.

model_form fails for ListField of EmbeddedDocumentField declared using a string

This is probably related to #23. If the model contains a ListField wrapping an EmbeddedDocumentField and the latter is built from a string, then model_form fails.

The following code shows the problem

from flask.ext.mongoengine import MongoEngine
from flask.ext.mongoengine.wtf import model_form

db = MongoEngine()

class EmbedMe( db.EmbeddedDocument ):
    afield = db.StringField()

class Outer( db.Document ):
    embedded = db.ListField( db.EmbeddedDocumentField( EmbedMe ) )

class OuterString( db.Document ):
    embedded = db.ListField( db.EmbeddedDocumentField( 'EmbedMe' ) )

print model_form( Outer )
print model_form( OuterString )

I'm sure I can provide a failing test based on aa6f13c and the snippet above, but I'm not sure I can also provide a fix.

Dear @rozza, can you help?

[RFE] Reap expired sessions

It would be great if there was an option to allow users to enable some form of reaping of expired sessions. A suggested solution might be to reap if an expired session is encountered, this way reaping is seamless. The alternative is to provide a user callable method to perform a clean up.

model_form doesn't validate (CSRF token missing') csrf_token is in fact inserted 0.7

class Channel(db.Document):
    title = StringField()

form = model_form(Channel, only=['title'])
if form.validate_on_submit():
    pass
return render_template('app.html', form=form)

in app.html

{{ form.errors }}
<form method='post'>
{{ form.csrf_token }}
{{ form.title }}
<input type="submit">
</form>

If i change the form to a normal flask_wtf Form it works!

Can't connect to remote database.

This repo seems more active, so let's try here. Original bug report: https://github.com/sbook/flask-mongoengine/issues/19

Traceback (most recent call last):
  File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/flask/app.py", line 1518, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/flask/app.py", line 1506, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/flask/app.py", line 1504, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/flask/app.py", line 1264, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/flask/app.py", line 1262, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/flask/app.py", line 1248, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/jonas/workspace/checklists/auth.py", line 58, in _decorate
    return view(*args, **kwargs)
  File "/home/jonas/workspace/checklists/app.py", line 70, in home
    return render_template('home.html', templates=templates, checklists=checklists)
  File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/flask/templating.py", line 123, in render_template
    context, ctx.app)
  File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/flask/templating.py", line 107, in _render
    rv = template.render(context)
  File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/jinja2/environment.py", line 894, in render
    return self.environment.handle_exception(exc_info, True)
  File "/home/jonas/workspace/checklists/templates/home.html", line 1, in top-level template code
    {% extends "base.html" %}
  File "/home/jonas/workspace/checklists/templates/base.html", line 38, in top-level template code
    {% block content %}
  File "/home/jonas/workspace/checklists/templates/home.html", line 14, in block "content"
    {% for template in templates %}
  File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/mongoengine/queryset.py", line 1494, in __iter__
    self.rewind()
  File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/mongoengine/queryset.py", line 975, in rewind
    self._cursor.rewind()
  File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/mongoengine/queryset.py", line 581, in _cursor
    self._cursor_obj = self._collection.find(self._query,
  File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/mongoengine/queryset.py", line 555, in _collection
    if self._collection_obj.name not in db.collection_names():
  File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/pymongo/database.py", line 363, in collection_names
    names = [r["name"] for r in results]
  File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/pymongo/cursor.py", line 747, in next
    if len(self.__data) or self._refresh():
  File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/pymongo/cursor.py", line 698, in _refresh
    self.__uuid_subtype))
  File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/pymongo/cursor.py", line 657, in __send_message
    self.__tz_aware)
  File "/home/jonas/workspace/checklists/env/lib/python2.7/site-packages/pymongo/helpers.py", line 102, in _unpack_response
    error_object["$err"])
OperationFailure: database error: unauthorized db:mydb lock type:-1 client:84.226.127.220

model_form Forms return '' instead of None for empty fields.

The email field validates '' differently than None. '' is an invalid email, None is a valid input. model_form based Forms return the wrong data.

from flask import Flask
from flask.ext.mongoengine import MongoEngine
import unittest
from flask.ext.mongoengine.wtf import model_form
from werkzeug.datastructures import MultiDict

app = Flask(__name__)

app.config.update(
    DEBUG = True,
    TESTING = True,
    MONGODB_HOST = 'localhost',
    MONGODB_PORT = '27017',
    MONGODB_DB = 'mongorest_example_app',
)

db = MongoEngine(app)

class User(db.Document):
    email = db.EmailField(required=False)
    name = db.StringField()

class FieldTestCase(unittest.TestCase):
    def setUp(self):
        self.app = app.test_client()

    def test_emptyemail(self):
        with app.test_request_context('/?name=Peter'):
            TestForm = model_form(User)
            data = MultiDict({'name':'John Doe'})
            form = TestForm(data,csrf_enabled=False)
            assert form.validate()
            assert form.data['email'] == None
# form.data['email'] is '' instaed of None

DynamicDocument: IntField returns as an ObjectId Field

I have an IntField in my DynamicDocument that is being returned as an 'ObjectId' field.
If I query the field directly in mongo, I see:

    { "fid" : 10200331 }

However if I print the field using flask-mongoengine, I see a hash of the int value and if I print the type, I see:

     <class 'bson.objectid.ObjectId'> 

When it should be:

     <type 'unicode'>.

My model is defined like this:

    class Alert(db.DynamicDocument):
        meta = {'collection': 'alerts'}
        fid = db.IntField(required=True, unique=True)

        def __init__(self, **kwargs):
            kwargs['fid'] = kwargs['id']
            kwargs.pop('id')
            super(Alert, self).__init__(**kwargs)

I've got other integers that are being interpreted correctly, but this is not. Any idea what's going on?

Debug toolbar doesn't log empty MongoDB queries

e.g.

import flask
from flask.ext.mongoengine import MongoEngine
from flask_debugtoolbar import DebugToolbarExtension

app = flask.Flask(__name__)
app.config['SECRET_KEY']       = 'not so secret'
app.config['MONGODB_SETTINGS'] = {'DB': 'testing'}
app.config['DEBUG_TB_PANELS']  = ('flask.ext.mongoengine.panels.MongoDebugPanel',)
app.debug = True

db = MongoEngine()
db.init_app(app)
DebugToolbarExtension(app)

class TestModel(db.Document):
    meta = {"collection": "test", "allow_inheritance": False}
    name = db.StringField()

@app.route('/')
def index():
    names = [item.name for item in TestModel.objects().all()]
    return "<html><body>Query result: %s</body></html>" % ', '.join(names)

if __name__ == "__main__":

    if not TestModel.objects:
        TestModel(name="Alice").save()
        TestModel(name="Bob").save()

    app.run(host="0.0.0.0", port=5000) 

Debug says "No queries recorded", however there was an empty {} query and it has returned some data

Lines 148, 149 in operation_tracker.py seems unnecessary

        if not query_son:
            return result

Debugtoolbar — tidy_stacktrace issue

I've noticed an ambiguous behavior of operation_tracker.py:_tidy_stacktrace() function: if your project located somewhere in "/var/www/html/myproject/", all queries will be marked as internal and hidden.

Probably here we must check file extension but not just "html" substring?

            fname = sys._getframe(i).f_code.co_filename
            if 'html' in fname:
                fnames.append(fname)

example app not running

accessing the sample app results in the following trace:

(fm)hideo  flask-mongoengine git:(master) python example/simpleapp.py 
 * Running on http://0.0.0.0:4000/
 * Restarting with reloader
Traceback (most recent call last):
  File "/home/matt/conf/virtualenvs/fm/lib/python2.7/site-packages/flask/app.py", line 1701, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/matt/conf/virtualenvs/fm/lib/python2.7/site-packages/flask/app.py", line 1689, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/home/matt/conf/virtualenvs/fm/lib/python2.7/site-packages/flask/app.py", line 1687, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/matt/conf/virtualenvs/fm/lib/python2.7/site-packages/flask/app.py", line 1360, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/matt/conf/virtualenvs/fm/lib/python2.7/site-packages/flask/app.py", line 1358, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/matt/conf/virtualenvs/fm/lib/python2.7/site-packages/flask_debugtoolbar/__init__.py", line 101, in dispatch_request
    return view_func(**req.view_args)
  File "/home/matt/fm/flask-mongoengine/example/simpleapp.py", line 50, in index
    Todo(title="Simple todo A", text="12345678910").save()  # Insert
  File "/home/matt/conf/virtualenvs/fm/lib/python2.7/site-packages/mongoengine/document.py", line 199, in save
    object_id = collection.save(doc, safe=safe, **write_options)
  File "/home/matt/conf/virtualenvs/fm/lib/python2.7/site-packages/pymongo/collection.py", line 241, in save
    return self.insert(to_save, manipulate, safe, check_keys, **kwargs)
TypeError: _insert() takes at most 4 arguments (5 given)

Next Milestone Questions & Call for Maintainers!

@anemitz & @thomasst do you guys have any plans for the next milestone / release of flask-mongoengine?

Unfortunately, I dont have the time available at the minute to fix the issues and push a release. If you are in the same boat, I'm happy to try and draft in more maintainers!

Any potential maintainers - please post here if you want to help further flask-mongoengine - I'm happy to mentor as well!

Broken with Mongoengine 0.8RC1

Traceback (most recent call last):
File "C:/djang/flaskAPI/wsgi.py", line 10, in
from flask_mongoengine.wtf.orm import model_form
File "C:\Python27\lib\site-packages\flask_mongoengine__init__.py", line 9, in
from mongoengine.base import ValidationError
ImportError: cannot import name ValidationError

Image and File fields interfaces

You have mentioned in the documentation that only 3 types of Fields are yet to be addressed like Geo, Obj, etc. Is there a plan to incorporate Image fields and File fields to enable web developers to focus on the layout and allow flask-mongoengine to act as the end to end broker?

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.