Exemplo n.º 1
0
    def setUp(self):
        super(JSONAppTestCase, self).setUp()
        self.app.config['MONGODB_DB'] = 'testing'
        self.app.config['TESTING'] = True
        self.app.config['TEMP_DB'] = 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
    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
Exemplo n.º 3
0
    def test_connection_kwargs(self):
        """Make sure additional connection kwargs work."""

        # Figure out whether to use "MAX_POOL_SIZE" or "MAXPOOLSIZE" based
        # on PyMongo version (former was changed to the latter as described
        # in https://jira.mongodb.org/browse/PYTHON-854)
        # TODO remove once PyMongo < 3.0 support is dropped
        if pymongo.version_tuple[0] >= 3:
            MAX_POOL_SIZE_KEY = 'MAXPOOLSIZE'
        else:
            MAX_POOL_SIZE_KEY = 'MAX_POOL_SIZE'

        self.app.config['MONGODB_SETTINGS'] = {
            'ALIAS': 'tz_aware_true',
            'DB': 'flask_mongoengine_testing_tz_aware',
            'TZ_AWARE': True,
            'READ_PREFERENCE': ReadPreference.SECONDARY,
            MAX_POOL_SIZE_KEY: 10,
        }
        db = MongoEngine()
        db.init_app(self.app)
        self.assertTrue(db.connection.codec_options.tz_aware)
        self.assertEqual(db.connection.max_pool_size, 10)
        self.assertEqual(
            db.connection.read_preference,
            ReadPreference.SECONDARY
        )
Exemplo n.º 4
0
 def setUp(self):
     super(JSONAppTestCase, self).setUp()
     self.app.config['MONGODB_DB'] = 'test_db'
     self.app.config['TESTING'] = True
     self.app.json_encoder = DummyEncoder
     db = MongoEngine()
     db.init_app(self.app)
     self.db = db
Exemplo n.º 5
0
Arquivo: db.py Projeto: zhy0216/ezlog3
def get_db(database=None):
    database = conf.MONGODB_DB
    mongo = MongoEngine()
    mongo.connect(
        database,
        host=conf.MONGODB_HOST,
        port=conf.MONGODB_PORT,
        username=conf.MONGODB_USER,
        password=conf.MONGODB_PASSWD
    )
    return mongo
Exemplo n.º 6
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
Exemplo n.º 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
Exemplo n.º 8
0
def create_app():

    db = MongoEngine()
    app = Flask(__name__)
    app.config.from_object(Config)
    # flask_security config
    user_datastore = MongoEngineUserDatastore(db, Users, Roles)
    security = Security(app, user_datastore)

    # do some init
    db.init_app(app)
    create_user_role(user_datastore, db)
    return app
Exemplo n.º 9
0
    def test_multiple_connections(self):
        """Make sure establishing multiple connections to a standalone
        MongoDB and switching between them works.
        """
        db = MongoEngine()
        self.app.config['MONGODB_SETTINGS'] = [
            {
                'ALIAS': 'default',
                'DB': 'flask_mongoengine_test_db_1',
                'HOST': 'localhost',
                'PORT': 27017
            },
            {
                'ALIAS': 'alternative',
                'DB': 'flask_mongoengine_test_db_2',
                'HOST': 'localhost',
                'PORT': 27017
            },
        ]

        class Todo(db.Document):
            title = db.StringField(max_length=60)
            text = db.StringField()
            done = db.BooleanField(default=False)
            meta = {'db_alias': 'alternative'}

        db.init_app(self.app)
        Todo.drop_collection()

        # Test saving a doc via the default connection
        with switch_db(Todo, 'default') as Todo:
            todo = Todo()
            todo.text = "Sample"
            todo.title = "Testing"
            todo.done = True
            s_todo = todo.save()

            f_to = Todo.objects().first()
            self.assertEqual(s_todo.title, f_to.title)

        # Make sure the doc doesn't exist in the alternative db
        with switch_db(Todo, 'alternative') as Todo:
            doc = Todo.objects().first()
            self.assertEqual(doc, None)

        # Make sure switching back to the default connection shows the doc
        with switch_db(Todo, 'default') as Todo:
            doc = Todo.objects().first()
            self.assertNotEqual(doc, None)
Exemplo n.º 10
0
    def setUp(self):
        db = MongoEngine()
        app = Flask("corrdb")
        # app.config.MONGODB_SETTINGS = { 'db': 'corrdb', 'host': '0.0.0.0', 'port': 27017 }
        print(app.config.db)
        app.config.from_object({'db': 'corrdb', 'host': '0.0.0.0', 'port': 27017 })
        app.logger_name = "corrdb.app"

        # Flask-MongoEngine instance
        db.init_app(app)

        # Custom Converters
        app.url_map.converters['objectid'] = ObjectIDConverter

        app.run(debug='--no-debug', host='0.0.0.0', port=5000, threaded=True)
 def setUp(self):
     super(PaginationTestCase, self).setUp()
     self.db_name = 'test_db'
     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)
Exemplo n.º 12
0
def create_app(app_name=None, blueprints=None):
    """Create the flask app."""
    if app_name is None:
        app_name = "cowrie_api"
    if blueprints is None:
        blueprints = DEFAULT_BLUEPRINTS

    app = Flask(app_name)

    configure_app(app)
    configure_logging(app)

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

    configure_blueprints(app, blueprints)

    return app
Exemplo n.º 13
0
 def setUp(self):
     super(WTFormsAppTestCase, self).setUp()
     self.db_name = 'test_db'
     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)
Exemplo n.º 14
0
    def test_live_connection(self):
        db = MongoEngine()
        self.app.config['TEMP_DB'] = True
        self.app.config['MONGODB_SETTINGS'] = {
            'host' : 'localhost',
            'port' : 27017
        }
        class Todo(db.Document):
            title = db.StringField(max_length=60)
            text = db.StringField()
            done = db.BooleanField(default=False)

        db.init_app(self.app)
        Todo.drop_collection()

        # Test persist
        todo = Todo()
        todo.text = "Sample"
        todo.title = "Testing"
        todo.done = True
        s_todo = todo.save()

        f_to = Todo.objects().first()
        self.assertEqual(s_todo.title, f_to.title)
Exemplo n.º 15
0
    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)
class PaginationTestCase(FlaskMongoEngineTestCase):

    def setUp(self):
        super(PaginationTestCase, self).setUp()
        self.db_name = 'test_db'
        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):
        try:
            self.db.connection.drop_database(self.db_name)
        except Exception:
            self.db.connection.client.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)

                if i == 3:
                    self.assertEqual([None, 2, 3, 4, None],
                                     list(paginator.iter_pages(0, 1, 1, 0)))

                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()
Exemplo n.º 17
0
from flask import Flask
from config import Config
from flask_mongoengine import MongoEngine, MongoEngineSessionInterface
from flask_swagger_ui import get_swaggerui_blueprint

app = Flask(__name__)

SWAGGER_URL = '/swagger'
SWAGGERUI_BLUEPRINT = get_swaggerui_blueprint(
    SWAGGER_URL,
    '/static/api_swagger.yaml',
    config={'app_name': "api-swagger"})
app.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_URL)

app.config.from_object(Config)

db = MongoEngine(app)
db.connect(**Config.MONGODB_SETTINGS)
app.session_interface = MongoEngineSessionInterface(db)
Exemplo n.º 18
0
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf import CSRFProtect

from flask_mongoengine import MongoEngine

from flask_pymongo import PyMongo

db = SQLAlchemy()
csrf = CSRFProtect()

mongodb_du = MongoEngine()

# 字典列表
api_config = {
    'size': {
        '0': '35.5',
        '1': '36',
        '2': '36.5',
        '3': '37',
        '4': '37.5',
        '5': '38',
        '6': '38.5',
        '7': '39',
        '8': '39.5',
        '9': '40',
        '10': '40.5',
        '11': '41',
        '12': '41.5',
        '13': '42',
        '14': '42.5',
        '15': '43',
Exemplo n.º 19
0
serializer = URLSafeSerializer(app.secret_key)

# MongoDB settings
app.config['MONGODB_SETTINGS'] = {
    'alias': 'registry',
    'db': 'registry',
    'host': '0.0.0.0',
    'port': 27017,
    'username': '******',
    'password': '******'
}

# Build db connection with straight mongoengine
# mongo = connect('registry', host='mongodb://*****:*****@0.0.0.0:27017/registry', alias='registry-db')

mongo = MongoEngine(app)
registry = mongo.get_db('registry')
members = registry.member

# Initialize flask-login
login_manager = LoginManager(app)


# Define login and registation forms (for flask-login)
class LoginForm(form.Form):
    name = fields.TextField(validators=[validators.DataRequired()])


class RegistrationForm(form.Form):
    name = fields.TextField(validators=[validators.DataRequired()])
Exemplo n.º 20
0
from datetime import datetime

from flask_mongoengine import MongoEngine
from mongoengine import DateTimeField, Document, StringField

image_db = MongoEngine()


class PicBed(Document):
    img_id = StringField(max_length=16, required=True)
    img_name = StringField(max_length=32, required=True)
    orig_img_name = StringField(required=True)
    created_time = DateTimeField(default=datetime.utcnow())
    meta = {
        "collection": "images",
        "indexes": ["img_id", "orig_img_name", ("img_id", "img_name")]
    }

    def __repr__(self):
        return "<%s(img_id=%s, img_name=%s)>" % (self.__class__.__name__,
                                                 self.img_id, self.img_name)
Exemplo n.º 21
0
def create_app(config=None):
    app = Flask(__name__)
    # read .envs and configuration class
    app = read_env(app, config)

    app.secret_key = app.config.get('SECRET_KEY')

    # define logging patterns
    import logging  # %(pathname)
    if app.config.get("TESTING"):
        log_format = ("[%(asctime)s] %(funcName)s:%(lineno)d "
                      "%(levelname)s - %(message)s")
        log_level = logging.DEBUG

    else:
        log_format = ("[%(asctime)s] {%(filename)s#%(funcName)s:%(lineno)d} "
                      "%(levelname)s - %(message)s")
        log_level = logging.INFO

    formatter = logging.Formatter(log_format)
    handler = logging.StreamHandler()
    handler.setLevel(log_level)
    handler.setFormatter(formatter)
    app.logger.addHandler(handler)
    app.logger.setLevel(log_level)
    # remove default Flask debug handler
    del app.logger.handlers[0]

    # setup apps
    from flask_debugtoolbar import DebugToolbarExtension
    from flask_mongoengine import MongoEngine
    from flask_bcrypt import Bcrypt
    from flask_rq2 import RQ
    from flask_restful import Api
    from flask_login import LoginManager

    DebugToolbarExtension(app)
    MongoEngine(app)
    Bcrypt(app)
    RQ(app)
    api = Api(app)
    login_manager = LoginManager(app)

    # register view blueprints
    from project.home.views import app_blueprint
    from project.admin.views import admin_blueprint
    from project.user.views import user_blueprint

    app.register_blueprint(app_blueprint)
    app.register_blueprint(admin_blueprint)
    app.register_blueprint(user_blueprint)

    # register api endpoints
    from .api import Resources, API_VERSION
    for resource, url in Resources:
        _endpoint = ".".join(API_VERSION.format(url).split("/")[1:-1])
        api.add_resource(resource, API_VERSION.format(url), endpoint=_endpoint)

    # import custom login manager functions
    from project.home.login_manager import load_user_from_request, load_user
    login_manager.login_view = "user.login"
    login_manager.user_loader(load_user)
    login_manager.request_loader(load_user_from_request)

    # jinja extensions
    app.jinja_env.add_extension('jinja2.ext.do')

    # default flashed messages category
    login_manager.login_message_category = 'info'
    login_manager.needs_refresh_message_category = 'info'

    return app
Exemplo n.º 22
0
from flask import Flask
from flask_login import LoginManager
from flask_jwt_extended import JWTManager
from flask_mongoengine import MongoEngine
from flask_cors import CORS
from flask_mail import Mail
from app.config import *

app = Flask(__name__)

if app.env == "development":
    app.config.from_object(DevelopmentConfig)
else:
    app.config.from_object(ProductionConfig)

cors = CORS(app, resources={r"/api/*": {"origins": "*"}})

db = MongoEngine(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
jwt_manager = JWTManager(app)
mail = Mail(app)


from app import models
from app.API import bot, devices, mqtt, authAPI
Exemplo n.º 23
0
"""
Exports a function to create an instance of the Image Search app.
"""

import os

from connexion import FlaskApp
from flask import Flask, render_template
from flask_mongoengine import MongoEngine
from swagger_ui_bundle import swagger_ui_3_path

mongoengine = MongoEngine()


def create_app(testing=False):
    """
    Creates an instance of the Image Search app.
    """

    # create connexion app
    connexion_options = {'swagger_path': swagger_ui_3_path}
    connexion_app = FlaskApp(__name__,
                             specification_dir='./swagger',
                             options=connexion_options)
    connexion_app.add_api('swagger.yml')

    # get a reference to underlying flask app
    app = connexion_app.app

    # do this because we want to allow instance configs
    app.config.root_path = app.instance_path
Exemplo n.º 24
0
class WTFormsAppTestCase(FlaskMongoEngineTestCase):
    def setUp(self):
        super(WTFormsAppTestCase, self).setUp()
        self.db_name = "test_db"
        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):
        try:
            self.db.connection.drop_database(self.db_name)
        except Exception:
            self.db.connection.client.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.assertEqual(BlogPost.objects.first().title, "Using MongoEngine")
            self.assertEqual(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.assertEqual(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, field_args={"dog": {"allow_blank": True}}
            )

            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 the options - should contain a dog (selected) and a
            # blank option there should be an extra blank option.
            choices = list(form.dog)
            self.assertEqual(len(choices), 2)
            self.assertFalse(choices[0].checked)
            self.assertEqual(choices[0].data, "__None")
            self.assertTrue(choices[1].checked)
            self.assertEqual(choices[1].data, dog.pk)

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

            # Validate selecting no item
            form = DogOwnerForm(MultiDict({"dog": "__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, field_args={"dogs": {"allow_blank": True}}
            )

            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 the options - both dogs should be selected and
            # there should be an extra blank option.
            choices = list(form.dogs)
            self.assertEqual(len(choices), 3)
            self.assertFalse(choices[0].checked)
            self.assertEqual(choices[0].data, "__None")
            self.assertTrue(choices[1].checked)
            self.assertEqual(choices[1].data, dogs[0].pk)
            self.assertTrue(choices[2].checked)
            self.assertEqual(choices[2].data, dogs[1].pk)

            # 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": "__None"}), 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 = bson.ObjectId()
            Item(owner_id=object_id, owner_item_id="1").save()

            try:
                Item(owner_id=object_id, owner_item_id="1").save()
                self.fail("Should have raised duplicate key error")
            except Exception:
                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)
Exemplo n.º 25
0
from flask import Flask
from flask_pymongo import PyMongo
from flask_mongoengine import MongoEngine

mongo = PyMongo()
me = MongoEngine()


def create_app():
    app = Flask(__name__)
    '''
    app.config['SQLALCHEMY_DATABASE_URI'] = \
        'postgresql+psycopg2://likit@localhost/healthdw_dev'
    '''
    app.config['MONGO_DBNAME'] = 'health_services'
    app.config['MONGODB_DB'] = 'health_services'

    me.init_app(app)
    mongo.init_app(app)

    from api import healthservice_blueprint
    app.register_blueprint(healthservice_blueprint, url_prefix='/api')

    return app
Exemplo n.º 26
0
APP = Flask(__name__)
APP.secret_key = session_key("key.hex")
APP.jinja_env.add_extension('jinja2.ext.loopcontrols')
INTROMARKDOWN = intro(
    "README.md",
    "https://raw.githubusercontent.com/qeeqbox/analyzer/master/README.md")
APP.config['MONGODB_SETTINGS'] = json_settings[
    environ["analyzer_env"]]["web_mongo"]
APP.config['SESSION_COOKIE_SAMESITE'] = "Lax"
QUEUE = QBQueue("analyzer",
                json_settings[environ["analyzer_env"]]["redis_settings"])
ANALYZER_TIMEOUT = json_settings[environ["analyzer_env"]]["analyzer_timeout"]
FUNCTION_TIMEOUT = json_settings[environ["analyzer_env"]]["function_timeout"]
MALWARE_FOLDER = json_settings[environ["analyzer_env"]]["malware_folder"]

MONGO_DB = MongoEngine()
MONGO_DB.init_app(APP)
BCRYPT = Bcrypt(APP)
LOGIN_MANAGER = LoginManager()
LOGIN_MANAGER.setup_app(APP)
CSRF = CSRFProtect()
CSRF.init_app(APP)
Markdown(APP)


class Namespace:
    '''
    this namespace for switches
    '''
    def __init__(self, kwargs):
        self.__dict__.update(kwargs)
from flask import Flask
from flask_mongoengine import MongoEngine

from apis import api

from config import get_config

app = Flask(__name__)

db = MongoEngine()

CONFIG = get_config()
db.connect(db=CONFIG["mongodb"]["db_name"],
           username=CONFIG["mongodb"]["username"],
           password=CONFIG["mongodb"]["password"],
           host=CONFIG["mongodb"]["host"],
           port=CONFIG["mongodb"]["port"],
           authentication_source=CONFIG["mongodb"]["auth_source"])

api.init_app(app)
app.run(host="0.0.0.0", port=5000, debug=True)
Exemplo n.º 28
0
Arquivo: app.py Projeto: shinSG/frapp
#!/usr/bin/python
# coding=utf-8

from flask import Flask
from flask_restful import Resource, Api
from flask_mongoengine import MongoEngine
import config

web_site = Flask(__name__)
api = Api(web_site)
db = MongoEngine(web_site)

subapps = config.INSTALL_APPS

for app in subapps:
    api.add_resource(TApi, '/<string:id>')
Exemplo n.º 29
0
    SECRET_KEY = 'some secret'

    MONGODB_SETTINGS = {
        'db': 'neatflex',
        'host': 'mongodb://localhost:27017/neatflex'
    }

    # Flask-User settings
    USER_APP_NAME = "NeatFlex"
    USER_ENABLE_EMAIL = False
    USER_ENABLE_USERNAME = True
    USER_REQUIRE_RETYPE_PASSWORD = False


application.config.from_object(__name__ + '.ConfigClass')
db = MongoEngine(application)
auth = HTTPBasicAuth()


class Movie(db.Document):
    year = db.StringField()
    imdbid = db.StringField()
    title = db.StringField()
    genre = db.ListField(db.StringField())
    image = db.StringField()


class User(db.Document, UserMixin):
    # User authentication information
    username = db.StringField(default='')
    password_hash = db.StringField()
Exemplo n.º 30
0
    widget = widgets.ListWidget(prefix_label=False)
    option_widget = widgets.CheckboxInput()


# Configuration
basedir= os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config['MONGODB_SETTINGS']={
    'db': 'freelance',
    'host': os.environ.get('MONGO_LOGIN'),
    'port': 27017,
    'username': '******',
    'password': '******'
}
app.config['SECRET_KEY'] = 'very hard to guess string'
db = MongoEngine()
db.init_app(app)
bootstrap = Bootstrap(app)
migrate = Migrate(app,db)

#Database Classes
class User(db.DynamicDocument):
    username = db.StringField()
    password_hash = db.StringField()
    role = db.StringField()
    date_joined = db.DateField()
    posts = db.ReferenceField('JobPost')

    @property
    def password(self):
        raise AttributeError("Password is not a readable attribute")
Exemplo n.º 31
0
def mongoengine_setup(request, app, tmpdir, realdburl):
    pytest.importorskip("flask_mongoengine")
    from flask_mongoengine import MongoEngine
    from mongoengine.fields import (
        BooleanField,
        DateTimeField,
        IntField,
        ListField,
        ReferenceField,
        StringField,
    )

    db_name = "flask_security_test_%s" % str(time.time()).replace(".", "_")
    app.config["MONGODB_SETTINGS"] = {
        "db": db_name,
        "host": "mongomock://localhost",
        "port": 27017,
        "alias": db_name,
    }

    db = MongoEngine(app)

    class Role(db.Document, RoleMixin):
        name = StringField(required=True, unique=True, max_length=80)
        description = StringField(max_length=255)
        permissions = StringField(max_length=255)
        meta = {"db_alias": db_name}

    class User(db.Document, UserMixin):
        email = StringField(unique=True, max_length=255)
        fs_uniquifier = StringField(unique=True, max_length=64, required=True)
        username = StringField(unique=True,
                               required=False,
                               sparse=True,
                               max_length=255)
        password = StringField(required=False, max_length=255)
        security_number = IntField(unique=True, required=False, sparse=True)
        last_login_at = DateTimeField()
        current_login_at = DateTimeField()
        tf_primary_method = StringField(max_length=255)
        tf_totp_secret = StringField(max_length=255)
        tf_phone_number = StringField(max_length=255)
        us_totp_secrets = StringField()
        us_phone_number = StringField(max_length=255)
        last_login_ip = StringField(max_length=100)
        current_login_ip = StringField(max_length=100)
        login_count = IntField()
        active = BooleanField(default=True)
        confirmed_at = DateTimeField()
        roles = ListField(ReferenceField(Role), default=[])
        meta = {"db_alias": db_name}

    def tear_down():
        with app.app_context():
            User.drop_collection()
            Role.drop_collection()
            db.connection.drop_database(db_name)

    request.addfinalizer(tear_down)

    return MongoEngineUserDatastore(db, User, Role)
Exemplo n.º 32
0
from flask import Flask
from flask import render_template
from flask_mongoengine import MongoEngine
from flask_mongoengine import MongoEngineSessionInterface

app = Flask(__name__)

app.config.from_object("knife.config.EnvConfig")

engine = MongoEngine(app)
app.session_interface = MongoEngineSessionInterface(engine)


@app.route("/")
def index():
    return "test"
Exemplo n.º 33
0
class WTFormsAppTestCase(FlaskMongoEngineTestCase):

    def setUp(self):
        super(WTFormsAppTestCase, self).setUp()
        self.db_name = 'test_db'
        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):
        try:
            self.db.connection.drop_database(self.db_name)
        except Exception:
            self.db.connection.client.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, field_args={
                'dog': {'allow_blank': True}
            })

            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 the options - should contain a dog (selected) and a
            # blank option there should be an extra blank option.
            choices = list(form.dog)
            self.assertEqual(len(choices), 2)
            self.assertFalse(choices[0].checked)
            self.assertEqual(choices[0].data, '__None')
            self.assertTrue(choices[1].checked)
            self.assertEqual(choices[1].data, dog.pk)

            # 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, field_args={
                'dogs': {'allow_blank': True}
            })

            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 the options - both dogs should be selected and
            # there should be an extra blank option.
            choices = list(form.dogs)
            self.assertEqual(len(choices), 3)
            self.assertFalse(choices[0].checked)
            self.assertEqual(choices[0].data, '__None')
            self.assertTrue(choices[1].checked)
            self.assertEqual(choices[1].data, dogs[0].pk)
            self.assertTrue(choices[2].checked)
            self.assertEqual(choices[2].data, dogs[1].pk)

            # 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': '__None',
            }), 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 = bson.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 Exception:
                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)
Exemplo n.º 34
0
from flask_sqlalchemy import SQLAlchemy
from flask_security import Security, SQLAlchemyUserDatastore, \
    UserMixin, RoleMixin, login_required, current_user
from flask_security.utils import encrypt_password
import flask_admin
from flask_admin.contrib import sqla
from flask_mongoengine import MongoEngine
from flask_admin.contrib.mongoengine import ModelView
from flask_admin import helpers as admin_helpers
# Create Flask application
app = Flask(__name__)
app.config.from_pyfile('config.py')
# Creamos modelo relacional
db = SQLAlchemy(app)
#Creamos modelo
dbm = MongoEngine()
dbm.init_app(app)


# Define models
roles_users = db.Table(
    'roles_users',
    db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
    db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))
)


class Role(db.Model, RoleMixin):
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(80), unique=True)
    description = db.Column(db.String(255))
Exemplo n.º 35
0
from flask_cors import CORS
from flask_mongoengine import MongoEngine
from flask_httpauth import HTTPBasicAuth


# Flask 实例
blog = Flask(__name__,
            instance_relative_config=True,
			static_folder = "../../dist/static",
			template_folder= "../../dist")

# auth
auth = HTTPBasicAuth()

# 载入配置
blog.config.from_object('config')
blog.config.from_pyfile('config.py')

# 允许跨域
cors = CORS(blog, resource={"/api/*": {"origins": "*"}})

# 数据库初始化
db = MongoEngine()
db.init_app(blog)

# 所有路由由 vue 接管
@blog.route("/", defaults={'path': ''})
@blog.route('/<path:path>')
def catch_all(path):
    return render_template("index.html")
Exemplo n.º 36
0
from flask_mongoengine import MongoEngine
from bson import json_util, ObjectId
from flask_cors import CORS

import pymongo
from pymongo import MongoClient

HOST_NAME = 'localhost'

app = Flask(__name__)
CORS(app)
app.config['MONGODB_SETTINGS'] = {'host': '127.0.0.1', 'db': 'kumi'}

kumi_mongo_client = MongoClient('localhost', 27017)
kumi_db = kumi_mongo_client.kumi
db = MongoEngine()
db.init_app(app)
try:
    db.get_db()
except pymongo.errors.OperationFailure as e:
    print(e)
    sys.exit(-1)

from models.course import course_api
app.register_blueprint(course_api)

app.secret_key = b'\xcc^\x91\xea\x17-\xd0W\x03\xa7\xf8J0\xac8\xc5'  # move to different file later


# Database
def login_required(
Exemplo n.º 37
0
"""
FILE: app/__init.py__

This file contains the application factory (Flask instance created here)
and allows 'site' to be treated like a package.
"""

import os

from flask import Flask
from config import Config
from flask_cors import CORS  #comment this on deployment
from flask_mongoengine import MongoEngine
from flask_jwt_extended import JWTManager

db = MongoEngine()  # db initialization occurs before the app starts

app = Flask(__name__)
app.config.from_object(Config)

app.config['MONGODB_SETTINGS'] = {
    "db": "simplicity-cloud",
    "host": "localhost",
    "port": 27017
}
db.init_app(app)

# hw1 = Hardware(name="Set1", capacity=512)

jwt = JWTManager(app)
Exemplo n.º 38
0
from datetime import datetime
import mongoengine as me
from mongoengine import ListField, EmbeddedDocumentField, EmbeddedDocument
from mongoengine import *
from bson.objectid import ObjectId

app = Flask(__name__)
title = "Task-Manager"
heading = "Task-Manager"

app.config['MONGODB_SETTINGS'] = {  # connection to databse
    'db': 'mydb1',
    'host': 'localhost',
    'port': 27017
}
db = MongoEngine()
db.init_app(app)  # creates the object of database connection

count = 1
user = None
admin = None


class Task(me.EmbeddedDocument):  # creating database model
    tid = me.IntField(default=0)
    name = me.StringField(max_length=200, required=True)
    desc = me.StringField(max_length=250, required=True)
    comments = me.StringField(max_length=250, required=True)
    priority = me.IntField(default=5)
    date = me.DateTimeField(default=datetime.utcnow())
    status = me.BooleanField(default=False)
Exemplo n.º 39
0
import functools

from . import config_env_list, version

_db = None
if os.environ.get('FANTASY_ACTIVE_DB', 'no') == 'yes':
    from flask_sqlalchemy import SQLAlchemy

    _db = SQLAlchemy()
    pass

_doc_db = None
if os.environ.get('FANTASY_ACTIVE_DOC_DB', 'no') == 'yes':
    from flask_mongoengine import MongoEngine

    _doc_db = MongoEngine()
    pass


def connect_celery(app, celery):
    app.celery = celery
    celery.conf.update(app.config)

    class ContextTask(celery.Task):
        def __call__(self, *args, **kwargs):
            with app.app_context():
                return self.run(*args, **kwargs)

    celery.Task = ContextTask
    pass
Exemplo n.º 40
0
import logging

from flask import Flask
from flask_appbuilder import AppBuilder
from flask_appbuilder.security.mongoengine.manager import SecurityManager
from flask_mongoengine import MongoEngine

logging.basicConfig(format="%(asctime)s:%(levelname)s:%(name)s:%(message)s")
logging.getLogger().setLevel(logging.DEBUG)

app = Flask(__name__)
app.config.from_object("config")
dbmongo = MongoEngine(app)
appbuilder = AppBuilder(app, security_manager_class=SecurityManager)

from . import models, views  # noqa
Exemplo n.º 41
0
from flask import Flask
from flask_mongoengine import MongoEngine
from flask_jwt_extended import JWTManager
from flask_mail import Mail
from todo.utils.response import response_with
import todo.utils.response_code as response_code
from celery import Celery
import logging

# Init MongoDB object
mongo = MongoEngine()

# Init Flask-Mail object
mail = Mail()

# Init Celery object
celery = Celery(__name__)


def init_celery(app, celery):
    """
    Update celery config and celery object with application context

    :param app: Flask application object
    :param celery: Celery object
    """
    celery.conf.update(broker_url=app.config['CELERY_BROKER_URL'],
                       result_backend=app.config['CELERY_RESULT_BACKEND'])

    class ContextTask(celery.Task):
        def __call__(self, *args, **kwargs):
Exemplo n.º 42
0
def create_app():
    """ Flask application factory """
    
    # Setup Flask and load app.config
    app = Flask(__name__)
    app.config.from_object(__name__+'.ConfigClass')

    # Setup Flask-MongoEngine
    db = MongoEngine(app)

    # Define the User document.
    # NB: Make sure to add flask_user UserMixin !!!
    class User(db.Document, UserMixin):
        active = db.BooleanField(default=True)

        # User authentication information
        username = db.StringField(default='')
        password = db.StringField()

        # User information
        first_name = db.StringField(default='')
        last_name = db.StringField(default='')

        # Relationships
        roles = db.ListField(db.StringField(), default=[])

    # Setup Flask-User and specify the User data-model
    user_manager = UserManager(app, db, User)

    # The Home page is accessible to anyone
    @app.route('/')
    def home_page():
        # String-based templates
        return render_template_string("""
            {% extends "flask_user_layout.html" %}
            {% block content %}
                <h2>Home page</h2>
                <p><a href={{ url_for('user.register') }}>Register</a></p>
                <p><a href={{ url_for('user.login') }}>Sign in</a></p>
                <p><a href={{ url_for('home_page') }}>Home page</a> (accessible to anyone)</p>
                <p><a href={{ url_for('member_page') }}>Member page</a> (login required)</p>
                <p><a href={{ url_for('user.logout') }}>Sign out</a></p>
            {% endblock %}
            """)

    # The Members page is only accessible to authenticated users via the @login_required decorator
    @app.route('/members')
    @login_required    # User must be authenticated
    def member_page():
        # String-based templates
        return render_template_string("""
            {% extends "flask_user_layout.html" %}
            {% block content %}
                <h2>Members page</h2>
                <p><a href={{ url_for('user.register') }}>Register</a></p>
                <p><a href={{ url_for('user.login') }}>Sign in</a></p>
                <p><a href={{ url_for('home_page') }}>Home page</a> (accessible to anyone)</p>
                <p><a href={{ url_for('member_page') }}>Member page</a> (login required)</p>
                <p><a href={{ url_for('user.logout') }}>Sign out</a></p>
            {% endblock %}
            """)

    return app
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# __author__ = "@netwookie"
# __credits__ = ["Rick Kauffman"]
# __license__ = "Apache2.0"
# __version__ = "1.0.0"
# __maintainer__ = "Rick Kauffman"
# __email__ = "*****@*****.**"

from flask import Flask
from flask_mongoengine import MongoEngine

db = MongoEngine()


def create_app(**config_overrides):
    app = Flask(__name__)
    app.config.from_pyfile('settings.py')

    app.config['MONGODB_SETTINGS'] = {
        'db': 'app_db',
        'host': 'localhost',
        'port': 27017,
        'username': '******',
        'password': '******',
        'authentication_source': 'admin'
    }
Exemplo n.º 44
0
"""
CRUD and filter tests
"""
import json
import unittest
from unittest.mock import MagicMock
from flask_mongoengine import MongoEngine
from app import APP
from authentification import JwtTokenAuthentication
from documents import Comment, User

DB = MongoEngine()
APP.config.from_pyfile('configs/testing.conf')
DB.init_app(APP)


class UnauthorizedTestCase(unittest.TestCase):
    """
    Authorization method returns unauthorized 401
    """
    def setUp(self):
        self.authorized = JwtTokenAuthentication.authorized
        JwtTokenAuthentication.authorized = MagicMock(return_value=False)

    def tearDown(self):
        JwtTokenAuthentication.authorized = self.authorized


class AuthorizedTestCase(unittest.TestCase):
    """
    Authorization method returns authorized 200
Exemplo n.º 45
0
# -*- coding:utf-8 -*-
from flask import Flask, render_template
from flask_bootstrap import Bootstrap
from config import config
from flask_moment import Moment
from flask_mongoengine import MongoEngine
import datetime

bootstrap = Bootstrap()
moment = Moment()
mongo_db = MongoEngine()


# 自定义jinjia2的过滤器
def transform_timestamp(timestamp):
    d = datetime.datetime.fromtimestamp(timestamp)
    result = d.strftime("%Y-%m-%d")
    return result


def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    bootstrap.init_app(app)
    moment.init_app(app)
    mongo_db.init_app(app)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)
Exemplo n.º 46
0
import datetime
from flask import Flask
from flask_mongoengine import MongoEngine

db = MongoEngine()
app = Flask(__name__, static_url_path='/assets', static_folder='assets')
app.config['MONGODB_SETTINGS'] = {'DB': 'startup'}
db.init_app(app)


class Keyword(db.Document):
    word = db.StringField(unique=True)
    website = db.DictField()
    weibo = db.DictField()
    wechat = db.DictField()
    facebook = db.DictField()
    twitter = db.DictField()
    instagram = db.DictField()
    github = db.DictField()
    created = db.DateTimeField()
    updated = db.DateTimeField(default=datetime.datetime.now)

    def save(self, *args, **kwargs):
        if not self.created:
            self.created = datetime.datetime.now()
        self.updated = datetime.datetime.now()
        return super(Keyword, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.word
Exemplo n.º 47
0
}

app.config["CELERY_BROKER_URL"] = "redis://{username}:{password}@{host}:{port}/{db}".format(
    host=CONFIG.get("redis.host"),
    port=CONFIG.get("redis.port"),
    db=CONFIG.get("redis.db", 0),
    username=CONFIG.get("redis.username", ""),
    password=CONFIG.get("redis.password", ""),
)

app.config["CACHE_TYPE"] = "redis"
app.config["CACHE_REDIS_URL"] = app.config["CELERY_BROKER_URL"]
app.config["CACHE_DEFAULT_TIMEOUT"] = CONFIG.get("api.default_cache_times")


DB = MongoEngine(app)

CACHE = Cache(app)

CELERY = Celery(app.name, broker=app.config["CELERY_BROKER_URL"])
CELERY.conf.update(app.config)


@CELERY.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):
    from . import tasks

    sender.add_periodic_task(
        CONFIG.get("api.fetch_photos_delta"),
        tasks.fetch_photos.s(),
        name="Fetch photos",
Exemplo n.º 48
0
def create_app(is_sentry_on=False, **kwargs):
    app = Flask(__name__)

    app.config.update(kwargs or {})

    db = MongoEngine()

    CORS(app)

    if 'TESTING' in kwargs and kwargs['TESTING']:
        app.testing = True

        db.init_app(
            app, {
                'MONGODB_SETTINGS': {
                    'db':
                    'testing',
                    'host':
                    'mongodb://*****:*****@ds111876.mlab.com:11876/testing'
                }
            })
        # db.connection
    else:
        app.config['MONGODB_SETTINGS'] = {
            'db':
            'cheapbookdev',
            'host':
            'mongodb://*****:*****@ds053305.mlab.com:53305/cheapbookdev'
        }
        db.init_app(app)

    import models
    configs = models.Config.objects.get(config_id='initials')
    app.config.from_object(configs)
    app.config['DEBUG'] = False

    mail = flask_mail.Mail()
    mail.init_app(app=app)
    if is_sentry_on:
        sentry = Sentry(
            dsn=
            'https://*****:*****@sentry.io/177217'
        )
        sentry.init_app(app)
    flask_mobility.Mobility().init_app(app=app)

    from utils.exception_handler import error_dict, Handler

    for e in error_dict:
        app.register_error_handler(e, Handler(e).generate_response)
    from utils.exceptions import general_exceptions

    # @app.errorhandler(404)
    # @app.errorhandler(401)
    @app.errorhandler(500)
    @json_response
    def page_not_found_500(error):
        print(error)
        return general_exceptions.BASIC_ERROR_500

    @app.errorhandler(404)
    @json_response
    def page_not_found_404(error):
        print(error)
        return general_exceptions.BASIC_ERROR_500

    @app.before_request
    def before_request():
        request_data = save_request(request)
        global_storage.request_data = request_data

    @app.after_request
    def after_request(resp):
        resp_data = save_response(resp)
        request_data = global_storage.request_data
        traffic = models.Traffic(request=request_data, response=resp_data)
        traffic.save()
        return resp

    import URLs
    routes = URLs.get_urls()
    for model in dir(models):
        temp_class = getattr(models, model)
        if inspect.isclass(temp_class) and issubclass(
                temp_class, models.base.BaseDocument):
            print(temp_class.__name__)
            app.url_map.converters[
                temp_class.__name__] = temp_class.get_converter()

    for route in routes:
        imported_class = route['cls']

        route_object = imported_class()
        app.add_url_rule(route['route'],
                         view_func=route_object.dispatcher,
                         endpoint=route['endpoint'],
                         methods=['GET', 'POST', 'PUT', 'DELETE'])

    return app
Exemplo n.º 49
0
def get_db_connection(app):
    app.config['MONGODB_HOST'] = DB_URI
    db = MongoEngine()
    db.init_app(app)
    return db
Exemplo n.º 50
0
        try:
            doc = self.get(*q_objs, **query)
            return doc, False
        except self._document.DoesNotExist:
            query.update(defaults)
            doc = self._document(**query)

            if auto_save:
                doc.save(write_options=write_options)
            return doc, True


class QuokkaDocument(Document):
    """Abstract document with extra helpers in the queryset class"""

    meta = {'abstract': True,
            'queryset_class': QuokkaQuerySet}


class QuokkaDynamicDocument(DynamicDocument):
    """Abstract Dynamic document with extra helpers in the queryset class"""

    meta = {'abstract': True,
            'queryset_class': QuokkaQuerySet}


db = MongoEngine()
db.ListField = ListField
db.Document = QuokkaDocument
db.DynamicDocument = QuokkaDynamicDocument
Exemplo n.º 51
0
def get_db(app):
    db = getattr(g, '_database', None)
    if db is None:
        db = g._database = MongoEngine(app)
    return db