def setUp(self):
        super(BasicAppTestCase, self).setUp()
        db = MongoEngine()

        class Todo(db.Document):
            title = db.StringField(max_length=60)
            text = db.StringField()
            done = db.BooleanField(default=False)
            pub_date = db.DateTimeField(default=datetime.datetime.now)

        db.init_app(self.app)

        Todo.drop_collection()
        self.Todo = Todo

        @self.app.route('/')
        def index():
            return '\n'.join(x.title for x in self.Todo.objects)

        @self.app.route('/add', methods=['POST'])
        def add():
            form = flask.request.form
            todo = self.Todo(title=form['title'],
                             text=form['text'])
            todo.save()
            return 'added'

        @self.app.route('/show/<id>/')
        def show(id):
            todo = self.Todo.objects.get_or_404(id=id)
            return '\n'.join([todo.title, todo.text])

        self.db = db
예제 #2
0
    def setUp(self):
        super(JSONAppTestCase, self).setUp()
        self.app.config['MONGODB_DB'] = 'testing'
        self.app.config['TESTING'] = True
        db = MongoEngine()

        class Todo(db.Document):
            title = db.StringField(max_length=60)
            text = db.StringField()
            done = db.BooleanField(default=False)
            pub_date = db.DateTimeField(default=datetime.datetime.now)

        db.init_app(self.app)

        Todo.drop_collection()
        self.Todo = Todo

        @self.app.route('/')
        def index():
            return flask.jsonify(result=self.Todo.objects())

        @self.app.route('/add', methods=['POST'])
        def add():
            form = flask.request.form
            todo = self.Todo(title=form['title'],
                             text=form['text'])
            todo.save()
            return flask.jsonify(result=todo)

        @self.app.route('/show/<id>/')
        def show(id):
            return flask.jsonify(result=self.Todo.objects.get_or_404(id=id))

        self.db = db
예제 #3
0
    def setUp(self):
        app = flask.Flask(__name__)
        app.config['MONGODB_DB'] = 'testing'
        app.config['TESTING'] = True
        db = MongoEngine()
        self.Todo = make_todo_model(db)

        db.init_app(app)

        self.Todo.drop_collection()

        @app.route('/')
        def index():
            return '\n'.join(x.title for x in self.Todo.objects)

        @app.route('/add', methods=['POST'])
        def add():
            form = flask.request.form
            todo = self.Todo(title=form['title'],
                             text=form['text'])
            todo.save()
            return 'added'

        @app.route('/show/<id>/')
        def show(id):
            todo = self.Todo.objects.get_or_404(id=id)
            return '\n'.join([todo.title, todo.text])

        self.app = app
        self.db = db
예제 #4
0
 def setUp(self):
     super(JSONAppTestCase, self).setUp()
     self.app.config['MONGODB_DB'] = 'testing'
     self.app.config['TESTING'] = True
     self.app.json_encoder = DummyEncoder
     db = MongoEngine()
     db.init_app(self.app)
     self.db = db
예제 #5
0
    def setUp(self):
        app = flask.Flask(__name__)
        app.config['MONGODB_DB'] = 'testing'
        app.config['TESTING'] = True
        app.json_encoder = DummyEncoder
        db = MongoEngine()
        db.init_app(app)

        self.app = app
        self.db = db
예제 #6
0
 def test_connection_kwargs_with_false_values(self):
     self.app.config['MONGODB_SETTINGS'] = {
         'DB': 'testing',
         'alias': 'test',
         'use_greenlets': False
     }
     self.app.config['TESTING'] = True
     db = MongoEngine()
     db.init_app(self.app)
     self.assertFalse(db.connection.use_greenlets)
예제 #7
0
def setup():
    app = Flask(__name__)
    app.config['SECRET_KEY'] = '1'
    app.config['CSRF_ENABLED'] = False
    app.config['MONGODB_SETTINGS'] = {'DB': 'tests'}

    db = MongoEngine()
    db.init_app(app)

    admin = Admin(app)

    return app, db, admin
예제 #8
0
def get_db(database=None):
    if not database:
        database = conf.MONGODB_DB
    if os.environ.get("UNITTEST_MODE"):
        database = conf.MONGODB_DB_UNITTEST
    mongo = MongoEngine()
    mongo.connect(
        database,
        host=conf.MONGODB_HOST,
        port=conf.MONGODB_PORT,
        username=conf.MONGODB_USER,
        password=conf.MONGODB_PASSWD
    )
    return mongo
예제 #9
0
 def test_connection_kwargs_as_list(self):
     self.app.config['MONGODB_SETTINGS'] = [{
         'DB': 'testing_tz_aware',
         'alias': 'tz_aware_true',
         'TZ_AWARE': True
     }, {
         'DB': 'testing_tz_aware_off',
         'alias': 'tz_aware_false',
         'TZ_AWARE': False
     }]
     self.app.config['TESTING'] = True
     db = MongoEngine()
     db.init_app(self.app)
     self.assertTrue(db.connection['tz_aware_true'].tz_aware)
     self.assertFalse(db.connection['tz_aware_false'].tz_aware)
예제 #10
0
 def setUp(self):
     super(PaginationTestCase, self).setUp()
     self.db_name = 'testing'
     self.app.config['MONGODB_DB'] = self.db_name
     self.app.config['TESTING'] = True
     self.app.config['CSRF_ENABLED'] = False
     self.db = MongoEngine()
     self.db.init_app(self.app)
예제 #11
0
    def test_connection_kwargs(self):
        app = flask.Flask(__name__)
        app.config['MONGODB_SETTINGS'] = {
            'DB': 'testing_tz_aware',
            'alias': 'tz_aware_true',
            'TZ_AWARE': True,
        }
        app.config['TESTING'] = True
        db = MongoEngine()
        db.init_app(app)
        self.assertTrue(db.connection.tz_aware)

        app.config['MONGODB_SETTINGS'] = {
            'DB': 'testing',
            'alias': 'tz_aware_false',
        }
        db.init_app(app)
        self.assertFalse(db.connection.tz_aware)
예제 #12
0
    def setUp(self):
        self.db_name = 'testing'

        app = flask.Flask(__name__)
        app.config['MONGODB_DB'] = self.db_name
        app.config['TESTING'] = True
        app.config['CSRF_ENABLED'] = False
        self.app = app
        self.db = MongoEngine()
        self.db.init_app(app)
예제 #13
0
 def setUp(self):
     super(WTFormsAppTestCase, self).setUp()
     self.db_name = 'testing'
     self.app.config['MONGODB_DB'] = self.db_name
     self.app.config['TESTING'] = True
     # For Flask-WTF < 0.9
     self.app.config['CSRF_ENABLED'] = False
     # For Flask-WTF >= 0.9
     self.app.config['WTF_CSRF_ENABLED'] = False
     self.db = MongoEngine()
     self.db.init_app(self.app)
예제 #14
0
 def setUp(self):
     super(WTFormsAppTestCase, self).setUp()
     self.db_name = "testing"
     self.app.config["MONGODB_DB"] = self.db_name
     self.app.config["TESTING"] = True
     # For Flask-WTF < 0.9
     self.app.config["CSRF_ENABLED"] = False
     # For Flask-WTF >= 0.9
     self.app.config["WTF_CSRF_ENABLED"] = False
     self.db = MongoEngine()
     self.db.init_app(self.app)
예제 #15
0
파일: core_app.py 프로젝트: Scille/kalon
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     # Support objectid in url routing
     self.url_map.converters['objectid'] = ObjectIdConverter
     # Custom json encoder for objectid and pagination
     # Mix between flask's root_path (module's path) and running dir path
     self.root_path = abspath(dirname(__file__) + '/..')
     # Overload default request to return 400 if no payload is provided
     self.request_class = JsonRequest
     self.json_encoder = dynamic_json_encoder_factory()
     restful.representations.json.settings['cls'] = self.json_encoder
     self.db = MongoEngine()
     self.solr = Solr()
예제 #16
0
def create_app():
    app = Flask(__name__, static_folder='../public/', static_url_path='/public')
    app.response_class = ResponseJSON
    app.config.from_pyfile(config.FLASK_CONFIG_PATH)

    # change debug output formatter to a pretty one-liner
    format = Formatter("%(levelname)6s | %(relativeCreated)6d | %(filename)s:%(lineno)d | %(message)s")
    app.logger.handlers[0].setFormatter(format)

    # resolve paths relative to this file
    app_path = path.dirname(__file__)
    app.config.update({
        'RECORDINGS_PATH': path.realpath(app_path + '/../public/recordings/'),
        'PATH_USER_PROFILE_IMAGE': path.realpath(app_path + '/../public/profile_images/'),
        'PATH_ASSETS': path.realpath(app_path + '/../public/assets/'),
        'PATH_PUBLIC': path.realpath(app_path + '/../public/'),
    })

    # sanity checks
    if not path.isdir(app.config['RECORDINGS_PATH']):
        raise Exception("Recordings path does not exist: " + app.config['RECORDINGS_PATH'])

    if not path.isdir(app.config['PATH_USER_PROFILE_IMAGE']):
        raise Exception("User profile images path does not exist: " + app.config['PATH_USER_PROFILE_IMAGE'])

    # app.json_encoder = MongoJsonEncoder

    # setup database and session storage
    # db settings come from flask.ini
    # and same engine is used for storing sessions
    mongo = MongoEngine()
    mongo.init_app(app)
    app.session_interface = MongoEngineSessionInterface(mongo)

    # toolbar = DebugToolbarExtension(app)

    return app, mongo
예제 #17
0
    def setUp(self):
        app = flask.Flask(__name__)
        app.config['MONGODB_DB'] = 'testing'
        app.config['TESTING'] = True
        db = MongoEngine()

        class Todo(db.Document):
            title = db.StringField(max_length=60)
            text = db.StringField()
            done = db.BooleanField(default=False)
            pub_date = db.DateTimeField(default=datetime.datetime.now)

        db.init_app(app)

        Todo.drop_collection()
        self.Todo = Todo

        @app.route('/')
        def index():
            return '\n'.join(x.title for x in self.Todo.objects)

        @app.route('/add', methods=['POST'])
        def add():
            form = flask.request.form
            todo = self.Todo(title=form['title'],
                             text=form['text'])
            todo.save()
            return 'added'

        @app.route('/show/<id>/')
        def show(id):
            todo = self.Todo.objects.get_or_404(id=id)
            return '\n'.join([todo.title, todo.text])

        self.app = app
        self.db = db
예제 #18
0
    def __init__(self, app):
        
        app.mail = Mail(app)

        db = MongoEngine()

        #TODO: pull these files out
        class Role(db.Document, RoleMixin):
            name = db.StringField(required=True, unique=True, max_length=80)
            description = db.StringField(max_length=255)

        class User(db.Document, UserMixin):
            email = db.StringField(unique=True, max_length=255)
            password = db.StringField(required=True, max_length=120)
            active = db.BooleanField(default=True)
            confirmation_token = db.StringField(max_length=255)
            confirmation_sent_at = db.DateTimeField()
            confirmed_at = db.DateTimeField()
            reset_password_token = db.StringField(max_length=255)
            reset_password_sent_at = db.DateTimeField()
            roles = db.ListField(db.ReferenceField(Role), default=[])

        try:
            db.init_app(app)

            Security(app, MongoEngineUserDatastore(db))

            #TODO: make a fabric task?
            @app.before_first_request
            def before_first_request():
                User.drop_collection()
                Role.drop_collection()
                populate_data()

        except:
            print 'cannot connect to mongo'
예제 #19
0
파일: core_app.py 프로젝트: Scille/kalon
class CoreApp(Flask):
    """
    CoreApp is a regular :class:`Flask` app with cors, flask-principal,
    "restfulness" flavors
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Support objectid in url routing
        self.url_map.converters['objectid'] = ObjectIdConverter
        # Custom json encoder for objectid and pagination
        # Mix between flask's root_path (module's path) and running dir path
        self.root_path = abspath(dirname(__file__) + '/..')
        # Overload default request to return 400 if no payload is provided
        self.request_class = JsonRequest
        self.json_encoder = dynamic_json_encoder_factory()
        restful.representations.json.settings['cls'] = self.json_encoder
        self.db = MongoEngine()
        self.solr = Solr()

    def bootstrap(self):
        """
        Initialize modules needing configuration

        :example:

            >>> app = CoreApp("my-app")
            >>> app.config['MY_CONF'] = 'DEFAULT_VALUE'
            >>> app.bootstrap()
        """
        # Principal and CORS support must be initialized at bootstrap time
        # in order to have up-to-date config
        self._principal = Principal(self, use_sessions=False)
        self._cors = cors.CORS(self)
        self.db.init_app(self)
        self.solr.init_app(self)
    def test_connection_default(self):
        self.app.config['MONGODB_SETTINGS'] = {}
        self.app.config['TESTING'] = True

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

        self.app.config['TESTING'] = True
        db = MongoEngine()
        db.init_app(self.app)
    def test_connection_default(self):
        app = flask.Flask(__name__)
        app.config['MONGODB_SETTINGS'] = {}
        app.config['TESTING'] = True

        db = MongoEngine()
        db.init_app(app)

        app.config['TESTING'] = True
        db = MongoEngine()
        db.init_app(app)
    def test_connection_db_only(self):
        app = flask.Flask(__name__)
        app.config['MONGODB_SETTINGS'] = {
            'db': 'test'
        }
        app.config['TESTING'] = True
        db = MongoEngine()
        db.init_app(app)

        app.config['MONGODB_DB'] = 'test'
        app.config['TESTING'] = True
        db = MongoEngine()
        db.init_app(app)
예제 #23
0
    def test_connection_kwargs(self):
        self.app.config['MONGODB_SETTINGS'] = {
            'DB': 'testing_tz_aware',
            'ALIAS': 'tz_aware_true',
            'TZ_AWARE': True
        }
        self.app.config['TESTING'] = True
        db = MongoEngine()
        db.init_app(self.app)
        self.assertTrue(db.connection.tz_aware)

        # PyMongo defaults to tz_aware = True so we have to explicitly turn
        # it off.
        self.app.config['MONGODB_SETTINGS'] = {
            'DB': 'testing',
            'ALIAS': 'tz_aware_false',
            'TZ_AWARE': False
        }
        db = MongoEngine()
        db.init_app(self.app)
        self.assertFalse(db.connection.tz_aware)
    def test_connection_missing_db(self):
        app = flask.Flask(__name__)
        app.config['MONGODB_SETTINGS'] = {
            'alias': 'tz_aware_true',
            'TZ_AWARE': True
        }
        app.config['TESTING'] = True
        db = MongoEngine()
        try:
            db.init_app(app)
            self.assertFalse("ValueError should've been raised")
        except ValueError:
            pass

        app.config['MONGODB_HOST'] = 'mongodb://localhost'
        app.config['TESTING'] = True
        db = MongoEngine()
        try:
            db.init_app(app)
            self.assertFalse("ValueError should've been raised")
        except ValueError:
            pass
예제 #25
0
class WTFormsAppTestCase(FlaskMongoEngineTestCase):

    def setUp(self):
        super(WTFormsAppTestCase, self).setUp()
        self.db_name = 'testing'
        self.app.config['MONGODB_DB'] = self.db_name
        self.app.config['TESTING'] = True
        # For Flask-WTF < 0.9
        self.app.config['CSRF_ENABLED'] = False
        # For Flask-WTF >= 0.9
        self.app.config['WTF_CSRF_ENABLED'] = False
        self.db = MongoEngine()
        self.db.init_app(self.app)

    def tearDown(self):
        self.db.connection.drop_database(self.db_name)

    def test_binaryfield(self):

        with self.app.test_request_context('/'):
            db = self.db

            class Binary(db.Document):
                binary = db.BinaryField()

            BinaryForm = model_form(Binary)
            form = BinaryForm(MultiDict({'binary': '1'}))
            self.assertTrue(form.validate())
            form.save()

    def test_choices_coerce(self):

        with self.app.test_request_context('/'):
            db = self.db

            CHOICES = ((1, "blue"), (2, "red"))

            class MyChoices(db.Document):
                pill = db.IntField(choices=CHOICES)

            MyChoicesForm = model_form(MyChoices)
            form = MyChoicesForm(MultiDict({"pill": "1"}))
            self.assertTrue(form.validate())
            form.save()
            self.assertEqual(MyChoices.objects.first().pill, 1)

    def test_list_choices_coerce(self):

        with self.app.test_request_context('/'):
            db = self.db

            CHOICES = ((1, "blue"), (2, "red"))

            class MyChoices(db.Document):
                pill = db.ListField(db.IntField(choices=CHOICES))

            MyChoicesForm = model_form(MyChoices)
            form = MyChoicesForm(MultiDict({"pill": "1"}))
            self.assertTrue(form.validate())
            form.save()
            self.assertEqual(MyChoices.objects.first().pill[0], 1)

    def test_emailfield(self):

        with self.app.test_request_context('/'):
            db = self.db

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

            EmailForm = model_form(Email)
            form = EmailForm(instance=Email())
            self.assertFalse("None" in "%s" % form.email)
            self.assertTrue(form.validate())

            form = EmailForm(MultiDict({"email": ""}))
            self.assertFalse("None" in "%s" % form.email)
            self.assertTrue(form.validate())

            # Ensure required works

            class Email(db.Document):
                email = db.EmailField(required=True)

            EmailForm = model_form(Email)
            form = EmailForm(MultiDict({"email": ""}))
            self.assertFalse("None" in "%s" % form.email)
            self.assertFalse(form.validate())

    def test_model_form(self):
        with self.app.test_request_context('/'):
            db = self.db

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

            class TextPost(BlogPost):
                email = db.EmailField(required=False)
                lead_paragraph = db.StringField(max_length=200)
                content = db.StringField(required=True)

            class LinkPost(BlogPost):
                url = db.StringField(required=True, max_length=200)
                interest = db.DecimalField(required=True)

            # Create a text-based post
            TextPostForm = model_form(
                TextPost,
                field_args={'lead_paragraph': {'textarea': True}})

            form = TextPostForm(MultiDict({
                'title': 'Using MongoEngine',
                'tags': ['mongodb', 'mongoengine']}))

            self.assertFalse(form.validate())

            form = TextPostForm(MultiDict({
                'title': 'Using MongoEngine',
                'content': 'See the tutorial',
                'tags': ['mongodb', 'mongoengine']}))

            self.assertTrue(form.validate())
            form.save()

            self.assertEqual(form.title.type, 'StringField')
            self.assertEqual(form.content.type, 'TextAreaField')
            self.assertEqual(form.lead_paragraph.type, 'TextAreaField')

            self.assertEquals(BlogPost.objects.first().title, 'Using MongoEngine')
            self.assertEquals(BlogPost.objects.count(), 1)

            form = TextPostForm(MultiDict({
                'title': 'Using Flask-MongoEngine',
                'content': 'See the tutorial',
                'tags': ['flask', 'mongodb', 'mongoengine']}))

            self.assertTrue(form.validate())
            form.save()
            self.assertEquals(BlogPost.objects.count(), 2)

            post = BlogPost.objects(title="Using Flask-MongoEngine").get()

            form = TextPostForm(MultiDict({
                'title': 'Using Flask-MongoEngine',
                'content': 'See the tutorial',
                'tags-0': 'flask',
                'tags-1': 'mongodb',
                'tags-2': 'mongoengine',
                'tags-3': 'flask-mongoengine',
            }), instance=post)
            self.assertTrue(form.validate())
            form.save()
            post = post.reload()

            self.assertEqual(post.tags, ['flask', 'mongodb', 'mongoengine', 'flask-mongoengine'])

            # Create a link post
            LinkPostForm = model_form(LinkPost)

            form = LinkPostForm(MultiDict({
                'title': 'Using Flask-MongoEngine',
                'url': 'http://flask-mongoengine.org',
                'interest': '0',
            }))
            form.validate()
            self.assertTrue(form.validate())

    def test_model_form_only(self):
        with self.app.test_request_context('/'):
            db = self.db

            class BlogPost(db.Document):
                title = db.StringField(required=True, max_length=200)
                posted = db.DateTimeField(default=datetime.datetime.now)
                tags = db.ListField(db.StringField())

            BlogPost.drop_collection()

            BlogPostForm = model_form(BlogPost, only=['tags'])
            form = BlogPostForm()
            self.assertTrue(hasattr(form, 'tags'))
            self.assertFalse(hasattr(form, 'posted'))

            BlogPostForm = model_form(BlogPost, exclude=['posted'])
            form = BlogPostForm()
            self.assertTrue(hasattr(form, 'tags'))
            self.assertFalse(hasattr(form, 'posted'))

    def test_model_form_with_custom_query_set(self):
        with self.app.test_request_context('/'):
            db = self.db

            class Dog(db.Document):
                breed = db.StringField()

                @queryset_manager
                def large_objects(cls, queryset):
                    return queryset(breed__in=['german sheppard', 'wolfhound'])

            class DogOwner(db.Document):
                dog = db.ReferenceField(Dog)

            big_dogs = [Dog(breed="german sheppard"), Dog(breed="wolfhound")]
            dogs = [Dog(breed="poodle")] + big_dogs
            for dog in dogs:
                dog.save()

            BigDogForm = model_form(DogOwner, field_args={'dog': {'queryset': Dog.large_objects}})

            form = BigDogForm(dog=big_dogs[0])
            self.assertTrue(form.validate())
            self.assertEqual(big_dogs, [d[1] for d in form.dog.iter_choices()])

    def test_modelselectfield(self):
        with self.app.test_request_context('/'):
            db = self.db

            class Dog(db.Document):
                name = db.StringField()

            class DogOwner(db.Document):
                dog = db.ReferenceField(Dog)

            DogOwnerForm = model_form(DogOwner)

            dog = Dog(name="fido")
            dog.save()

            form = DogOwnerForm(dog=dog)
            self.assertTrue(form.validate())

            self.assertEqual(wtforms.widgets.Select, type(form.dog.widget))
            self.assertFalse(form.dog.widget.multiple)

            # Validate selecting one item
            form = DogOwnerForm(MultiDict({
                'dog': dog.id,
                }))
            self.assertEqual(form.dog.data, dog)

            # Validate selecting no item
            form = DogOwnerForm(MultiDict({
                'dog': u'__None',
                }), dog=dog)
            self.assertEqual(form.dog.data, None)

    def test_modelselectfield_multiple(self):
        with self.app.test_request_context('/'):
            db = self.db

            class Dog(db.Document):
                name = db.StringField()

            class DogOwner(db.Document):
                dogs = db.ListField(db.ReferenceField(Dog))

            DogOwnerForm = model_form(DogOwner)

            dogs = [Dog(name="fido"), Dog(name="rex")]
            for dog in dogs:
                dog.save()

            form = DogOwnerForm(dogs=dogs)
            self.assertTrue(form.validate())

            self.assertEqual(wtforms.widgets.Select, type(form.dogs.widget))
            self.assertTrue(form.dogs.widget.multiple)

            # Validate if both dogs are selected
            choices = list(form.dogs)
            self.assertEqual(len(choices), 2)
            self.assertTrue(choices[0].checked)
            self.assertTrue(choices[1].checked)

            # Validate selecting two items
            form = DogOwnerForm(MultiDict({
                'dogs': [dog.id for dog in dogs],
                }))
            self.assertEqual(form.dogs.data, dogs)

            # Validate selecting none actually empties the list
            form = DogOwnerForm(MultiDict({
                'dogs': [],
                }), dogs=dogs)
            self.assertEqual(form.dogs.data, None)

    def test_modelselectfield_multiple_initalvalue_None(self):
        with self.app.test_request_context('/'):
            db = self.db

            class Dog(db.Document):
                name = db.StringField()

            class DogOwner(db.Document):
                dogs = db.ListField(db.ReferenceField(Dog))

            DogOwnerForm = model_form(DogOwner)

            dogs = [Dog(name="fido"), Dog(name="rex")]
            for dog in dogs:
                dog.save()

            form = DogOwnerForm(dogs=None)
            self.assertTrue(form.validate())

            self.assertEqual(wtforms.widgets.Select, type(form.dogs.widget))
            self.assertTrue(form.dogs.widget.multiple)

            # Validate if both dogs are selected
            choices = list(form.dogs)
            self.assertEqual(len(choices), 2)
            self.assertFalse(choices[0].checked)
            self.assertFalse(choices[1].checked)
            
    def test_modelradiofield(self):
        with self.app.test_request_context('/'):
            db = self.db
        
            choices = (('male', 'Male'), ('female', 'Female'), ('other', 'Other'))
        
            class Poll(db.Document):
                answer = db.StringField(choices=choices)
    
            PollForm = model_form(Poll, field_args={'answer': {'radio': True}})
        
            form = PollForm(answer=None)
            self.assertTrue(form.validate())
        
            self.assertEqual(form.answer.type, 'RadioField')
            self.assertEqual(form.answer.choices, choices)

    def test_passwordfield(self):
        with self.app.test_request_context('/'):
            db = self.db

            class User(db.Document):
                password = db.StringField()

            UserForm = model_form(User, field_args={'password': {'password': True}})
            form = UserForm(password='******')
            self.assertEqual(wtforms.widgets.PasswordInput, type(form.password.widget))

    def test_unique_with(self):

        with self.app.test_request_context('/'):
            db = self.db

            class Item (db.Document):
                owner_id = db.ObjectIdField(required=True)
                owner_item_id = db.StringField(required=True, unique_with='owner_id')

            Item.drop_collection()

            object_id = ObjectId()
            Item(object_id, owner_item_id="1").save()

            try:
                Item(object_id, owner_item_id="1").save()
                self.fail("Should have raised duplicate key error")
            except:
                pass

            self.assertEqual(1, Item.objects.count())

    def test_sub_field_args(self):
        with self.app.test_request_context('/'):
            db = self.db

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

            field_args = {'lst': {'label': 'Custom Label',
                                  'field_args': {'widget': wtforms.widgets.HiddenInput(),
                                                 'label': "Hidden Input"}}}
            CustomForm = model_form(TestModel, field_args=field_args)

            custom_form = CustomForm(obj=TestModel(lst=["Foo"]))
            list_label = flask.render_template_string("{{ custom_form.lst.label }}", custom_form=custom_form)
            self.assertTrue("Custom Label" in list_label)
            self.assertTrue("Hidden Input" not in list_label)

            sub_label = flask.render_template_string("{{ custom_form.lst }}", custom_form=custom_form)
            self.assertTrue("Hidden Input" in sub_label)

    def test_modelselectfield_multiple_selected_elements_must_be_retained(self):
        with self.app.test_request_context('/'):
            db = self.db

            class Dog(db.Document):
                name = db.StringField()

                def __unicode__(self):
                    return self.name

            class DogOwner(db.Document):
                dogs = db.ListField(db.ReferenceField(Dog))

            DogOwnerForm = model_form(DogOwner)

            fido = Dog(name="fido").save()
            Dog(name="rex").save()

            dogOwner = DogOwner(dogs=[fido])
            form = DogOwnerForm(obj=dogOwner)
            html = form.dogs()

            m = re.search("<option selected .+?>(.*?)</option>", html)
            self.assertTrue(m is not None, "Should have one selected option")
            self.assertEqual("fido", m.group(1))

    def test_model_form_help_text(self):
        with self.app.test_request_context('/'):
            db = self.db

            class BlogPost(db.Document):
                title = db.StringField(required=True, help_text="Some imaginative title to set the world on fire")

            post = BlogPost(title="hello world").save()

            BlogPostForm = model_form(BlogPost)
            form = BlogPostForm(instance=post)

            self.assertEqual(form.title.description, "Some imaginative title to set the world on fire")

    def test_shared_field_args(self):
        with self.app.test_request_context('/'):
            db = self.db

            class BlogPost(db.Document):
                title = db.StringField(required=True)
                content = db.StringField(required=False)

            shared_field_args = {'title': {'validators': [
                wtforms.validators.Regexp('test')
            ]}}

            TitleOnlyForm = model_form(BlogPost, field_args=shared_field_args,
                                       exclude=['content'])
            BlogPostForm = model_form(BlogPost, field_args=shared_field_args)

            # ensure shared field_args don't create duplicate validators
            title_only_form = TitleOnlyForm()
            self.assertEqual(len(title_only_form.title.validators), 2)

            blog_post_form = BlogPostForm()
            self.assertEqual(len(blog_post_form.title.validators), 2)

    def test_embedded_model_form(self):
        with self.app.test_request_context('/'):
            db = self.db

            class Content(db.EmbeddedDocument):
                text = db.StringField()
                lang = db.StringField(max_length=3)

            class Post(db.Document):
                title = db.StringField(max_length=120, required=True)
                tags = db.ListField(db.StringField(max_length=30))
                content = db.EmbeddedDocumentField("Content")

            PostForm = model_form(Post)
            form = PostForm()
            self.assertTrue("content-text" in "%s" % form.content.text)
예제 #26
0
#Application Factory Method
from flask import Flask
from flask.ext.mongoengine import MongoEngine

db = MongoEngine()  # Create instance of Mongo Engine


def create_app(**config_overrides):  #** allows unit tester to override
    app = Flask(__name__)

    app.config.from_pyfile(
        'settings.py')  #get application settings from file settings.py
    #Need to override this for unit testing
    app.config.update(config_overrides)

    db.init_app(app)

    from user.views import user_app
    from relationship.views import relationship_app
    from home.views import home_app
    from feed.views import feed_app

    #register blueprints
    app.register_blueprint(user_app)
    app.register_blueprint(relationship_app)
    app.register_blueprint(home_app)
    app.register_blueprint(feed_app)
    return app
예제 #27
0
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 22 17:11:33 2014

@author: Yunus
"""

from flask import Flask
from flask.ext.mongoengine import MongoEngine

app = Flask(__name__)
app.config["MONGODB_SETTINGS"] = {'DB': "my_tumble_log"}
app.config["SECRET_KEY"] = "KeepThisS3cr3t"

db = MongoEngine(app)

if __name__ == '__main__':
    app.run()
예제 #28
0
def create_app(testing=False, live=False):
    from bhs_api.models import User, Role
    from bhs_api.forms import LoginForm

    app = Flask(__name__)
    app.testing = testing

    # Get configuration from file
    must_have_keys = set([
        'secret_key',
        'mail_server',
        'mail_port',
        'user_db_host',
        'user_db_port',
        'elasticsearch_host',
        'user_db_name',
        'data_db_host',
        'data_db_port',
        'data_db_name',
        'image_bucket_url',
        'video_bucket_url',
        'redis_host',
        'redis_port',
        'caching_ttl',
    ])

    # load the conf file. use local copy if nothing in the system
    if os.path.exists(CONF_FILE):
        conf = get_conf(CONF_FILE, must_have_keys)
    else:
        path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                            os.pardir, 'conf', 'bhs_config.yaml')
        conf = get_conf(path, must_have_keys)

    # Our config - need to move everything here
    app.config[
        'VIDEO_BUCKET_URL'] = "https://storage.googleapis.com/bhs-movies"
    app.config[
        'IMAGE_BUCKET_URL'] = "https://storage.googleapis.com/bhs-flat-pics"

    # Set app config
    app.config['DEBUG'] = True
    app.config['FRONTEND_SERVER'] = conf.frontend_server
    app.config['DEFAULT_NEXT'] = '/mjs'
    # Security Config
    app.config['SECRET_KEY'] = conf.secret_key
    app.config['WTF_CSRF_ENABLED'] = False
    app.config['SECURITY_PASSWORDLESS'] = True
    app.config['SECURITY_EMAIL_SENDER'] = 'BH Databases<*****@*****.**>'
    app.config['SECURITY_USER_IDENTITY_ATTRIBUTES'] = 'email'
    app.config[
        'SECURITY_EMAIL_SUBJECT_PASSWORDLESS'] = 'Login link for Your Jewish Story'
    app.config['SECURITY_POST_LOGIN_VIEW'] = '/mjs'
    app.config['SECURITY_USER_IDENTITY_ATTRIBUTES'] = ('email', 'username',
                                                       'hash')
    # Mail Config
    app.config['MAIL_SERVER'] = conf.mail_server
    app.config['MAIL_PORT'] = conf.mail_port
    # Mail optional username and password
    try:
        app.config['MAIL_USERNAME'] = conf.mail_username
        app.config['MAIL_PASSWORD'] = conf.mail_password
    except AttributeError:
        pass

    # DB Config
    app.config['MONGODB_DB'] = conf.user_db_name
    app.config['MONGODB_HOST'] = conf.user_db_host
    app.config['MONGODB_PORT'] = conf.user_db_port
    # CACHING
    app.config['CACHING_TTL'] = conf.caching_ttl

    app.mail = Mail(app)
    app.db = MongoEngine(app)
    app.user_datastore = MongoEngineUserDatastore(app.db, User, Role)
    app.security = Security(app,
                            app.user_datastore,
                            passwordless_login_form=LoginForm)
    # Create database connection object
    app.client_data_db = pymongo.MongoClient(
        conf.data_db_host,
        conf.data_db_port,
        read_preference=pymongo.ReadPreference.SECONDARY_PREFERRED)
    app.data_db = app.client_data_db[conf.data_db_name]

    # Create the elasticsearch connection
    app.es = elasticsearch.Elasticsearch(conf.elasticsearch_host)
    # Add the user's endpoints
    from bhs_api.user import user_endpoints
    app.register_blueprint(user_endpoints)
    # Add the v1 endpoint
    from bhs_api.v1_endpoints import v1_endpoints
    app.register_blueprint(v1_endpoints, url_prefix='/v1')
    # Initialize autodoc - https://github.com/acoomans/flask-autodoc
    #allow CORS
    cors = CORS(app,
                origins=['*'],
                headers=[
                    'content-type', 'accept', 'authentication-token',
                    'Authorization'
                ])
    # logging
    if live:
        app.config['PROPAGATE_EXCEPTIONS'] = True
        try:
            fh = logging.FileHandler(conf.log_file)
            formatter = logging.Formatter(
                '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
            fh.setFormatter(formatter)
            app.logger.addHandler(fh)
        except AttributeError:
            pass

    # redis
    try:
        app.redis = redis.StrictRedis(host=conf.redis_host,
                                      port=conf.redis_port,
                                      db=0)
    except AttributeError:
        app.redis = None

    app.logger.debug("Hellow world")

    return app, conf
예제 #29
0
from flask.app import Flask
from flask.ext.mongoengine import MongoEngine

from flask.ext.restframework.model_resource import ModelResource
from flask.ext.restframework.router import DefaultRouter
from flask_restframework import fields, BaseSerializer, ModelSerializer

app = Flask(__name__)

db = MongoEngine(app, config={"MONGODB_DB": "todo"})

from mongoengine import fields as dbfields


class ToDo(dbfields.EmbeddedDocument):
    title = dbfields.StringField(required=True)
    body = dbfields.StringField(required=True)
    is_done = dbfields.BooleanField(default=False)


class ToDoList(dbfields.Document):
    title = dbfields.StringField(required=True)

    # Use embedded field for todos. You can also use ReferenceField
    todos = dbfields.EmbeddedDocumentListField(ToDo)


class ToDoListSerializer(ModelSerializer):
    class Meta:
        model = ToDoList
예제 #30
0
def connect_db(app):
    MongoEngine(app)
예제 #31
0
from flask import Flask
from flask.ext.mongoengine import MongoEngine
from flask.ext.bcrypt import Bcrypt

# Index page
index = Flask(__name__)

# Add mongoDB stuff
index.config['MONGODB_SETTINGS'] = {'DB': 'index'}
index.config['SECRET_KEY'] = 'root'

index_db = MongoEngine(index)

# Encryption
index_bcrypt = Bcrypt(index)


# Use the blueprints
def register_blueprints(index):
    # Put the blueprint import here to prevent circular imports
    from index.views import index_bp

    index.register_blueprint(index_bp)


# Call the newly defined function to actually use the blueprints
register_blueprints(index)

if __name__ == '__main__':
    index.run()
예제 #32
0
class PaginationTestCase(FlaskMongoEngineTestCase):
    def setUp(self):
        super(PaginationTestCase, self).setUp()
        self.db_name = 'testing'
        self.app.config['MONGODB_DB'] = self.db_name
        self.app.config['TESTING'] = True
        self.app.config['CSRF_ENABLED'] = False
        self.db = MongoEngine()
        self.db.init_app(self.app)

    def tearDown(self):
        self.db.connection.drop_database(self.db_name)

    def test_queryset_paginator(self):
        with self.app.test_request_context('/'):
            db = self.db

            class Post(db.Document):
                title = db.StringField(required=True, max_length=200)

            for i in range(42):
                Post(title="post: %s" % i).save()

        self.assertRaises(NotFound, Pagination, Post.objects, 0, 10)
        self.assertRaises(NotFound, Pagination, Post.objects, 6, 10)

        paginator = Pagination(Post.objects, 1, 10)
        self._test_paginator(paginator)

    def test_paginate_plain_list(self):

        self.assertRaises(NotFound, Pagination, range(1, 42), 0, 10)
        self.assertRaises(NotFound, Pagination, range(1, 42), 6, 10)

        paginator = Pagination(range(1, 42), 1, 10)
        self._test_paginator(paginator)

    def test_list_field_pagination(self):

        with self.app.test_request_context('/'):
            db = self.db

            class Post(db.Document):
                title = db.StringField(required=True, max_length=200)
                comments = db.ListField(db.StringField())
                comment_count = db.IntField()

            comments = ["comment: %s" % i for i in range(42)]
            post = Post(title="post has comments",
                        comments=comments,
                        comment_count=len(comments)).save()

            # Check without providing a total
            paginator = ListFieldPagination(Post.objects, post.id, "comments",
                                            1, 10)
            self._test_paginator(paginator)

            # Check with providing a total (saves a query)
            paginator = ListFieldPagination(Post.objects, post.id, "comments",
                                            1, 10, post.comment_count)
            self._test_paginator(paginator)

            paginator = post.paginate_field('comments', 1, 10)
            self._test_paginator(paginator)

    def _test_paginator(self, paginator):
        self.assertEqual(5, paginator.pages)
        self.assertEqual([1, 2, 3, 4, 5], list(paginator.iter_pages()))

        for i in [1, 2, 3, 4, 5]:

            if i == 1:
                self.assertRaises(NotFound, paginator.prev)
                self.assertFalse(paginator.has_prev)
            else:
                self.assertTrue(paginator.has_prev)

            if i == 5:
                self.assertRaises(NotFound, paginator.next)
                self.assertFalse(paginator.has_next)
            else:
                self.assertTrue(paginator.has_next)

            self.assertEqual(i, paginator.page)
            self.assertEqual(i - 1, paginator.prev_num)
            self.assertEqual(i + 1, paginator.next_num)

            # Paginate to the next page
            if i < 5:
                paginator = paginator.next()
예제 #33
0
from flask.ext.mongoengine import MongoEngine
from flask.ext.cache import Cache

# Define the WSGI application object
app = Flask(__name__)

# Configurations
app.config.from_object('config')

# Initialize cache
#cache = Cache()
#cache.init_app(app, config={ 'CACHE_TYPE': 'simple' })

# Define the database object which is imported
# by modules and controllers
db = MongoEngine()
db.connect(host=app.config['MONGODB_DATABASE_HOST'])
db.init_app(app)

# Define email
mail = Mail(app)


# Sample HTTP error handling
@app.errorhandler(404)
def not_found(error):
    return render_template('404.html'), 404


# Import a module / component using its blueprint handler variable (mod_auth)
from app.auth.web.views import auth_web as auth_web_module
예제 #34
0
__author__ = 'mendrugory'
from flask.ext.mongoengine import MongoEngine
from app import application
from secret_settings import MONGODB_HOST, MONGODB_NAME, MONGODB_USER, MONGODB_PWD, MONGODB_PORT

application.config['MONGODB_SETTINGS'] = {
    'db': MONGODB_NAME,
    'host': MONGODB_HOST,
    'port': MONGODB_PORT,
    'username': MONGODB_USER,
    'password': MONGODB_PWD
}

db = MongoEngine(application)
예제 #35
0
from flask.ext.mongoengine import MongoEngine

client = MongoEngine()


def create_mongo(app):
    """
    Mongo connection factory
    """
    global client

    # get db client
    client.init_app(app)
예제 #36
0
##############
## DATABASE ##
##############

parser = ConfigParser()
parser.read('mongo.cfg')
DB_NAME = parser.get('mongo', 'DB_NAME')
DB_USERNAME = parser.get('mongo', 'DB_USERNAME')
DB_PASSWORD = parser.get('mongo', 'DB_PASSWORD')
DB_HOST_ADDRESS = parser.get('mongo', 'DB_HOST_ADDRESS')

APP.config["MONGODB_DB"] = DB_NAME
mongoengine.connect(DB_NAME, host='mongodb://' + DB_USERNAME + ':'
        + DB_PASSWORD + '@' + DB_HOST_ADDRESS)

DB = MongoEngine(APP)

## Schema ##

class Menu(DB.DynamicDocument):
    name = DB.StringField(max_length=16)
    menu = DB.DictField()


######################
## Helper functions ##
######################

#@APP.before_request
def updateMenusIfNecessary():
    "Calls `updateMenus()` every 24 hours, and once on app boot-up."
예제 #37
0
파일: __init__.py 프로젝트: ljb-2000/neobug
from flask import Flask
from flask.ext import admin, login
from flask.ext.admin import helpers
from flask.ext.admin.contrib.mongoengine import ModelView
from flask.ext.mongoengine import MongoEngine, MongoEngineSessionInterface

neobug = Flask(__name__)
neobug.config['UPLOAD_FOLDER'] = 'neobug/static/uploads'

if 'neobug.test.config' in sys.modules:
    neobug.config.from_object(sys.modules['neobug.test.config'])
else:
    neobug.config['MONGODB_SETTINGS'] = {'DB': 'neobug'}
    neobug.config['SECRET_KEY'] = 'KupiKotaZaStoBaksov'

db = MongoEngine(neobug)
neobug.session_interface = MongoEngineSessionInterface(db)
from neobug.models import *
from neobug.admin_views import *
from neobug import views

from blueprints.wiki.views import wiki
from blueprints.projects.views import projects
from blueprints.downloads.views import downloads
from blueprints.downloads.models import Download
neobug.register_blueprint(wiki, url_prefix='/wiki')
neobug.register_blueprint(projects, url_prefix='/projects')
neobug.register_blueprint(downloads, url_prefix='/downloads')


def init_login():
예제 #38
0
class WTFormsAppTestCase(FlaskMongoEngineTestCase):
    def setUp(self):
        super(WTFormsAppTestCase, self).setUp()
        self.db_name = "testing"
        self.app.config["MONGODB_DB"] = self.db_name
        self.app.config["TESTING"] = True
        # For Flask-WTF < 0.9
        self.app.config["CSRF_ENABLED"] = False
        # For Flask-WTF >= 0.9
        self.app.config["WTF_CSRF_ENABLED"] = False
        self.db = MongoEngine()
        self.db.init_app(self.app)

    def tearDown(self):
        self.db.connection.drop_database(self.db_name)

    def test_binaryfield(self):

        with self.app.test_request_context("/"):
            db = self.db

            class Binary(db.Document):
                binary = db.BinaryField()

            BinaryForm = model_form(Binary)
            form = BinaryForm(MultiDict({"binary": "1"}))
            self.assertTrue(form.validate())
            form.save()

    def test_choices_coerce(self):

        with self.app.test_request_context("/"):
            db = self.db

            CHOICES = ((1, "blue"), (2, "red"))

            class MyChoices(db.Document):
                pill = db.IntField(choices=CHOICES)

            MyChoicesForm = model_form(MyChoices)
            form = MyChoicesForm(MultiDict({"pill": "1"}))
            self.assertTrue(form.validate())
            form.save()
            self.assertEqual(MyChoices.objects.first().pill, 1)

    def test_list_choices_coerce(self):

        with self.app.test_request_context("/"):
            db = self.db

            CHOICES = ((1, "blue"), (2, "red"))

            class MyChoices(db.Document):
                pill = db.ListField(db.IntField(choices=CHOICES))

            MyChoicesForm = model_form(MyChoices)
            form = MyChoicesForm(MultiDict({"pill": "1"}))
            self.assertTrue(form.validate())
            form.save()
            self.assertEqual(MyChoices.objects.first().pill[0], 1)

    def test_emailfield(self):

        with self.app.test_request_context("/"):
            db = self.db

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

            EmailForm = model_form(Email)
            form = EmailForm(instance=Email())
            self.assertFalse("None" in "%s" % form.email)
            self.assertTrue(form.validate())

            form = EmailForm(MultiDict({"email": ""}))
            self.assertFalse("None" in "%s" % form.email)
            self.assertTrue(form.validate())

            # Ensure required works

            class Email(db.Document):
                email = db.EmailField(required=True)

            EmailForm = model_form(Email)
            form = EmailForm(MultiDict({"email": ""}))
            self.assertFalse("None" in "%s" % form.email)
            self.assertFalse(form.validate())

    def test_model_form(self):
        with self.app.test_request_context("/"):
            db = self.db

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

            class TextPost(BlogPost):
                email = db.EmailField(required=False)
                content = db.StringField(required=True)

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

            # Create a text-based post
            TextPostForm = model_form(TextPost)

            form = TextPostForm(**{"title": "Using MongoEngine", "tags": ["mongodb", "mongoengine"]})

            self.assertFalse(form.validate())

            form = TextPostForm(
                **{"title": "Using MongoEngine", "content": "See the tutorial", "tags": ["mongodb", "mongoengine"]}
            )

            self.assertTrue(form.validate())
            form.save()

            self.assertEquals(BlogPost.objects.first().title, "Using MongoEngine")
            self.assertEquals(BlogPost.objects.count(), 1)

            form = TextPostForm(
                **{
                    "title": "Using Flask-MongoEngine",
                    "content": "See the tutorial",
                    "tags": ["flask", "mongodb", "mongoengine"],
                }
            )

            self.assertTrue(form.validate())
            form.save()
            self.assertEquals(BlogPost.objects.count(), 2)

            post = BlogPost.objects(title="Using Flask-MongoEngine").get()

            form = TextPostForm(
                MultiDict(
                    {
                        "title": "Using Flask-MongoEngine",
                        "content": "See the tutorial",
                        "tags-0": "flask",
                        "tags-1": "mongodb",
                        "tags-2": "mongoengine",
                        "tags-3": "flask-mongoengine",
                    }
                ),
                instance=post,
            )
            self.assertTrue(form.validate())
            form.save()
            post = post.reload()

            self.assertEqual(post.tags, ["flask", "mongodb", "mongoengine", "flask-mongoengine"])

    def test_model_form_only(self):
        with self.app.test_request_context("/"):
            db = self.db

            class BlogPost(db.Document):
                title = db.StringField(required=True, max_length=200)
                posted = db.DateTimeField(default=datetime.datetime.now)
                tags = db.ListField(db.StringField())

            BlogPost.drop_collection()

            BlogPostForm = model_form(BlogPost, only=["tags"])
            form = BlogPostForm()
            self.assertTrue(hasattr(form, "tags"))
            self.assertFalse(hasattr(form, "posted"))

            BlogPostForm = model_form(BlogPost, exclude=["posted"])
            form = BlogPostForm()
            self.assertTrue(hasattr(form, "tags"))
            self.assertFalse(hasattr(form, "posted"))

    def test_model_form_with_custom_query_set(self):
        with self.app.test_request_context("/"):
            db = self.db

            class Dog(db.Document):
                breed = db.StringField()

                @queryset_manager
                def large_objects(cls, queryset):
                    return queryset(breed__in=["german sheppard", "wolfhound"])

            class DogOwner(db.Document):
                dog = db.ReferenceField(Dog)

            big_dogs = [Dog(breed="german sheppard"), Dog(breed="wolfhound")]
            dogs = [Dog(breed="poodle")] + big_dogs
            for dog in dogs:
                dog.save()

            BigDogForm = model_form(DogOwner, field_args={"dog": {"queryset": Dog.large_objects}})

            form = BigDogForm(dog=big_dogs[0])
            self.assertTrue(form.validate())
            self.assertEqual(big_dogs, [d[1] for d in form.dog.iter_choices()])

    def test_modelselectfield(self):
        with self.app.test_request_context("/"):
            db = self.db

            class Dog(db.Document):
                name = db.StringField()

            class DogOwner(db.Document):
                dog = db.ReferenceField(Dog)

            DogOwnerForm = model_form(DogOwner)

            dog = Dog(name="fido")
            dog.save()

            form = DogOwnerForm(dog=dog)
            self.assertTrue(form.validate())

            self.assertEqual(wtforms.widgets.Select, type(form.dog.widget))
            self.assertEqual(False, form.dog.widget.multiple)

    def test_modelselectfield_multiple(self):
        with self.app.test_request_context("/"):
            db = self.db

            class Dog(db.Document):
                name = db.StringField()

            class DogOwner(db.Document):
                dogs = db.ListField(db.ReferenceField(Dog))

            DogOwnerForm = model_form(DogOwner)

            dogs = [Dog(name="fido"), Dog(name="rex")]
            for dog in dogs:
                dog.save()

            form = DogOwnerForm(dogs=dogs)
            self.assertTrue(form.validate())

            self.assertEqual(wtforms.widgets.Select, type(form.dogs.widget))
            self.assertEqual(True, form.dogs.widget.multiple)

            # Validate if both dogs are selected
            choices = list(form.dogs)
            self.assertEqual(len(choices), 2)
            self.assertTrue(choices[0].checked)
            self.assertTrue(choices[1].checked)

    def test_modelselectfield_multiple_initalvalue_None(self):
        with self.app.test_request_context("/"):
            db = self.db

            class Dog(db.Document):
                name = db.StringField()

            class DogOwner(db.Document):
                dogs = db.ListField(db.ReferenceField(Dog))

            DogOwnerForm = model_form(DogOwner)

            dogs = [Dog(name="fido"), Dog(name="rex")]
            for dog in dogs:
                dog.save()

            form = DogOwnerForm(dogs=None)
            self.assertTrue(form.validate())

            self.assertEqual(wtforms.widgets.Select, type(form.dogs.widget))
            self.assertEqual(True, form.dogs.widget.multiple)

            # Validate if both dogs are selected
            choices = list(form.dogs)
            self.assertEqual(len(choices), 2)
            self.assertFalse(choices[0].checked)
            self.assertFalse(choices[1].checked)

    def test_passwordfield(self):
        with self.app.test_request_context("/"):
            db = self.db

            class User(db.Document):
                password = db.StringField()

            UserForm = model_form(User, field_args={"password": {"password": True}})
            form = UserForm(password="******")
            self.assertEqual(wtforms.widgets.PasswordInput, type(form.password.widget))

    def test_unique_with(self):

        with self.app.test_request_context("/"):
            db = self.db

            class Item(db.Document):
                owner_id = db.ObjectIdField(required=True)
                owner_item_id = db.StringField(required=True, unique_with="owner_id")

            Item.drop_collection()

            object_id = ObjectId()
            Item(object_id, owner_item_id="1").save()

            try:
                Item(object_id, owner_item_id="1").save()
                self.fail("Should have raised duplicate key error")
            except:
                pass

            self.assertEqual(1, Item.objects.count())

    def test_sub_field_args(self):
        with self.app.test_request_context("/"):
            db = self.db

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

            field_args = {
                "lst": {
                    "label": "Custom Label",
                    "field_args": {"widget": wtforms.widgets.HiddenInput(), "label": "Hidden Input"},
                }
            }
            CustomForm = model_form(TestModel, field_args=field_args)

            custom_form = CustomForm(obj=TestModel(lst=["Foo"]))
            list_label = flask.render_template_string("{{ custom_form.lst.label }}", custom_form=custom_form)
            self.assertTrue("Custom Label" in list_label)
            self.assertTrue("Hidden Input" not in list_label)

            sub_label = flask.render_template_string("{{ custom_form.lst }}", custom_form=custom_form)
            self.assertTrue("Hidden Input" in sub_label)

    def test_modelselectfield_multiple_selected_elements_must_be_retained(self):
        with self.app.test_request_context("/"):
            db = self.db

            class Dog(db.Document):
                name = db.StringField()

                def __unicode__(self):
                    return self.name

            class DogOwner(db.Document):
                dogs = db.ListField(db.ReferenceField(Dog))

            DogOwnerForm = model_form(DogOwner)

            fido = Dog(name="fido").save()
            Dog(name="rex").save()

            dogOwner = DogOwner(dogs=[fido])
            form = DogOwnerForm(obj=dogOwner)
            html = form.dogs()

            m = re.search("<option selected .+?>(.*?)</option>", html)
            self.assertTrue(m is not None, "Should have one selected option")
            self.assertEqual("fido", m.group(1))

    def test_model_form_help_text(self):
        with self.app.test_request_context("/"):
            db = self.db

            class BlogPost(db.Document):
                title = db.StringField(required=True, help_text="Some imaginative title to set the world on fire")

            post = BlogPost(title="hello world").save()

            BlogPostForm = model_form(BlogPost)
            form = BlogPostForm(instance=post)

            self.assertEqual(form.title.description, "Some imaginative title to set the world on fire")

    def test_embedded_model_form(self):
        with self.app.test_request_context("/"):
            db = self.db

            class Content(db.EmbeddedDocument):
                text = db.StringField()
                lang = db.StringField(max_length=3)

            class Post(db.Document):
                title = db.StringField(max_length=120, required=True)
                tags = db.ListField(db.StringField(max_length=30))
                content = db.EmbeddedDocumentField("Content")

            PostForm = model_form(Post)
            form = PostForm()
            self.assertTrue("content-text" in "%s" % form.content.text)
예제 #39
0
class WTFormsAppTestCase(unittest.TestCase):
    def setUp(self):
        self.db_name = 'testing'

        app = flask.Flask(__name__)
        app.config['MONGODB_DB'] = self.db_name
        app.config['TESTING'] = True
        app.config['CSRF_ENABLED'] = False
        self.app = app
        self.db = MongoEngine()
        self.db.init_app(app)

    def tearDown(self):
        self.db.connection.drop_database(self.db_name)

    def test_model_form(self):
        with self.app.test_request_context('/'):
            db = self.db

            class BlogPost(db.Document):
                title = db.StringField(required=True, max_length=200)
                posted = db.DateTimeField(default=datetime.datetime.now)
                tags = db.ListField(db.StringField(max_length=50))

            class TextPost(BlogPost):
                email = db.EmailField(required=False)
                content = db.StringField(required=True)

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

            # Create a text-based post
            TextPostForm = model_form(TextPost)

            form = TextPostForm(**{
                'title': 'Using MongoEngine',
                'tags': ['mongodb', 'mongoengine']
            })

            self.assertFalse(form.validate())

            form = TextPostForm(
                **{
                    'title': 'Using MongoEngine',
                    'content': 'See the tutorial',
                    'tags': ['mongodb', 'mongoengine']
                })

            self.assertTrue(form.validate())
            form.save()

            self.assertEquals(BlogPost.objects.first().title,
                              'Using MongoEngine')
            self.assertEquals(BlogPost.objects.count(), 1)

            form = TextPostForm(
                MultiDict({
                    'title': 'Using MongoEngine',
                    'content': 'See the tutorial',
                    'tags': ['mongodb', 'mongoengine']
                }))

            self.assertTrue(form.validate())
            form.save()
            self.assertEquals(BlogPost.objects.count(), 2)

    def test_model_form_with_custom_query_set(self):
        with self.app.test_request_context('/'):
            db = self.db

            class Dog(db.Document):
                breed = db.StringField()

                @queryset_manager
                def large_objects(cls, queryset):
                    return queryset(breed__in=['german sheppard', 'wolfhound'])

            class DogOwner(db.Document):
                dog = db.ReferenceField(Dog)

            big_dogs = [Dog(breed="german sheppard"), Dog(breed="wolfhound")]
            dogs = [Dog(breed="poodle")] + big_dogs
            for dog in dogs:
                dog.save()

            BigDogForm = model_form(
                DogOwner, field_args={'dog': {
                    'queryset': Dog.large_objects
                }})

            form = BigDogForm(dog=big_dogs[0])
            self.assertTrue(form.validate())
            self.assertEqual(big_dogs, [d[1] for d in form.dog.iter_choices()])

    def test_modelselectfield(self):
        with self.app.test_request_context('/'):
            db = self.db

            class Dog(db.Document):
                name = db.StringField()

            class DogOwner(db.Document):
                dog = db.ReferenceField(Dog)

            DogOwnerForm = model_form(DogOwner)

            dog = Dog(name="fido")
            dog.save()

            form = DogOwnerForm(dog=dog)
            self.assertTrue(form.validate())

            self.assertEqual(wtforms.widgets.Select, type(form.dog.widget))
            self.assertEqual(False, form.dog.widget.multiple)

    def test_modelselectfield_multiple(self):
        with self.app.test_request_context('/'):
            db = self.db

            class Dog(db.Document):
                name = db.StringField()

            class DogOwner(db.Document):
                dogs = db.ListField(db.ReferenceField(Dog))

            DogOwnerForm = model_form(DogOwner)

            dogs = [Dog(name="fido"), Dog(name="rex")]
            for dog in dogs:
                dog.save()

            form = DogOwnerForm(dogs=dogs)
            self.assertTrue(form.validate())

            self.assertEqual(wtforms.widgets.Select, type(form.dogs.widget))
            self.assertEqual(True, form.dogs.widget.multiple)

            # Validate if both dogs are selected
            choices = list(form.dogs)
            self.assertEqual(len(choices), 2)
            self.assertTrue(choices[0].checked)
            self.assertTrue(choices[1].checked)

    def test_passwordfield(self):
        with self.app.test_request_context('/'):
            db = self.db

            class User(db.Document):
                password = db.StringField()

            UserForm = model_form(User,
                                  field_args={'password': {
                                      'password': True
                                  }})
            form = UserForm(password='******')
            self.assertEqual(wtforms.widgets.PasswordInput,
                             type(form.password.widget))
예제 #40
0
 def db(self):
     db = MongoEngine(self.app)
     return db
예제 #41
0
# Create dummy secrey key so we can use sessions
app.config['SECRET_KEY'] = '123456790'
app.config['MONGODB_SETTINGS'] = {
    'db':
    'ai-aggregator',
    'host':
    os.environ.get('MONGODB_URL', 'mongodb://localhost:27017/ai-aggregator'),
}
app.config.update(CELERY_BROKER_URL=os.environ.get('REDIS_URL',
                                                   'redis://localhost:6379/0'),
                  CELERY_RESULT_BACKEND=os.environ.get(
                      'REDIS_URL', 'redis://localhost:6379/0'))

# Create models
db = MongoEngine()
db.init_app(app)
login_manager.init_app(app)
app.json_encoder = JSONEncoder


# Create user loader function
@login_manager.user_loader
def load_user(user_id):
    try:
        User.objects.get(id=user_id)
    except User.DoesNotExist:
        return AnonymousUserMixin()


# Create user model.
예제 #42
0
class WTFormsAppTestCase(unittest.TestCase):

    def setUp(self):
        self.db_name = 'testing'

        app = flask.Flask(__name__)
        app.config['MONGODB_DB'] = self.db_name
        app.config['TESTING'] = True
        app.config['CSRF_ENABLED'] = False
        self.app = app
        self.db = MongoEngine()
        self.db.init_app(app)

    def tearDown(self):
        self.db.connection.drop_database(self.db_name)

    def test_model_form(self):
        with self.app.test_request_context('/'):
            db = self.db

            class BlogPost(db.Document):
                title = db.StringField(required=True, max_length=200)
                posted = db.DateTimeField(default=datetime.datetime.now)
                tags = db.ListField(db.StringField(max_length=50))

            class TextPost(BlogPost):
                email = db.EmailField(required=False)
                content = db.StringField(required=True)

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


            # Create a text-based post
            TextPostForm = model_form(TextPost)

            form = TextPostForm(**{
                'title': 'Using MongoEngine',
                'tags': ['mongodb', 'mongoengine']})

            self.assertFalse(form.validate())

            form = TextPostForm(**{
                'title': 'Using MongoEngine',
                'content': 'See the tutorial',
                'tags': ['mongodb', 'mongoengine']})

            self.assertTrue(form.validate())
            form.save()

            self.assertEquals(BlogPost.objects.first().title, 'Using MongoEngine')
            self.assertEquals(BlogPost.objects.count(), 1)

            form = TextPostForm(MultiDict({
                'title': 'Using MongoEngine',
                'content': 'See the tutorial',
                'tags': ['mongodb', 'mongoengine']}))

            self.assertTrue(form.validate())
            form.save()
            self.assertEquals(BlogPost.objects.count(), 2)


    def test_model_form_with_custom_query_set(self):
        with self.app.test_request_context('/'):
            db = self.db

            class Dog(db.Document):
                breed = db.StringField()

                @queryset_manager
                def large_objects(cls, queryset):
                    return queryset(breed__in = ['german sheppard', 'wolfhound'])

            class DogOwner(db.Document):
                dog = db.ReferenceField(Dog)

            big_dogs = [Dog(breed="german sheppard"), Dog(breed="wolfhound")]
            dogs = [Dog(breed="poodle")] + big_dogs
            for dog in dogs:
                dog.save()

            BigDogForm = model_form(DogOwner, field_args={'dog': {'queryset' : Dog.large_objects} })

            form = BigDogForm(dog=big_dogs[0])
            self.assertTrue(form.validate())
            self.assertEqual( big_dogs, [d[1] for d in form.dog.iter_choices()] )


    def test_modelselectfield(self):
        with self.app.test_request_context('/'):
            db = self.db

            class Dog(db.Document):
                name = db.StringField()

            class DogOwner(db.Document):
                dog = db.ReferenceField(Dog)

            DogOwnerForm = model_form(DogOwner)

            dog = Dog(name="fido")
            dog.save()

            form = DogOwnerForm(dog=dog)
            self.assertTrue(form.validate())

            self.assertEqual(wtforms.widgets.Select, type(form.dog.widget))
            self.assertEqual(False, form.dog.widget.multiple)


    def test_modelselectfield_multiple(self):
        with self.app.test_request_context('/'):
            db = self.db

            class Dog(db.Document):
                name = db.StringField()

            class DogOwner(db.Document):
                dogs = db.ListField(db.ReferenceField(Dog))

            DogOwnerForm = model_form(DogOwner)

            dogs = [Dog(name="fido"), Dog(name="rex")]
            for dog in dogs:
                dog.save()

            form = DogOwnerForm(dogs=dogs)
            self.assertTrue(form.validate())

            self.assertEqual(wtforms.widgets.Select, type(form.dogs.widget))
            self.assertEqual(True, form.dogs.widget.multiple)

    def test_passwordfield(self):
        with self.app.test_request_context('/'):
            db = self.db

            class User(db.Document):
                password = db.StringField()

            UserForm = model_form(User, field_args = { 'password': {'password' : True} })
            form = UserForm(password='******')
            self.assertEqual(wtforms.widgets.PasswordInput, type(form.password.widget))
예제 #43
0
def init_database():
    app.config["MONGODB_SETTINGS"] = {"DB": "imagematcher"}
    return MongoEngine(app)
예제 #44
0
def not_found(error):
    return render_template('404.html'), 404
    #return "Oops!! It's 404. Page doesn't exist."


@app.route("/", methods=['GET', 'POST'])
def redirect_home():
    return redirect(url_for('home.home_page'))


# # database connection
# app.config['MONGODB_SETTINGS'] = {'HOST':os.environ.get('MONGOLAB_URI'),'DB': 'FlaskLogin'}
# app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')
# app.debug = os.environ.get('DEBUG',False)

db = MongoEngine(app)  # connect MongoEngine with Flask App
app.session_interface = MongoEngineSessionInterface(
    db)  # sessions w/ mongoengine

# Flask BCrypt will be used to salt the user password
flask_bcrypt = Bcrypt(app)

# Associate Flask-Login manager with current app
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'login'
login_manager.init_app(app)

# Import a module / component using its blueprint handler variable (mod_auth)
from app.mod_home.controllers import mod_home as auth_home
예제 #45
0
# -*- coding: utf-8 -*-
#!/usr/bin/env python

from flask import Flask
from flask.ext.mongoengine import MongoEngine
from flaskext.markdown import Markdown

app = Flask(__name__)  #创建Flask类的实例
app.config.from_object("config")  #从config.py读入配置
md = Markdown(app,
              extensions=['footnotes'],
              entension_configs={'footnotes': ('PLACE_MARKER', '```')},
              safe_mode=True,
              output_format='html4')
db = MongoEngine(app)  #实例化数据库

#这个import语句放在这里, 防止views, models import发生循环import
from app import views, models
예제 #46
0
from flask import Flask
from giga_web.ext.ses_mailer import SES_Mailer
from flask.ext.mongoengine import MongoEngine
from make_celery import make_celery
from settings import ProductionConfig, TestConfig
from celery.utils.log import get_task_logger


giga_web = Flask('giga_web')
giga_web.config.from_object(ProductionConfig)
celery_logger = get_task_logger('giga_web')
celery = make_celery(giga_web)
mailer = SES_Mailer(giga_web)
db = MongoEngine(giga_web)
db.init_app(giga_web)
#running celery requires this command:
#celery worker -A giga_web.celery --autoscale=4,2 -Q test_queue

import helpers
from giga_web import views, tasks, ext, models
예제 #47
0
import os
from flask import Flask,request
from flask import Flask,render_template
import requests
import json
import datetime
import collections
from flask import jsonify
from models.models import *
from flask.ext.mongoengine import MongoEngine
from flask.ext.mongoengine.wtf import model_form

app = Flask(__name__)
app.config.from_object('config')
mongoDb = MongoEngine(app)
mongoDb.connect()


def convert(data):
    if isinstance(data, basestring):
        return str(data)
    elif isinstance(data, collections.Mapping):
        return dict(map(convert, data.iteritems()))
    elif isinstance(data, collections.Iterable):
        return type(data)(map(convert, data))
    else:
        return data

@app.route('/')
@app.route('/index')
def index():
예제 #48
0
#!/usr/bin/env python
#-*- coding: utf-8 -*-
from flask import Flask
from flask.ext.mongoengine import MongoEngine
# from flask.ext.bootstrap import Bootstrap
# from flask.ext.mail import Mail
# from flask.ext.sqlalchemy import SQLAlchemy
from config import config
from flask.ext.login import LoginManager
from datetime import datetime
import memcache
from apscheduler.schedulers.background import BackgroundScheduler

conf = config['default']
scheduler = BackgroundScheduler()
db = MongoEngine()
mc = memcache.Client([conf.QCLOUD_MEMCACHED_IP], debug=0)
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'


def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    # app.config.from_pyfile('the-config.cfg')

    config[config_name].init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
예제 #49
0
try:
    # only works in debug mode
    from flask_debugtoolbar import DebugToolbarExtension

    toolbar = DebugToolbarExtension()
except ImportError:
    print('debugtoolbar extension not available.')


{%- if cookiecutter.use_sql == 'yes' %}
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()

{% endif %}


{%- if cookiecutter.use_nosql == 'yes' %}
from flask.ext.mongoengine import MongoEngine
nosql = MongoEngine()

{% endif %}

{%- if cookiecutter.use_socketio == 'yes' %}
from flask_socketio import SocketIO
socketio = SocketIO()

{% endif %}
예제 #50
0
class WTFormsAppTestCase(FlaskMongoEngineTestCase):

    def setUp(self):
        super(WTFormsAppTestCase, self).setUp()
        self.db_name = 'testing'
        self.app.config['MONGODB_DB'] = self.db_name
        self.app.config['TESTING'] = True
        # For Flask-WTF < 0.9
        self.app.config['CSRF_ENABLED'] = False
        # For Flask-WTF >= 0.9
        self.app.config['WTF_CSRF_ENABLED'] = False
        self.db = MongoEngine()
        self.db.init_app(self.app)

    def tearDown(self):
        self.db.connection.drop_database(self.db_name)

    def test_binaryfield(self):

        with self.app.test_request_context('/'):
            db = self.db

            class Binary(db.Document):
                binary = db.BinaryField()

            BinaryForm = model_form(Binary)
            form = BinaryForm(MultiDict({'binary': '1'}))
            self.assertTrue(form.validate())
            form.save()

    def test_choices_coerce(self):

        with self.app.test_request_context('/'):
            db = self.db

            CHOICES = ((1, "blue"), (2, "red"))

            class MyChoices(db.Document):
                pill = db.IntField(choices=CHOICES)

            MyChoicesForm = model_form(MyChoices)
            form = MyChoicesForm(MultiDict({"pill": "1"}))
            self.assertTrue(form.validate())
            form.save()
            self.assertEqual(MyChoices.objects.first().pill, 1)

    def test_list_choices_coerce(self):

        with self.app.test_request_context('/'):
            db = self.db

            CHOICES = ((1, "blue"), (2, "red"))

            class MyChoices(db.Document):
                pill = db.ListField(db.IntField(choices=CHOICES))

            MyChoicesForm = model_form(MyChoices)
            form = MyChoicesForm(MultiDict({"pill": "1"}))
            self.assertTrue(form.validate())
            form.save()
            self.assertEqual(MyChoices.objects.first().pill[0], 1)

    def test_emailfield(self):

        with self.app.test_request_context('/'):
            db = self.db

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

            EmailForm = model_form(Email)
            form = EmailForm(instance=Email())
            self.assertFalse("None" in "%s" % form.email)
            self.assertTrue(form.validate())

            form = EmailForm(MultiDict({"email": ""}))
            self.assertFalse("None" in "%s" % form.email)
            self.assertTrue(form.validate())

            # Ensure required works

            class Email(db.Document):
                email = db.EmailField(required=True)

            EmailForm = model_form(Email)
            form = EmailForm(MultiDict({"email": ""}))
            self.assertFalse("None" in "%s" % form.email)
            self.assertFalse(form.validate())

    def test_model_form(self):
        with self.app.test_request_context('/'):
            db = self.db

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

            class TextPost(BlogPost):
                email = db.EmailField(required=False)
                content = db.StringField(required=True)

            class LinkPost(BlogPost):
                url = db.StringField(required=True)
                interest =  db.DecimalField(required=True)

            # Create a text-based post
            TextPostForm = model_form(TextPost)

            form = TextPostForm(MultiDict({
                'title': 'Using MongoEngine',
                'tags': ['mongodb', 'mongoengine']}))

            self.assertFalse(form.validate())

            form = TextPostForm(MultiDict({
                'title': 'Using MongoEngine',
                'content': 'See the tutorial',
                'tags': ['mongodb', 'mongoengine']}))

            self.assertTrue(form.validate())
            form.save()

            self.assertEquals(BlogPost.objects.first().title, 'Using MongoEngine')
            self.assertEquals(BlogPost.objects.count(), 1)

            form = TextPostForm(MultiDict({
                'title': 'Using Flask-MongoEngine',
                'content': 'See the tutorial',
                'tags': ['flask', 'mongodb', 'mongoengine']}))

            self.assertTrue(form.validate())
            form.save()
            self.assertEquals(BlogPost.objects.count(), 2)

            post = BlogPost.objects(title="Using Flask-MongoEngine").get()

            form = TextPostForm(MultiDict({
                'title': 'Using Flask-MongoEngine',
                'content': 'See the tutorial',
                'tags-0': 'flask',
                'tags-1': 'mongodb',
                'tags-2': 'mongoengine',
                'tags-3': 'flask-mongoengine',
            }), instance=post)
            self.assertTrue(form.validate())
            form.save()
            post = post.reload()

            self.assertEqual(post.tags, ['flask', 'mongodb', 'mongoengine', 'flask-mongoengine'])

            # Create a link post
            LinkPostForm = model_form(LinkPost)

            form = LinkPostForm(MultiDict({
                'title': 'Using Flask-MongoEngine',
                'url': 'http://flask-mongoengine.org',
                'interest': '0',
            }))
            form.validate()
            self.assertTrue(form.validate())

    def test_model_form_only(self):
        with self.app.test_request_context('/'):
            db = self.db

            class BlogPost(db.Document):
                title = db.StringField(required=True, max_length=200)
                posted = db.DateTimeField(default=datetime.datetime.now)
                tags = db.ListField(db.StringField())

            BlogPost.drop_collection()

            BlogPostForm = model_form(BlogPost, only=['tags'])
            form = BlogPostForm()
            self.assertTrue(hasattr(form, 'tags'))
            self.assertFalse(hasattr(form, 'posted'))

            BlogPostForm = model_form(BlogPost, exclude=['posted'])
            form = BlogPostForm()
            self.assertTrue(hasattr(form, 'tags'))
            self.assertFalse(hasattr(form, 'posted'))

    def test_model_form_with_custom_query_set(self):
        with self.app.test_request_context('/'):
            db = self.db

            class Dog(db.Document):
                breed = db.StringField()

                @queryset_manager
                def large_objects(cls, queryset):
                    return queryset(breed__in=['german sheppard', 'wolfhound'])

            class DogOwner(db.Document):
                dog = db.ReferenceField(Dog)

            big_dogs = [Dog(breed="german sheppard"), Dog(breed="wolfhound")]
            dogs = [Dog(breed="poodle")] + big_dogs
            for dog in dogs:
                dog.save()

            BigDogForm = model_form(DogOwner, field_args={'dog': {'queryset': Dog.large_objects}})

            form = BigDogForm(dog=big_dogs[0])
            self.assertTrue(form.validate())
            self.assertEqual(big_dogs, [d[1] for d in form.dog.iter_choices()])

    def test_modelselectfield(self):
        with self.app.test_request_context('/'):
            db = self.db

            class Dog(db.Document):
                name = db.StringField()

            class DogOwner(db.Document):
                dog = db.ReferenceField(Dog)

            DogOwnerForm = model_form(DogOwner)

            dog = Dog(name="fido")
            dog.save()

            form = DogOwnerForm(dog=dog)
            self.assertTrue(form.validate())

            self.assertEqual(wtforms.widgets.Select, type(form.dog.widget))
            self.assertEqual(False, form.dog.widget.multiple)

    def test_modelselectfield_multiple(self):
        with self.app.test_request_context('/'):
            db = self.db

            class Dog(db.Document):
                name = db.StringField()

            class DogOwner(db.Document):
                dogs = db.ListField(db.ReferenceField(Dog))

            DogOwnerForm = model_form(DogOwner)

            dogs = [Dog(name="fido"), Dog(name="rex")]
            for dog in dogs:
                dog.save()

            form = DogOwnerForm(dogs=dogs)
            self.assertTrue(form.validate())

            self.assertEqual(wtforms.widgets.Select, type(form.dogs.widget))
            self.assertEqual(True, form.dogs.widget.multiple)

            # Validate if both dogs are selected
            choices = list(form.dogs)
            self.assertEqual(len(choices), 2)
            self.assertTrue(choices[0].checked)
            self.assertTrue(choices[1].checked)

    def test_modelselectfield_multiple_initalvalue_None(self):
        with self.app.test_request_context('/'):
            db = self.db

            class Dog(db.Document):
                name = db.StringField()

            class DogOwner(db.Document):
                dogs = db.ListField(db.ReferenceField(Dog))

            DogOwnerForm = model_form(DogOwner)

            dogs = [Dog(name="fido"), Dog(name="rex")]
            for dog in dogs:
                dog.save()

            form = DogOwnerForm(dogs=None)
            self.assertTrue(form.validate())

            self.assertEqual(wtforms.widgets.Select, type(form.dogs.widget))
            self.assertEqual(True, form.dogs.widget.multiple)

            # Validate if both dogs are selected
            choices = list(form.dogs)
            self.assertEqual(len(choices), 2)
            self.assertFalse(choices[0].checked)
            self.assertFalse(choices[1].checked)
            
    def test_modelradiofield(self):
        with self.app.test_request_context('/'):
            db = self.db
        
            choices = (('male', 'Male'), ('female', 'Female'), ('other', 'Other'))
        
            class Poll(db.Document):
                answer = db.StringField(choices=choices)
    
            PollForm = model_form(Poll, field_args={'answer': {'radio': True}})
        
            form = PollForm(answer=None)
            self.assertTrue(form.validate())
        
            self.assertEqual(form.answer.type, 'RadioField')
            self.assertEqual(form.answer.choices, choices)

    def test_passwordfield(self):
        with self.app.test_request_context('/'):
            db = self.db

            class User(db.Document):
                password = db.StringField()

            UserForm = model_form(User, field_args={'password': {'password': True}})
            form = UserForm(password='******')
            self.assertEqual(wtforms.widgets.PasswordInput, type(form.password.widget))

    def test_unique_with(self):

        with self.app.test_request_context('/'):
            db = self.db

            class Item (db.Document):
                owner_id = db.ObjectIdField(required=True)
                owner_item_id = db.StringField(required=True, unique_with='owner_id')

            Item.drop_collection()

            object_id = ObjectId()
            Item(object_id, owner_item_id="1").save()

            try:
                Item(object_id, owner_item_id="1").save()
                self.fail("Should have raised duplicate key error")
            except:
                pass

            self.assertEqual(1, Item.objects.count())

    def test_sub_field_args(self):
        with self.app.test_request_context('/'):
            db = self.db

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

            field_args = {'lst': {'label': 'Custom Label',
                                  'field_args': {'widget': wtforms.widgets.HiddenInput(),
                                                 'label': "Hidden Input"}}}
            CustomForm = model_form(TestModel, field_args=field_args)

            custom_form = CustomForm(obj=TestModel(lst=["Foo"]))
            list_label = flask.render_template_string("{{ custom_form.lst.label }}", custom_form=custom_form)
            self.assertTrue("Custom Label" in list_label)
            self.assertTrue("Hidden Input" not in list_label)

            sub_label = flask.render_template_string("{{ custom_form.lst }}", custom_form=custom_form)
            self.assertTrue("Hidden Input" in sub_label)

    def test_modelselectfield_multiple_selected_elements_must_be_retained(self):
        with self.app.test_request_context('/'):
            db = self.db

            class Dog(db.Document):
                name = db.StringField()

                def __unicode__(self):
                    return self.name

            class DogOwner(db.Document):
                dogs = db.ListField(db.ReferenceField(Dog))

            DogOwnerForm = model_form(DogOwner)

            fido = Dog(name="fido").save()
            Dog(name="rex").save()

            dogOwner = DogOwner(dogs=[fido])
            form = DogOwnerForm(obj=dogOwner)
            html = form.dogs()

            m = re.search("<option selected .+?>(.*?)</option>", html)
            self.assertTrue(m is not None, "Should have one selected option")
            self.assertEqual("fido", m.group(1))

    def test_model_form_help_text(self):
        with self.app.test_request_context('/'):
            db = self.db

            class BlogPost(db.Document):
                title = db.StringField(required=True, help_text="Some imaginative title to set the world on fire")

            post = BlogPost(title="hello world").save()

            BlogPostForm = model_form(BlogPost)
            form = BlogPostForm(instance=post)

            self.assertEqual(form.title.description, "Some imaginative title to set the world on fire")

    def test_shared_field_args(self):
        with self.app.test_request_context('/'):
            db = self.db

            class BlogPost(db.Document):
                title = db.StringField(required=True)
                content = db.StringField(required=False)

            shared_field_args = {'title': {'validators': [
                wtforms.validators.Regexp('test')
            ]}}

            TitleOnlyForm = model_form(BlogPost, field_args=shared_field_args,
                                       exclude=['content'])
            BlogPostForm = model_form(BlogPost, field_args=shared_field_args)

            # ensure shared field_args don't create duplicate validators
            title_only_form = TitleOnlyForm()
            self.assertEqual(len(title_only_form.title.validators), 2)

            blog_post_form = BlogPostForm()
            self.assertEqual(len(blog_post_form.title.validators), 2)

    def test_embedded_model_form(self):
        with self.app.test_request_context('/'):
            db = self.db

            class Content(db.EmbeddedDocument):
                text = db.StringField()
                lang = db.StringField(max_length=3)

            class Post(db.Document):
                title = db.StringField(max_length=120, required=True)
                tags = db.ListField(db.StringField(max_length=30))
                content = db.EmbeddedDocumentField("Content")

            PostForm = model_form(Post)
            form = PostForm()
            self.assertTrue("content-text" in "%s" % form.content.text)
예제 #51
0
#! /usr/bin/env python3
# -*- encoding: utf-8 -*-
"""
__init__.py
flask app
"""
__author__ = 'Yoshiya Ito <*****@*****.**>'
__version__ = '0.0.1'
__date__ = '30 03 2016'

from flask import Flask
from flask.ext.mongoengine import MongoEngine
from flask.ext.restful import Api
from redis import Redis

sample = Flask(__name__)
redis = Redis()
mongo = MongoEngine(sample)
api = Api(sample)

import app.views
예제 #52
0
파일: do.py 프로젝트: LarryEitel/pyfem
import default_settings
from app import app
from flask.ext.mongoengine import MongoEngine

def _flush_db():
    from mongoengine.connection import _get_db
    me = _get_db()
    #Truncate/wipe the database
    names = [name for name in me.collection_names() \
        if 'system.' not in name]
    [me.drop_collection(name) for name in names]

app.config.from_object('default_settings')

me = MongoEngine()
me.init_app(app)

_flush_db()

g           = globals.load()
g['usr']    = {"OID": "50468de92558713d84b03fd7", "at": (-84.163063, 9.980516)}
g['me']     = app.me
g['logger'] = app.logger

debug = app.logger.debug
post    = ctrs.post.Post(g).post
put     = ctrs.put.Put(g).put

resp = post({'slug': 'lwe', 'lNam': 'Stooge', 'emails': [{'_types': ['Email'], 'prim': True, '_cls': 'Email', 'address': '*****@*****.**', 'typ': 'work', 'eId': 1}], 'fNam': 'Moe', '_cls': 'Prs'})
예제 #53
0
# client = pymongo.MongoClient(host='192.168.1.33', port=27017)
# if 'MONGODB_SETTINGS' in config:
#     # Connection settings provided as a dictionary.
#     connection = _create_connection(config['MONGODB_SETTINGS'])
# else:
#     # Connection settings provided in standard format.
#     settings = {'alias': config.get('MONGODB_ALIAS', None),
#                 'db': config.get('MONGODB_DB', None),
#                 'host': config.get('MONGODB_HOST', None),
#                 'password': config.get('MONGODB_PASSWORD', None),
#                 'port': config.get('MONGODB_PORT', None),
#                 'username': config.get('MONGODB_USERNAME', None)}

# db = MongoEngine(app)
db = MongoEngine(app, app.config)


def register_blueprints(app):
    # prevents circular imports
    from tumblelog.views import posts
    from tumblelog.admin import admin

    app.register_blueprint(posts)
    app.register_blueprint(admin)


register_blueprints(app)

if __name__ == '__main__':
    app.run()
예제 #54
0
#coding: utf-8

from flask import jsonify
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.mongoengine import MongoEngine
from flask.ext.cache import Cache

import conf

# database and cache

db = SQLAlchemy()
mongo = MongoEngine()
cache = Cache()


class SessionMixin(object):
    def to_dict(self, *columns):
        dct = {}
        for col in columns:
            value = getattr(self, col)
            if isinstance(value, datetime.datetime):
                value = value.strftime('%Y-%m-%d %H:%M:%S')
                dct[col] = value
        return dct

    def save(self):
        db.session.add(self)
        db.session.commit()
        return self
예제 #55
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask.ext.mongoengine import MongoEngine
from .fields import ListField

db = MongoEngine()
db.ListField = ListField
예제 #56
0
파일: app.py 프로젝트: iluddy/flock
    celery.conf.update(app.config)
    TaskBase = celery.Task

    class ContextTask(TaskBase):
        abstract = True
        def __call__(self, *args, **kwargs):
            with app.app_context():
                return TaskBase.__call__(self, *args, **kwargs)

    celery.Task = ContextTask
    return celery

celery = make_celery(app)

# DB
db = MongoEngine()
db.init_app(app)
db_wrapper = Database(db, cfg)

if __name__ == '__main__':

    # TODO - not this
    __builtin__.flock_app = app

    # Logging
    setup_logger(cfg["logging"]["file"], cfg["logging"]["level"])

    # Init Rollbar
    @app.before_first_request
    def init_rollbar():
        rollbar.init(
예제 #57
0
from flask import Flask

from flask.ext.mongoengine import MongoEngine

app = Flask(__name__)

app.config.from_object('config') # 实例化配置

db = MongoEngine(app)  # 实例化mongoEngine

from ReStartLearn.FlaskAndTodo.app import views, models

예제 #58
0
파일: __init__.py 프로젝트: Moobusy/lusk
# -*- coding: utf-8 -*-
'''
	Docer
	~~~~~~
	A document viewing platform.

	:copyright: (c) 2015 by Docer.Org.
	:license: MIT, see LICENSE for more details.
'''

from flask import Flask
from flask.ext.mongoengine import MongoEngine
from app.frontend import frontend as frontend_blueprint
from app.backend import backend as backend_blueprint

app = Flask(__name__)
app.config.from_object('config.DevelopmentConfig')
# mongodb
mongo = MongoEngine(app)


def create_app():
    """Create a flask app with a config."""

    app.register_blueprint(frontend_blueprint)
    app.register_blueprint(backend_blueprint,
                           name='admin',
                           url_prefix='/admin')

    return app
예제 #59
0
    `mongoengine` and `mongoengine.fields` modules.

BaseDocument
    Base abstract model schema that provides some common columns and methods
    for subclasses.
"""
from copy import deepcopy

from bson import json_util
from mongoengine import errors as mongo_errors, fields

from coati.core import utils

from flask.ext.mongoengine import MongoEngine, QuerySet

db = MongoEngine()


class CustomEmailField(fields.EmailField):
    """
    Custom EmailField to use our custom email regex at validation.
    """
    def validate(self, value):
        if not utils.EMAIL_REGEX.match(value):
            self.error(utils.INVALID_EMAIL_MSG)
        super(CustomEmailField, self).validate(value)


class CustomQuerySet(QuerySet):
    """
    Custom QuerySet for additional features.