本文整理汇总了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
示例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
示例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
示例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)
示例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
示例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
示例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)
示例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
示例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)
示例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")
示例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)
#.........这里部分代码省略.........
示例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))
示例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
示例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()