示例#1
0
    def test_multiple_pymongos(self):
        uri1 = "mongodb://localhost:{}/{}".format(self.port, self.dbname)
        uri2 = "mongodb://localhost:{}/{}".format(self.port, self.dbname + "2")

        mongo1 = flask_pymongo.PyMongo(self.app,
                                       uri1)  # noqa: F841 unused variable
        mongo2 = flask_pymongo.PyMongo(self.app,
                                       uri2)  # noqa: F841 unused variable
示例#2
0
 def test_config_without_document_class(self):
     self.app.config['MONGO_PORT'] = self.port
     mongo = flask_pymongo.PyMongo(self.app)
     if pymongo.version_tuple[0] > 2:
         assert mongo.cx.codec_options.document_class == dict
     else:
         assert mongo.cx.document_class == dict
示例#3
0
    def setUp(self):
        super(FlaskPyMongoTest, self).setUp()

        self.dbname = self.__class__.__name__
        self.app.config['MONGO_DBNAME'] = self.dbname
        self.mongo = flask_pymongo.PyMongo(self.app)
        self.mongo.cx.drop_database(self.dbname)
示例#4
0
    def test_it_doesnt_require_db_name_in_uri(self):
        uri = "mongodb://localhost:{}".format(self.port)

        with doesnt_raise(Exception):
            mongo = flask_pymongo.PyMongo(self.app, uri)

        assert mongo.db is None
示例#5
0
    def test_multiple_pymongos(self):
        for prefix in ('ONE', 'TWO'):
            self.app.config['%s_PORT' % prefix] = self.port
            self.app.config['%s_DBNAME' % prefix] = prefix

        for prefix in ('ONE', 'TWO'):
            flask_pymongo.PyMongo(self.app, config_prefix=prefix)
示例#6
0
    def test_it_doesnt_connect_by_default(self):
        uri = "mongodb://localhost:{}/{}".format(self.port, self.dbname)

        mongo = flask_pymongo.PyMongo(self.app, uri)

        with pytest.raises(CouldNotConnect):
            _wait_until_connected(mongo, timeout=0.2)
示例#7
0
    def test_config_with_uri_passed_directly(self):
        uri = "mongodb://localhost:{}/{}".format(self.port, self.dbname)

        mongo = flask_pymongo.PyMongo(self.app, uri, connect=True)

        _wait_until_connected(mongo)
        assert mongo.db.name == self.dbname
        assert ("localhost", self.port) == mongo.cx.address
示例#8
0
 def test_config_with_document_class(self):
     self.app.config['MONGO_PORT'] = self.port
     self.app.config['MONGO_DOCUMENT_CLASS'] = CustomDict
     mongo = flask_pymongo.PyMongo(self.app)
     if pymongo.version_tuple[0] > 2:
         assert mongo.cx.codec_options.document_class == CustomDict
     else:
         assert mongo.cx.document_class == CustomDict
示例#9
0
    def test_config_with_uri_in_flask_conf_var(self):
        uri = "mongodb://localhost:{}/{}".format(self.port, self.dbname)
        self.app.config["MONGO_URI"] = uri

        mongo = flask_pymongo.PyMongo(self.app, connect=True)

        _wait_until_connected(mongo)
        assert mongo.db.name == self.dbname
        assert ("localhost", self.port) == mongo.cx.address
示例#10
0
    def test_custom_document_class(self):
        class CustomDict(dict):
            pass

        uri = "mongodb://localhost:{}/{}".format(self.port, self.dbname)
        mongo = flask_pymongo.PyMongo(self.app, uri, document_class=CustomDict)
        assert mongo.db.things.find_one() is None, "precondition failed"

        mongo.db.things.insert_one({"_id": "thing", "val": "foo"})

        assert type(mongo.db.things.find_one()) == CustomDict
示例#11
0
    def test_custom_config_prefix(self):
        self.app.config['CUSTOM_DBNAME'] = 'flask_pymongo_test_db'
        self.app.config['CUSTOM_HOST'] = 'localhost'
        self.app.config['CUSTOM_PORT'] = self.port

        mongo = flask_pymongo.PyMongo(self.app, 'CUSTOM')
        assert mongo.db.name == 'flask_pymongo_test_db', 'wrong dbname: %s' % mongo.db.name
        if pymongo.version_tuple[0] > 2:
            time.sleep(0.2)
            assert ('localhost', self.port) == mongo.cx.address
        else:
            assert mongo.cx.host == 'localhost'
            assert mongo.cx.port == self.port
示例#12
0
    def test_converts_str_to_int(self):
        self.app.config['MONGO_DBNAME'] = 'flask_pymongo_test_db'
        self.app.config['MONGO_HOST'] = 'localhost'
        self.app.config['MONGO_PORT'] = str(self.port)

        mongo = flask_pymongo.PyMongo(self.app)
        assert mongo.db.name == 'flask_pymongo_test_db', 'wrong dbname: %s' % mongo.db.name
        if pymongo.version_tuple[0] > 2:
            time.sleep(0.2)
            assert ('localhost', self.port) == mongo.cx.address
        else:
            assert mongo.cx.host == 'localhost'
            assert mongo.cx.port == self.port
    def configure_instance(self, app, database_name):
        mongo_host = os.environ.get('MONGO_HOST')
        if mongo_host is None:
            mongo_host = 'localhost'

        mongo_port = os.environ.get('MONGO_PORT')
        if mongo_port is None:
            mongo_port = 27017

        # TODO: add a password to the mongo database so that its contents are hidden behind this API
        app.config['MONGO_URI'] = 'mongodb://{0}:{1}/{2}'.format(
            mongo_host, mongo_port, database_name)
        MongoSession.instance.mongo = flask_pymongo.PyMongo(app)
示例#14
0
    def configure_instance(self, app, database_name):
        mongo_host = os.environ.get('MONGO_HOST')
        if mongo_host is None:
            mongo_host = 'localhost'

        mongo_port = os.environ.get('MONGO_PORT')
        if mongo_port is None:
            mongo_port = 27017

        # TODO: add a password to the mongo database so that its contents are
        # TODO: hidden behind this API
        uri = f"mongodb://{mongo_host}:{mongo_port}/{database_name}"
        app.config['MONGO_URI'] = uri
        MongoSession.instance.mongo = flask_pymongo.PyMongo(app)
示例#15
0
 def __init__(self):
     super(WebServer, self).__init__(__name__)
     if ROLLBAR_KEY:
         self.setup_rollbar()
     self.before_request(WebServer._redirect_to_https)
     self.before_request(self._check_auth)
     self.config['MONGO_URI'] = MONGO_URI
     self.mongo = flask_pymongo.PyMongo(self)
     with self.app_context() as ctx:
         self.tokens = store.TokenStore(self.mongo.db.tokens,
                                        ctx,
                                        key=CRYPTO_KEY)
         self.archive = slack_archive.SlackArchive(self.mongo.db, ctx,
                                                   self.tokens,
                                                   SLACK_TEAM_TOKEN)
示例#16
0
    def test_host_with_port_does_not_get_overridden_by_separate_port_config_value(
            self):
        self.app.config['MONGO_HOST'] = 'localhost:{}'.format(self.port)
        self.app.config['MONGO_PORT'] = 27018

        with warnings.catch_warnings():
            # URI connections without a username and password
            # work, but warn that auth should be supplied
            warnings.simplefilter('ignore')
            mongo = flask_pymongo.PyMongo(self.app)
        if pymongo.version_tuple[0] > 2:
            time.sleep(0.2)
            assert ('localhost', self.port) == mongo.cx.address
        else:
            assert mongo.cx.host == 'localhost'
            assert mongo.cx.port == self.port
示例#17
0
    def test_config_with_uri_no_port(self):
        self.app.config[
            'MONGO_URI'] = 'mongodb://localhost/flask_pymongo_test_db'

        with warnings.catch_warnings():
            # URI connections without a username and password
            # work, but warn that auth should be supplied
            warnings.simplefilter('ignore')
            mongo = flask_pymongo.PyMongo(self.app)
        assert mongo.db.name == 'flask_pymongo_test_db', 'wrong dbname: %s' % mongo.db.name
        if pymongo.version_tuple[0] > 2:
            time.sleep(0.2)
            assert ('localhost', self.port) == mongo.cx.address
        else:
            assert mongo.cx.host == 'localhost'
            assert mongo.cx.port == self.port
示例#18
0
    def __init__(self, app):
        """Configures the mongodb name and uri
        using the reader in client."""

        self.app = app

        read = reader.Reader()

        self.app.config['MONGODB_NAME'] = read.get_d_value()[0]
        self.app.config['MONGO_URI'] = read.get_d_value()[1]

        try:
            self.database = flask_pymongo.PyMongo(self.app)
            self.handler = self.database.db.packets
        except (pymongo.errors.InvalidURI, pymongo.errors.InvalidName,
                pymongo.errors.ConnectionFailure):
            print("Invalid database URI or database name.")
            exit(-1)
示例#19
0
    def test_missing_auth_mechanism_in_prefixed_config(self):
        self.app.config["CUSTOM_MONGO_HOST"] = 'localhost'
        self.app.config["CUSTOM_MONGO_PORT"] = self.port
        self.app.config["CUSTOM_MONGO_USERNAME"] = '******'
        self.app.config["CUSTOM_MONGO_PASSWORD"] = '******'
        self.app.config['CUSTOM_MONGO_DBNAME'] = 'test_db'

        mongo = flask_pymongo.PyMongo(self.app, 'CUSTOM_MONGO')

        assert mongo.db.name == 'test_db', 'wrong dbname: %s' % mongo.db.name

        if pymongo.version_tuple[0] > 2:
            time.sleep(0.2)

            assert ('localhost', self.port) == mongo.cx.address
        else:
            assert mongo.cx.host == 'localhost'
            assert mongo.cx.port == self.port
示例#20
0
文件: app.py 项目: brandon15811/slag
 def __init__(self):
     super(WebServer, self).__init__(__name__)
     if (os.environ.get('WERKZEUG_RUN_MAIN') != 'true'
             and 'gunicorn' not in os.environ.get('SERVER_SOFTWARE', '')):
         return  # skip any heavy operations for Werkzeug debug wrapper
     if ROLLBAR_KEY:
         self.setup_rollbar()
     self.before_request(WebServer._redirect_to_https)
     self.before_request(self._check_auth)
     self.config['MONGO_URI'] = MONGO_URI
     self.mongo = flask_pymongo.PyMongo(self)
     with self.app_context() as ctx:
         self.tokens = store.TokenStore(self.mongo.db.tokens,
                                        ctx,
                                        key=CRYPTO_KEY)
         self.archive = slack_archive.SlackArchive(self.mongo, ctx,
                                                   self.tokens,
                                                   SLACK_TEAM_TOKEN)
示例#21
0
def create_session(app, database_name, host=None, port=None):
    if host is None or port is None:
        host, port = get_host_and_port()
        print(f"mongodb host and port set to {host}:{port}")
    url = f"mongodb://{host}:{port}/{database_name}"
    app.config['MONGO_URI'] = url
    sess = flask_pymongo.PyMongo(app, serverSelectionTimeoutMS=5000)
    SSTE = flask_pymongo.pymongo.errors.ServerSelectionTimeoutError
    try:
        print("Confirming connection to mongodb...", end='', flush=True)
    except SSTE as e:
        msg = textwrap.dedent(f"""\
            {str(e)}

            Cannot connect to mongodb.
            Tried using MONGO_URI of {url}
            """)
        raise SSTE(msg) from None
    print("Connected!", flush=True)
    return sess
示例#22
0
    def test_uri_prioritised_over_host_and_port(self):
        self.app.config[
            'MONGO_URI'] = 'mongodb://localhost:{}/database_name'.format(
                self.port)
        self.app.config['MONGO_HOST'] = 'some_other_host'
        self.app.config['MONGO_PORT'] = 27018
        self.app.config['MONGO_DBNAME'] = 'not_the_correct_db_name'

        with warnings.catch_warnings():
            # URI connections without a username and password
            # work, but warn that auth should be supplied
            warnings.simplefilter('ignore')
            mongo = flask_pymongo.PyMongo(self.app)
        if pymongo.version_tuple[0] > 2:
            time.sleep(0.2)
            assert ('localhost', self.port) == mongo.cx.address
        else:
            assert mongo.cx.host == 'localhost'
            assert mongo.cx.port == self.port
        assert mongo.db.name == 'database_name'
示例#23
0
    def test_create_with_document_class(self):
        """ This test doesn't use self.mongo, because it has to change config

        It uses second mongo connection, using a CUSTOM prefix to avoid
        duplicate config_prefix exception. To make use of tearDown and thus DB
        deletion even in case of failure, it uses same DBNAME.

        """
        # copying standard DBNAME, so this DB gets also deleted by tearDown
        self.app.config['CUSTOM_DBNAME'] = self.app.config['MONGO_DBNAME']
        self.app.config['CUSTOM_DOCUMENT_CLASS'] = CustomDict
        self.app.config['CUSTOM_PORT'] = self.port
        # not using self.mongo, because we want to use updated config
        # also using CUSTOM, to avoid duplicate config_prefix exception
        mongo = flask_pymongo.PyMongo(self.app, 'CUSTOM')
        assert mongo.db.things.find_one() is None
        # write document and retrieve, to check if type is really CustomDict
        if pymongo.version_tuple[0] > 2:
            # Write Concern is set to w=1 by default in pymongo > 3.0
            mongo.db.things.insert_one({'_id': 'thing', 'val': 'foo'})
        else:
            mongo.db.things.insert({'_id': 'thing', 'val': 'foo'}, w=1)
        assert type(mongo.db.things.find_one()) == CustomDict
示例#24
0
    def setUp(self):
        super(FlaskPyMongoTest, self).setUp()

        uri = "mongodb://localhost:{}/{}".format(self.port, self.dbname)
        self.mongo = flask_pymongo.PyMongo(self.app, uri)
示例#25
0
    def test_it_fails_with_no_uri(self):
        self.app.config.pop("MONGO_URI", None)

        with pytest.raises(ValueError):
            flask_pymongo.PyMongo(self.app)
示例#26
0
import os
from flask import Flask, render_template, redirect, request, url_for
import flask_pymongo
from bson.objectid import ObjectId
from os import path
from utils.db_utils import handle_mongo_errors, find_object
if path.exists("env.py"):
    import env

app = Flask(__name__)
app.config["MONGO_DBNAME"] = 'fuel_management'
app.config["MONGO_URI"] = os.environ.get('MONGO_URI')
app.config["FLASK_DEBUG"] = False
app.config["SECRET_KEY"] = b'_5#y2L"F4Q8z\n\xec]/'

mongo = flask_pymongo.PyMongo(app)


@app.route('/')
@app.route('/get_receipts')
def get_receipts():
    """
    Display all the receipts for the user
    """
    return render_template('receipts.html', receipts=mongo.db.receipts.find())


@app.route('/add_receipt')
def add_receipt():
    return render_template('addreceipt.html', sites=mongo.db.sites.find())
示例#27
0
ALWAYS_PRESENT = ['Assassin', 'Merlin']
EVIL = ['Mordred', 'Morgana', 'Oberon', 'Minion of Mordred', 'Assassin']
GOOD = ['Merlin', 'Percival', 'Loyal Servant of Arthur']
GENERIC_BAD, GENERIC_GOOD = 'Minion of Mordred', 'Loyal Servant of Arthur'
OPTIONAL_ROLES = ['Mordred', 'Morgana', 'Percival', 'Oberon']

MONGO_URL = os.environ.get('MONGO_URL')
if not MONGO_URL:
    MONGO_URL = "mongodb://*****:*****@app.route('/favicon.ico')
def favicon():
    ''' Favicon inspired by @angadsg. :) '''
    return flask.send_from_directory('public', 'favicon.ico')
示例#28
0
# import multi
#import logger
import flask
import flask_pymongo as fp
import os
import json
import bson as bo
import glob
#from bson.objectid import ObjectId

#app = Flask(__name__)
app = Flask(__name__, static_url_path='/static')

app.config['MONGO_DBNAME'] = 'art'  # name of database on mongo
app.config["MONGO_URI"] = "mongodb://127.0.0.1:27017/art"
mongo = fp.PyMongo(app)


@app.route("/accueil", methods=["GET", "POST"])
@app.route("/index", methods=["GET", "POST"])
@app.route("/", methods=["GET", "POST"])
def accueil():
    if request.method == 'POST':
        req = (request.form['motcle']).lower()
        print(req)
        res = mongo.db.articles.find({"motcle": req})
        err = str("Pas de résultat pour '" + str(request.form['motcle']) +
                  "'.")
        item_count = mongo.db.articles.count_documents({"motcle": req})

        #
示例#29
0
    textbooks.insert_many(file_data)

    # Load data into students collection
    students = database['students']
    with open(DB_PATH + 'students.json') as file:
        file_data = json.load(file)
    students.insert_many(file_data)

else:
    database = client['sproulclub']

app = flask.Flask(__name__)
app.config["DEBUG"] = True
app.config["MONGO_URI"] = "mongodb://*****:*****@app.route('/')
def home():
    return f"""<h1> sproul.club backend take home assignment</h1>
        <h2> How it works </h2>
        I set up my REST API to take requests at the `/api/`. Credentials such as student
        email and password are passed in through JSON, which are verified against the student and
        textbook collections in the MongoDB database. The endpoints were tested using Postman.
        <h2> API Endpoints </h2>
        <ul>
示例#30
0
    def test_it_requires_db_name_in_uri(self):
        uri = "mongodb://localhost:{}".format(self.port)

        with pytest.raises(ValueError):
            flask_pymongo.PyMongo(self.app, uri)