def setupDB(self): self.connection = MongoClient(MONGO_HOST, MONGO_PORT) self.connection.drop_database(MONGO_DBNAME) if MONGO_USERNAME: self.connection[MONGO_DBNAME].add_user(MONGO_USERNAME, MONGO_PASSWORD) # seed result = self.connection[MONGO_DBNAME].people.\ insert_one({ 'name': "John" }) result = self.connection[MONGO_DBNAME].people.\ insert_one({ 'name': "Peter", "relations": [ { "relation_type": "family", "relation": result.inserted_id, } ], "rest_relations": [ { "relation_type": "family", "relation": result.inserted_id, } ] })
def initialize_db(app): db = MongoClient().salt db.init_app(app) # print("================init db================") # print(mongo.salt) # print("==================\n") return db
def is_db_server_up(mongo_url): client = MongoClient(mongo_url, serverSelectionTimeoutMS=100) try: client.server_info() return True except ServerSelectionTimeoutError: return False
def setupDB(self): self.connection = MongoClient(MONGO_HOST, MONGO_PORT) self.connection.drop_database(MONGO_DBNAME) if MONGO_USERNAME: self.connection[MONGO_DBNAME].add_user(MONGO_USERNAME, MONGO_PASSWORD) self.bulk_insert()
class ErpsyTest(unittest.TestCase): def setUp(self): self.app = create_app(config_name='testing') self.client = self.app.test_client self.part = {"name": "Polystyrene PWB", "description": "DC Block Type Reference 22320f", "part_number": "30758314"} self.mongo = MongoClient('localhost', 27017) db = self.mongo['test'] self.collection = db['parts'] self.collection.insert_one(self.part) def test_parts_response(self): res = self.client().get('/parts/') self.assertEqual(res.status_code, 200) def test_parts_format(self): res = self.client().get('/parts/') keys = set(json.loads(res.get_data(as_text=True))[ 0].keys()) self.assertEqual( keys, set(['part_number', 'description', 'name'])) def tearDown(self): self.collection.delete_many({}) self.mongo.close()
def get_db_version(mongo_url): """ Return the mongo db version :param mongo_url: Which mongo to check. :return: version as a tuple (e.g. `(u'4', u'0', u'8')`) """ client = MongoClient(mongo_url, serverSelectionTimeoutMS=100) server_version = tuple(client.server_info()["version"].split(".")) return server_version
def setUp(self): self.app = create_app(config_name='testing') self.client = self.app.test_client self.part = {"name": "Polystyrene PWB", "description": "DC Block Type Reference 22320f", "part_number": "30758314"} self.mongo = MongoClient('localhost', 27017) db = self.mongo['test'] self.collection = db['parts'] self.collection.insert_one(self.part)
def addstate(): try: card=random.randint(55555,99999) balance=random.randint(1000,8000) conn = MongoClient('localhost',27017) db = conn.admin collection = db.bankdetails status=collection.insert_one({"name":"stu","card no": card,"balance":balance}) conn.close() return "successful" except: return "unsuccessful"
def setUp(self): # setup a test client app.app.testing = True self.app = app.app.test_client() # configure access rights to the mongodb testdatabase app.app.config['MONGO_DBNAME'] = "testdatabase" app.app.config[ "MONGO_URI"] = 'mongodb://*****:*****@ds237770.mlab.com:37770/testdatabase' # configure connection to the testdatabase app.client = MongoClient( 'mongodb://*****:*****@ds237770.mlab.com:37770/testdatabase') app.db = app.client['testdatabase'] app.db.drop_collection('customers') # create a test collection called 'customers' app.db.create_collection('customers') customers = app.db.get_collection('customers') # insert test customers customers.insert_one( insertCustomer('12345', 'Krueger', 'Freddy', 63, 2000, '9:30')) customers.insert_one( insertCustomer('56789', 'Vorhees', 'Jason', 45, 9000, '12:00'))
def mongo_login(): email = request.form['email'] password = request.form['password'] print('email: %s, password: %s' % (email, password)) try: client = MongoClient() db = client.test_db user = db.users.find_one({'email': email.lower()}) if user and user['password'] == password: result = { 'resultCode': '1', 'email': user['email'], 'name': user['name'], 'surname': user['surname'] } else: result = { 'resultCode': '0', } print result return json.dumps(result) except Exception as e: return "error: %s" % (e)
def stats(): ''' Statistics page This page initially writes to a json file the entire collection, it then calls the actual page to be rendered. The ObjectID is excluded from this json file. ''' title = "Statistics | RecipieDB" client = MongoClient() collection = mongo.db.recipies cursor = collection.find({}, {"_id": 0}) file = open("static/data/collection.json", "w") file.write('[') qnt_cursor = 0 for document in cursor: qnt_cursor += 1 num_max = cursor.count() if (num_max == 1): file.write(json.dumps(document)) elif (num_max >= 1 and qnt_cursor <= num_max - 1): file.write(json.dumps(document)) file.write(',') elif (qnt_cursor == num_max): file.write(json.dumps(document)) file.write(']') file.close() return render_template('stats.html', title=title)
def open(self): try: self.client = MongoClient(MONGO_ADDR, MONGO_PORT) self.mongo = self.client[self.db_name] except pymongo.errors.ConnectionFailure, conn_exception: raise "Could not connect to MongoDB: {}".format(conn_exception)
def delete_from_all_collections_by_user_id(self, db_name: str, user_id: str) -> dict: print('In Method: delete_by_user_id()') client = MongoClient(db_config.connection_string) db = client.get_database(db_name) try: collection_names = [ collection for collection in db.collection_names() if not collection.startswith('system.') ] for collection_name in collection_names: db[collection_name].delete_many({'user_id': user_id}) except Exception as e: print('Exception Thrown:') print(e) client.close() return {'success': False} client.close() return {'success': True}
def addstate(): #try: #args = request.args #strng = base64.b64decode(args['val']).decode('utf-8') #obj = request.get_json() card = random.randint(55555, 99999) balance = random.randint(1000, 8000) conn = MongoClient('localhost', 27017) db = conn.admin collection = db.bankdetails status = collection.insert_one({ "name": "stu", "card no": card, "balance": balance }) conn.close() #print(obj) return "successful"
class TestMultiMongo(TestBase): def setUp(self): super(TestMultiMongo, self).setUp() self.setupDB2() schema = { 'author': { 'type': 'string' }, 'title': { 'type': 'string' }, } settings = {'schema': schema, 'mongo_prefix': 'MONGO1'} self.app.register_resource('works', settings) def tearDown(self): super(TestMultiMongo, self).tearDown() self.dropDB2() def setupDB2(self): self.connection = MongoClient() self.connection.drop_database(MONGO1_DBNAME) self.connection[MONGO1_DBNAME].add_user(MONGO1_USERNAME, MONGO1_PASSWORD) self.bulk_insert2() def dropDB2(self): self.connection = MongoClient() self.connection.drop_database(MONGO1_DBNAME) self.connection.close() def bulk_insert2(self): _db = self.connection[MONGO1_DBNAME] works = self.random_works(self.known_resource_count) _db.works.insert(works) self.work = _db.works.find_one() self.connection.close() def random_works(self, num): works = [] for i in range(num): dt = datetime.now() work = { 'author': self.random_string(20), 'title': self.random_string(30), eve.LAST_UPDATED: dt, eve.DATE_CREATED: dt, } works.append(work) return works
def get_product_by_id(product_id): """ Method for finding product by id :param product_id: :return: """ mongo = MongoClient(Config.MONGO_URI) if ObjectId().is_valid(product_id) is False: return bad_request(t['invalid_id']) db_operations = mongo.db.product product = db_operations.find_one_or_404({'_id': ObjectId(product_id)}) response_product = Product().from_dict(product).to_dict() return jsonify(response_product)
def main(ip='*', ip_db='*'): global url, collection url = "tcp://{}:9002".format(ip) app.config['MONGO_DBNAME'] = 'users' app.config['MONGO_URI'] = 'mongodb://' + ip_db + ':27017/users' dbconnect = False while not dbconnect: conn = MongoClient('mongodb://' + ip_db + ':27017/', serverSelectionTimeoutMS=5000, connectTimeoutMS=200000) try: conn.server_info() # force connection # Database db = conn.users # Created or Switched to collection names: my_gfg_collection collection = db.user_collection dbconnect = True except ServerSelectionTimeoutError as e: if DEBUG: print(e) print("Could not connect to MongoDB", flush=True) app.run(debug=True, host='0.0.0.0', port='5002')
def mongo_get_users(): try: client = MongoClient() db = client.test_db users = db.users result = [] for user in users.find(): result.append({ 'email': user['email'], 'password': user['password'], 'name': user['name'], 'surname': user['surname'] }) return json.dumps(result) except Exception as e: return "error: %s" % (e)
def __init__(self, app): uri = ( "mongodb://{user}:{password}@{host}:{port}/{db}?ssl=false").format( user=mongo_user, password=mongo_pass, host=mongo_host, port=mongo_port, db=mongo_dB) app.config["MONGO_URI"] = uri app.config["MONGO_DBNAME"] = "desafioluiza" mongo = PyMongo(app) client = MongoClient(uri) self.db = client.desafioluiza
def mongo_sign_up(): try: email = request.form['email'] password = request.form['password'] name = request.form['name'] surname = request.form['surname'] client = MongoClient() db = client.test_db db.users.insert_one({ "email": email.lower(), "password": password, "name": name, "surname": surname }) return "gud" except Exception as e: return "error: %s" % (e)
def get_products(): """ Method for get product list with pagination by params: dict and/or title: str :return: """ mongo = MongoClient(Config.MONGO_URI) page = request.args.get('page', DEFAULT_PAGE, type=int) per_page = min( request.args.get('per_page', PER_PAGE_DEFAULT, type=int), PER_PAGE_MAX) db_operations = mongo.db.product data = { k: v for k, v in request.args.items() if k not in ['page', 'per_page'] } query_data = Product.get_query_from_data(data) query = db_operations.find result = Product().to_collection_dict(query, query_data, page, per_page) return jsonify(result)
def create_product(): """ Method for product creation by request :return: """ mongo = MongoClient(Config.MONGO_URI) db_operations = mongo.db.product data = request.get_json(force=True) or {} if 'title' not in data or 'description' not in data or 'params' not in data: return bad_request(t['empty_field']) new_product = Product() if Product.params_is_valid(data): new_product.save_to_db(data, db_operations) response = jsonify(new_product.to_dict()) response.status_code = 201 response.headers['Location'] = url_for('api.get_product_by_id', product_id=new_product._id) return response else: return bad_request(t['invalid_value'])
class TestBase(unittest.TestCase): def setUp(self, settings=None): self.this_directory = os.path.dirname(os.path.realpath(__file__)) if settings is None: settings = os.path.join(self.this_directory, 'test_settings.py') self.setupDB() self.settings = settings self.app = eve.Eve(settings=self.settings) self.app.register_blueprint(eve_swagger.swagger) self.app.config['SWAGGER_INFO'] = { 'title': 'Test eve-swagger', 'version': '0.0.1' } self.test_client = self.app.test_client() self.domain = self.app.config['DOMAIN'] self.swagger_doc = self.get_swagger_doc() def tearDown(self): del self.app self.dropDB() def setupDB(self): self.connection = MongoClient(MONGO_HOST, MONGO_PORT) self.connection.drop_database(MONGO_DBNAME) if MONGO_USERNAME: self.connection[MONGO_DBNAME].add_user(MONGO_USERNAME, MONGO_PASSWORD) def dropDB(self): self.connection = MongoClient(MONGO_HOST, MONGO_PORT) self.connection.drop_database(MONGO_DBNAME) self.connection.close() def get_swagger_doc(self): r = self.test_client.get('/api-docs') return self.parse_response(r) def parse_response(self, r): try: v = json.loads(r.get_data().decode('utf-8')) except ValueError: v = None return v
class settingsTestCase(TestMinimal): def setUp(self): return super().setUp(settings_file = './settings.py') def dropDB(self): self.connection = MongoClient(MONGO_HOST,MONGO_PORT) self.connection.drop_database(MONGO_DBNAME) self.connection.close() def setupDB(self): self.connection = MongoClient(MONGO_HOST,MONGO_PORT) self.connection.drop_database(MONGO_DBNAME) def testGet(self): return_json,return_code = self.get(url) self.assert200(return_code) def testPost(self): return_json, return_code = self.post(url, {"cjv": 0.1231231}) self.assertFalse(self.domain) self.assertFalse(return_json)
class TestBase(unittest.TestCase): def setUp(self, settings=None): self.this_directory = os.path.dirname(os.path.realpath(__file__)) if settings is None: settings = os.path.join(self.this_directory, "test_settings.py") self.setupDB() self.settings = settings self.app = eve.Eve(settings=self.settings) self.app.register_blueprint(eve_swagger.swagger) self.app.config["SWAGGER_INFO"] = {"title": "Test eve-swagger", "version": "0.0.1"} self.test_client = self.app.test_client() self.domain = self.app.config["DOMAIN"] self.swagger_doc = self.get_swagger_doc() def tearDown(self): del self.app self.dropDB() def setupDB(self): self.connection = MongoClient(MONGO_HOST, MONGO_PORT) self.connection.drop_database(MONGO_DBNAME) if MONGO_USERNAME: self.connection[MONGO_DBNAME].add_user(MONGO_USERNAME, MONGO_PASSWORD) def dropDB(self): self.connection = MongoClient(MONGO_HOST, MONGO_PORT) self.connection.drop_database(MONGO_DBNAME) self.connection.close() def get_swagger_doc(self): r = self.test_client.get("/api-docs") return self.parse_response(r) def parse_response(self, r): try: v = json.loads(r.get_data().decode("utf-8")) except ValueError: v = None return v
from flask import Flask from flask import render_template from flask_pymongo import PyMongo, MongoClient import csv #Defines the Flask app and the MongoDB parameters. #Additionally, allows for connection to stanford path. app = Flask(__name__) app.config[ "MONGO_URI"] = "mongodb+srv://scarlettexperiment-1pxrx.mongodb.net/test" mongo = PyMongo(app) app.config["CLIENT"] = MongoClient( "mongodb+srv://scarlettexperiment-1pxrx.mongodb.net/test", username="******", password="******", authSource="admin") local_corenlp_path = r'/Users/Masayuki/stanford-corenlp-full-2018-10-05' def poemAnalysis(poemObject): #https://stackoverflow.com/questions/32879532/stanford-nlp-for-python #Connect to the Stanford NLP server. Note that in order to run this code, #The Stanford NLP server must be run. The local_corenlp_path above must be #changed, and the instructions must be followed from the link above. nlp = StanfordCoreNLP('http://localhost:9000') #Set the analysis to be of sentiment. pros = {'annotators': 'sentiment', 'outputFormat': 'json'} poem = poemObject.get('poems')[0] res = nlp.annotate(poem, properties=pros)
def init(uri=None, db="trackeame"): app = Flask(__name__) app.config["MONGO_URI"] = os.environ.get("MONGOLAB_URI", uri) mongo = MongoClient(app.config["MONGO_URI"]) app.mongo = mongo app.database = mongo[db] @app.route("/") def root_page(): return render_template("index.html") @app.route("/api/users") def get_users(): output = [] users = app.database.users.find() for user in users: output.append({"name": user["name"], "lastname": user["lastname"], "sex": user["sex"]}) return jsonify(output) @app.route("/api/users", methods=['POST']) def add_user(): users = app.database.users name = request.json["name"] lastname = request.json["lastname"] sex = request.json["sex"] id = users.insert({"name": name, "lastname": lastname, "sex": sex}) user = users.find_one({'_id': id}) result = {"name": user["name"], "lastname": user["lastname"], "sex": user["sex"]} return jsonify(result) @app.route("/api/locations", methods=['DELETE']) def clear_locations(): locations = app.database.locations try: locations.delete_many({}) except KeyError: abort(403) result = {"ok": 1} return jsonify(result) @app.route("/api/locations", methods=['POST']) def add_locations(): locations = app.database.locations cuadrantes = {"N": 1, "S":-1, "W":-1, "E": 1} try: posiciones = request.json["posiciones"] posiciones_parseadas = [] ultima_posicion = None for posicion in posiciones.split("\n"): if posicion is not '': nueva_posicion = {} print(posicion) try: tipo, hora_gcm, validez, latitud, polo, longitud, hemisferio, dato1, dato2, fecha, dato3, dato4, dato5 = posicion.split(",") if latitud is not '' and longitud is not '': tiempo_hora = datetime( int(fecha[4:6]), int(fecha[2:4]), int(fecha[0:2]), int(hora_gcm[0:2]), int(hora_gcm[2:4]), int(hora_gcm[4:6])) nueva_posicion["timestamp"] = datetime.timestamp(tiempo_hora) nueva_posicion["latitud"] = (int(latitud[0:2]) + (float(latitud[2:9]) / 60)) * cuadrantes[polo] nueva_posicion["longitud"] = (int(longitud[0:3]) + (float(longitud[3:10]) / 60)) * cuadrantes[hemisferio] nueva_posicion["tiempo_de_parada"] = 0 if tipo == "$PARADA" and ultima_posicion is not None: ultima_posicion["tiempo_de_parada"] = nueva_posicion["timestamp"] - ultima_posicion["timestamp"] posiciones_parseadas.append(nueva_posicion) ultima_posicion = nueva_posicion except Exception: pass if len(posiciones_parseadas) > 0: locations.insert_many(posiciones_parseadas) except KeyError: abort(403) resultado = {"ok": 1} return jsonify(resultado) @app.route("/api/locations") def get_locations(): output = [] locations = app.database.locations.find() for location in locations: output.append({"posicion": { "timestamp": location["timestamp"], "latitud": location["latitud"], "longitud": location["longitud"], "tiempoDeParada": location["tiempo_de_parada"] }}) return jsonify(output) return app
from flask import Flask, jsonify, send_file, request, render_template from flask_pymongo import MongoClient from api.apiFunctions import getMonthlySleepDeclarations, getMonthlyNutritions, findUser, signIn, signUp, createNutrition, createSleepDeclaration, deleteNutrition, editSleepHours, updateUserInfo app = Flask(__name__) #DATABASE client = MongoClient('mongodb+srv://redus:[email protected]/dnd?retryWrites=true&w=majority') db = client['dnd'] #MODELS User = db['users'] Nutirtion = db['nutritions'] SleepDeclaration = db['sleepDeclarations'] #FRONT END STUFF @app.route('/nasafont') def nasaFontMethod(): return send_file('./font/nasalization-rg.woff') @app.route('/homebackground') def homeBackgroundMethod(): return send_file('./images/background.png') @app.route('/homemidground') def homeMidgroundMethod(): return send_file('./images/midground.png') @app.route('/homeforeground') def homeForegroundMethod(): return send_file('./images/foreground.png')
ENVIRONMENT_DEBUG = os.environ.get("APP2_DEBUG", True) ENVIRONMENT_PORT = os.environ.get("APP2_PORT", 8282) REDIS_PORT = os.environ.get("REDIS_PORT", 6379) REDIS_CHANNEL = os.environ.get("REDIS_CHANNEL", 'mongo') REDIS_CHANNEL_NOTIFY = os.environ.get("REDIS_CHANNEL_NOTIFY", 'notify') application = Flask(__name__) """ MongoDB setup """ # application.config["MONGO_URI"] = 'mongodb://' + os.environ['MONGODB_USERNAME'] + ':' + os.environ['MONGODB_PASSWORD'] + '@' + os.environ['MONGODB_HOSTNAME'] + ':27017/' + os.environ['MONGODB_DATABASE'] # mongo = PyMongo(application) # db = mongo.db client = MongoClient(host=os.environ['MONGODB_HOSTNAME'], port=27017, username=os.environ['MONGODB_USERNAME'], password=os.environ['MONGODB_PASSWORD'], authSource="admin") db = client['flaskdb'] collection = db["data"] """ Redis setup """ redis = redis.StrictRedis(host="redis", port=REDIS_PORT, db=0) pubsub = redis.pubsub(ignore_subscribe_messages=True) channel = REDIS_CHANNEL channel_notify = REDIS_CHANNEL_NOTIFY global_json = None
"""Pull down music data""" import datetime import billboard from flask_pymongo import MongoClient FANTASY_LIFE_START_DATE = datetime.date(year=2016, month=8, day=1) client = MongoClient() db = client.fantasy print("runnning") def create_music_db(): """Makes a new database for the nba""" players = db.players musicians = db.musicians musicians.drop() singers = ['Bruno Mars', 'Ed Sheeran', 'Kendrick Lamar', 'Future', 'Lil Uzi Vert',\ 'James Arthur', 'Julia Michaels', 'Imagine Dragons', 'Sam Hunt', 'Taylor Swift',\ 'Katy Perry', 'Justin Bieber'] cursor = players.find() for singer, user in zip(singers, cursor): _ = musicians.insert({ "associated_player_id": user['_id'], "artist": singer })
from flask import Flask, render_template, redirect ,request,url_for from wtforms import StringField, BooleanField from wtforms.validators import Length, InputRequired from flask_wtf import FlaskForm from bson import ObjectId from flask_pymongo import MongoClient from flask_bootstrap import Bootstrap # creates a Flask application, named app app = Flask(__name__) Bootstrap(app) #calling client client = MongoClient('mongodb://127.0.0.1:27017') #database name db = client.mydatabase todos = db.todo # for securing our content app.config['SECRET_KEY'] = 'this_is_a_secret' class Todo(FlaskForm): title = StringField("Title", validators=[InputRequired(), Length(max=100)]) done = BooleanField("Done") '''def validate_name(form, field): if len(field.data) > 50: raise ValidationError('Name must be less than 50 characters') ''' '''todos = [ { 'Title': 'Do TOC Assignment',
def dropDB(self): self.connection = MongoClient(MONGO_HOST, MONGO_PORT) self.connection.drop_database(MONGO_DBNAME) self.connection.close()
def setupDB(self): self.connection = MongoClient(MONGO_HOST, MONGO_PORT) self.connection.drop_database(MONGO_DBNAME) if MONGO_USERNAME: self.connection[MONGO_DBNAME].add_user(MONGO_USERNAME, MONGO_PASSWORD)