當前位置: 首頁>>代碼示例>>Python>>正文


Python MongoEngine.init_app方法代碼示例

本文整理匯總了Python中flask_mongoengine.MongoEngine.init_app方法的典型用法代碼示例。如果您正苦於以下問題:Python MongoEngine.init_app方法的具體用法?Python MongoEngine.init_app怎麽用?Python MongoEngine.init_app使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在flask_mongoengine.MongoEngine的用法示例。


在下文中一共展示了MongoEngine.init_app方法的14個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: setUp

# 需要導入模塊: from flask_mongoengine import MongoEngine [as 別名]
# 或者: from flask_mongoengine.MongoEngine import init_app [as 別名]
    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
開發者ID:adamchainz,項目名稱:flask-mongoengine,代碼行數:37,代碼來源:test_json_app.py

示例2: setUp

# 需要導入模塊: from flask_mongoengine import MongoEngine [as 別名]
# 或者: from flask_mongoengine.MongoEngine import init_app [as 別名]
    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
開發者ID:adamchainz,項目名稱:flask-mongoengine,代碼行數:35,代碼來源:test_basic_app.py

示例3: setUp

# 需要導入模塊: from flask_mongoengine import MongoEngine [as 別名]
# 或者: from flask_mongoengine.MongoEngine import init_app [as 別名]
 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
開發者ID:MongoEngine,項目名稱:flask-mongoengine,代碼行數:10,代碼來源:test_json.py

示例4: test_connection_default

# 需要導入模塊: from flask_mongoengine import MongoEngine [as 別名]
# 或者: from flask_mongoengine.MongoEngine import init_app [as 別名]
    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)
開發者ID:adamchainz,項目名稱:flask-mongoengine,代碼行數:12,代碼來源:test_basic_app.py

示例5: setup

# 需要導入模塊: from flask_mongoengine import MongoEngine [as 別名]
# 或者: from flask_mongoengine.MongoEngine import init_app [as 別名]
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
開發者ID:alanhamlett,項目名稱:flask-admin,代碼行數:14,代碼來源:__init__.py

示例6: create_app

# 需要導入模塊: from flask_mongoengine import MongoEngine [as 別名]
# 或者: from flask_mongoengine.MongoEngine import init_app [as 別名]
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
開發者ID:xinali,項目名稱:penework,代碼行數:15,代碼來源:app.py

示例7: setUp

# 需要導入模塊: from flask_mongoengine import MongoEngine [as 別名]
# 或者: from flask_mongoengine.MongoEngine import init_app [as 別名]
    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)
開發者ID:usnistgov,項目名稱:corr,代碼行數:17,代碼來源:test_models.py

示例8: create_app

# 需要導入模塊: from flask_mongoengine import MongoEngine [as 別名]
# 或者: from flask_mongoengine.MongoEngine import init_app [as 別名]
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
開發者ID:donthack-me,項目名稱:donthackme_api,代碼行數:21,代碼來源:app.py

示例9: test_live_connection

# 需要導入模塊: from flask_mongoengine import MongoEngine [as 別名]
# 或者: from flask_mongoengine.MongoEngine import init_app [as 別名]
    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)
開發者ID:adamchainz,項目名稱:flask-mongoengine,代碼行數:26,代碼來源:test_connection.py

示例10: Flask

# 需要導入模塊: from flask_mongoengine import MongoEngine [as 別名]
# 或者: from flask_mongoengine.MongoEngine import init_app [as 別名]
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")
開發者ID:huybery,項目名稱:huybery-blog,代碼行數:32,代碼來源:__init__.py

示例11: WTFormsAppTestCase

# 需要導入模塊: from flask_mongoengine import MongoEngine [as 別名]
# 或者: from flask_mongoengine.MongoEngine import init_app [as 別名]
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)
#.........這裏部分代碼省略.........
開發者ID:MongoEngine,項目名稱:flask-mongoengine,代碼行數:103,代碼來源:test_forms.py

示例12: Flask

# 需要導入模塊: from flask_mongoengine import MongoEngine [as 別名]
# 或者: from flask_mongoengine.MongoEngine import init_app [as 別名]
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))
開發者ID:e-gob,項目名稱:Notificaciones-SES,代碼行數:32,代碼來源:app.py

示例13: MongoEngine

# 需要導入模塊: from flask_mongoengine import MongoEngine [as 別名]
# 或者: from flask_mongoengine.MongoEngine import init_app [as 別名]
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
開發者ID:iamsk,項目名稱:startupbox,代碼行數:32,代碼來源:models.py

示例14: PaginationTestCase

# 需要導入模塊: from flask_mongoengine import MongoEngine [as 別名]
# 或者: from flask_mongoengine.MongoEngine import init_app [as 別名]
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()
開發者ID:MongoEngine,項目名稱:flask-mongoengine,代碼行數:99,代碼來源:test_pagination.py


注:本文中的flask_mongoengine.MongoEngine.init_app方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。