def setUp(self): from pymodm import connect from api.models import FileModel self.model = FileModel connect( "mongodb://*****:*****@db:27017/testdb?authSource=admin")
def interval_avg(): """This function determines the average heart rate after a specified time. This function connects to the Mongo database, and uses data from the database. This function uses a request.get to parse in the information sent from the client. The patient_id is determined from the request, and locates the user and associated data. The specified time is also determined from the request information. The function stores the heart rate data and corresponding time stamps into a list, as well as converting the given time stamp from UTC to unix form. This data is then parsed into another function called 'avg_hr_specified', that determines the average heart rate since the given time. :return: message :rtype: str """ from avg_hr_spec import avg_hr_specified import datetime connect("mongodb://*****:*****@ds157503.mlab.com:57503/bme590") r = request.get_json() user = Patient.objects.raw({"_id": r["patient_id"]}).first() time_since = r["heart_rate_data_since"] heart_rate_values = user.heart_rate_data new_time_since = datetime.datetime.fromisoformat(time_since).timestamp() return jsonify(avg_hr_specified(new_time_since, heart_rate_values))
def avg_hr(patient_id): """This function determines the average heart rate. This function connects to the Mongo database, and gets data from the database. The input patient_id is converted from a string to int, and used to locate the patient in question. This function creates an empty list of heart rates, and utilizes a for loop. The for loop appends all the heart rate values from the list of dictionaries that contains the heart rate values and time stamps. This heart rate list is then parsed into a function called 'average_hr' that calculates the average heart rate over all values. :param patient_id: user id :type patient_id: str :return: message :rtype: str """ from avg_heart_rate import average_hr connect("mongodb://*****:*****@ds157503.mlab.com:57503/bme590") patient_id = int(patient_id) user = Patient.objects.raw({"_id": patient_id}).first() heart_rates = [] for data in user.heart_rate_data: heart_rates.append(data["hr"]) return jsonify(str(float(average_hr(heart_rates))))
def initConnect(server='mongodb://*****:*****@ds139288.mlab.com:39288//', db='systix-sandbox', force_connect=False): global serverConnected if ((serverConnected is False) or force_connect): connect(server.rstrip('/') + '/' + db) serverConnected = True
def main(ctx, find_missing_annotations, find_duplicate_tools, find_invalid_annotations, annotations_yml_url, db_name, db_host, db_auth_database, db_user, db_password, db_port, slack_token): config = {} if (db_name is None) or (db_host is None) or (db_user is None): print_help(ctx, value=True) elif ( (find_missing_annotations is True) or (find_invalid_annotations is True)) and (annotations_yml_url is None): print_help(ctx, value=True) else: config['BIOCONT_DB_NAME'] = db_name config['MONGODB_HOST'] = db_host config['MONGO_PORT'] = db_port config['MONGODB_USER'] = db_user config['MONGODB_ADMIN_DB'] = db_auth_database config['MONGODB_PASS'] = db_password config['DATABASE_URI'] = get_database_uri(config) tools = [] if find_missing_annotations is True or find_duplicate_tools is True: db_uri = get_database_uri(config) connect(db_uri) tools = list(MongoTool.get_all_tools()) i = len(tools) print("Total tools: {}".format(i)) if find_missing_annotations is True: missing_annotations(annotations_yml_url, tools, slack_token) if find_duplicate_tools is True: duplicate_tools(tools, slack_token) if find_invalid_annotations is True: invalid_annotations(annotations_yml_url)
def add_patient(): """This function creates a new patient. This function connects to the Mongo database, and posts data to the database. It uses a try statement to validate the data being parsed into the function. If the data is not valid then a Validation Error is returned. The function also sets up a model for the data being parsed in and saves it to the Patient class. It returns a message to confirm the addition of the new patient to the database. :return: message :rtype: str """ connect("mongodb://*****:*****@ds157503.mlab.com:57503/bme590") r = request.get_json() # parses the POST request body as JSON try: validate_patient(r) except ValidationError as inst: return jsonify({"message": inst.exception}), 500 p = Patient( patient_id=r["patient_id"], attending_email=r["attending_email"], user_age=r["user_age"]) p.save() result = { "message": "Added patient {0} successfully to the patient list".format( request.json["patient_id"])} return jsonify(result)
def create_app(): instance_path = os.environ["FLASK_INSTANCE_PATH"] app = Flask('captaina', instance_path=instance_path, instance_relative_config=True) app.config.from_object('config') app.config.from_pyfile('config.py') csrf.init_app(app) fbcrypt.init_app(app) login_manager.init_app(app) from .utils import handle_needs_login, prefix_application_path login_manager.unauthorized_handler(handle_needs_login) modm.connect(app.config['MONGO_DATABASE_URI']) from .models import init_crypt_from_flask init_crypt_from_flask(app, login_manager) print("Connected to", app.config['MONGO_DATABASE_URI']) from .views import register_blueprints register_blueprints(app, csrf) from .cli import register_cli register_cli(app) register_jinja_filters(app) prefix_application_path(app, "/captaina") return app
def create_app(): app = Flask(__name__) app.register_blueprint(api1) config = ProdConfig if os.getenv('APP_IS_PROD') else DevConfig app.config.from_object(config) connect(app.config['MONGODB_URI'], connect=False) return app
def get_heart_rate(patient_id): """ Return all previous HR data Args: patient_id: ID of patient you want data for Returns: HRdata (json): json of all HR data Raises: ValidationError: User doesn't exist ValidationError: No HR data for user """ connect("mongodb://*****:*****@ds157818.mlab.com:57818/hr") a = int(patient_id) try: for user in User.objects.raw({"_id": a}): try: validate_get_heart_rate(user.heart_rate) logging.info("Add heart rate data %s", user.heart_rate) except ValidationError: return jsonify("User exists but no heart rate data") return jsonify(user.heart_rate) except UnboundLocalError: raise ValidationError("User does not exist") logging.warning("Tried to access user that does not exist")
def create_app(config_name="prod"): app = Flask(__name__) # Configure app app.config.from_object(CONFIG[config_name]()) # Connect to DB from pymodm import connect connect(app.config["DATABASE_URI"]) # Add blueprints from server.blueprint.authentication.blueprint import api as authentication_api from server.blueprint.chart.blueprint import api as chart_api from server.blueprint.event.blueprint import api as event_api from server.blueprint.interactivity.blueprint import api as interactivity_api from server.blueprint.slash_command.blueprint import api as slash_command_api app.register_blueprint(authentication_api) app.register_blueprint(interactivity_api) app.register_blueprint(slash_command_api) app.register_blueprint(event_api) app.register_blueprint(chart_api) return app
def calculate_avg_HR(patient_id): """ Average of HR data for all measurements Args: patient_id (int): id of specified patient Returns: ave (json): json with value of average HR Raises: ValidationError: user doesn't exist """ connect("mongodb://*****:*****@ds157818.mlab.com:57818/hr") a = int(patient_id) try: for user in User.objects.raw({"_id": a}): try: validate_get_heart_rate(user.heart_rate) logging.info("Average heart rate data") except ValidationError: pass mes = jsonify("User exists but no heart rate data") ave = mean(user.heart_rate) mes = jsonify(ave) except UnboundLocalError: mes = "User does not exist" # raise ValidationError("User does not exist") logging.warning("Tried to access user that does not exist") return mes
def find_reference(mongo_db_connect_url, permutation_id, find_wizard_id=False): def _find_mummy(permutation_id): if not find_wizard_id: return MDBHyperpipe.objects.raw({ 'permutation_id': PermutationTest.get_mother_permutation_id(permutation_id), 'computation_completed': True }).order_by([('computation_start_time', DESCENDING)]).first() else: return MDBHyperpipe.objects.raw({ 'wizard_object_id': permutation_id }).order_by([('computation_start_time', DESCENDING)]).first() try: # in case we haven't been connected try again connect(mongo_db_connect_url, alias="photon_core") mother_permutation = _find_mummy(permutation_id) except DoesNotExist: return None except ConnectionError: # in case we haven't been connected try again connect(mongo_db_connect_url, alias="photon_core") try: mother_permutation = _find_mummy(permutation_id) except DoesNotExist: return None return mother_permutation
def test_add_heart_rate(): """ Tests main.add_heart_rate function """ try: from pymodm import connect from main import add_heart_rate import pytest import models import datetime except ImportError as e: print("Necessary import failed: {}".format(e)) return d = datetime.datetime.now() connect("mongodb://*****:*****@test.test", age=0, age_units="year", heart_rate=[1], heart_rate_times=[d]) u.save() u = models.User.objects.raw({"_id": "*****@*****.**"}).first() ret = add_heart_rate("*****@*****.**", heart_rate=4, time=d) assert ret["user_email"] == "*****@*****.**" assert ret["user_age"] == 0 assert ret["age_units"] == "year" assert ret["heart_rates"] == [1, 4] assert len(ret["heart_rate_times"]) == 2
def do_scraping(datainicial, datafinal): """ Essa função verifica os formatos de data e realiza a busca, processamento e persistência das viagens. Parâmetros: datainicial -- String no formato 'dd/mm/YYYY' datafinal -- String no formato 'dd/mm/YYYY' """ if datainicial: try: datetime.strptime(datainicial, '%d/%m/%Y') if not datafinal: datafinal = datetime.now().strftime('%d/%m/%Y') else: datetime.strptime(datafinal, '%d/%m/%Y') connect(URL_MONGODB) res = request_viagens(datainicial, datafinal) viagens = get_viagens_from_request(res) print(str(len(viagens)) + ' Viagens salvas com sucesso') except ValueError: print('Data em formato inválido') return else: print('A data inicial é obrigatória')
def initDb(db_name): """Connect to database.""" print("Connecting to database...") connect("mongodb+srv://db_access:[email protected]/" "{}?retryWrites=true&w=majority".format(db_name)) print("Connected to database") return
def __new__(cls): if not hasattr(cls, 'init_done'): cls.instance = super(DBManager, cls).__new__(cls) connect(Config.c.mongodb.url + Config.c.mongodb.database_name) cls.instance.storage = GridFSStorage(GridFSBucket(_get_db())) cls.init_done = True return cls.instance
def test_avg_total_hr(): connect("mongodb://vcm-3502.vm.duke.edu:27017/heart_rate_app") email = "*****@*****.**" rates = [45, 65, 34, 68] for rate in rates: add_heart_rate(email, rate, datetime.datetime.now()) # Should be [66, 56, 45, 65, 34, 68] now if including previous test assert abs(avg_total_hr(email) - 55.67) < 0.1
def global_init(): global client, db connect("mongodb+srv://bme_547_final_project:bme_547_final_project" "@bme547finalproject-gjnxe.mongodb.net/test?retryWrites=true") client = MongoClient("mongodb+srv://bme_547_final_project:bme_" "547_final_project@bme547finalproject-gjnxe." "mongodb.net/test?retryWrites=true") db = client.test
def init_db(): print("Connecting to database...") # connect("mongodb+srv://db_access:[email protected]/" # "wc?retryWrites=true&w=majority") connect( "mongodb+srv://bme547student:xbzXZ35Y4&[email protected]/" "wc?retryWrites=true&w=majority") print("Connected to database")
def connect_to_mongodb(): """ a wrapper function used to connect to MongoDB :return: """ from pymodm import connect url = "mongodb://*****:*****@ds159993.mlab.com:59993/bme590" connect(url)
def __init__(self): with open("config.json", 'r') as f: config_info = json.load(f) db_user = config_info["mongo_user"] db_pass = config_info["mongo_pass"] url = "mongodb://{}:{}@ds041337.mlab.com:41337/heart_rate_sentinel".format( db_user, db_pass) connect(url)
def __init__(self, env_config): logging.info("Setting up database connection") try: db_url = self.uri_from_config(env_config) connect(db_url) except Exception as e: raise Exception(f"Unable to connect to database: {e}") else: logging.info("Database connection stablished")
def create_app(config_name): app = Flask(__name__) app.config.from_object(config_by_name[config_name]) connect(app.config['MONGO_URI']) # pymodm 사용 전에 반드시 호출 flask_bcrypt.init_app(app) return app
def init_db(): """ Initialized and connected to mongodb database. """ print("Connecting to database...") connect("mongodb+srv://tongfu:Fu19980311tong" "@images-yiprk.mongodb.net/images?retryWrites=true&w=majority") print("Connected to database.")
def __init__(self, **kwargs): with open("config.json", 'r') as f: config_info = json.load(f) db_user = config_info["mongo_user"] db_pass = config_info["mongo_pass"] url = "mongodb://{}:{}@ds133378.mlab.com:33378/" \ "image_processing".format(db_user, db_pass) connect(url)
def test_add_heart_rate(): connect("mongodb://vcm-3502.vm.duke.edu:27017/heart_rate_app") email = "*****@*****.**" test_user = models.User(email, 22, [], []) test_user.heart_rate.append(66) test_user.heart_rate_times.append(datetime.datetime.now()) test_user.save() add_heart_rate(email, 56, datetime.datetime.now()) updated_test = models.User.objects.raw({"_id": email}).first() assert updated_test.heart_rate[1] == 56 and updated_test.age == 22
def get_status(patient_id): """Determine whether or not a specified patient is tachycardic based on previously available heart rate Args: patient_id: Specified patient id Returns: d (Response instance): Whether or not the patient is tachycardic and the time stamp associated with the most recent heart rate measurement Excepts: Input Error: If specified user does not exist EmptyHrListError: If no heart rate measurements exist for specified user """ connect("mongodb://*****:*****@ds037768.mlab.com:37768/bme_590") r = int(patient_id) try: check_id_exists(r) except InputError as inst4: logging.warning("Specified a user that does not exist") return jsonify({"message": inst4.message}) try: check_list_empty(r) except EmptyHrListError as inst5: logging.warning("No heart rate measurements exist for specified user") return jsonify({"message": inst5.message}) (age, recent_hr, recent_time_str) = data_for_is_tach(r) is_tach = is_tachycardic(age, recent_hr) if is_tach == 1: d = { "message": "patient is tachycardic", "timestamp of recent hr measurement": recent_time_str } logging.info("successfully returned that patient is tachycardic") return jsonify(d) if is_tach == 0: d = { "message": "patient is tachycardic", "timestamp of recent hr measurement": recent_time_str } logging.info("successfully returned that patient is not tachycardic") return jsonify(d)
def test_interval_hr(): connect("mongodb://vcm-3502.vm.duke.edu:27017/heart_rate_app") email = "*****@*****.**" now = datetime.datetime.now() test_user = models.User(email, 22, [], []) test_user.heart_rate.append(66) test_user.heart_rate_times.append(now) test_user.save() time.sleep(0.500) then = datetime.datetime.now() add_heart_rate(email, 78, then) assert interval_hr(email, time2str(now)) == 72
async def deleteOldMessages(days, hours): print('Clean start') if days == None: days = 0 else: days = int(days) if hours == None: hours = 0 else: hours = int(hours) connect(os.environ.get('MONGODB_URL_MESSAGES'), alias='Messages') Message.objects.raw({"date": {"$lt": datetime.now() - timedelta(days=days, hours=hours)}}).delete()
def database_connection(): """Connect to database and configure logging Returns: None """ connect("mongodb+srv://dervil_dong_moavenzadeh_qi" ":[email protected]" "/test?retryWrites=true&w=majority") logging.basicConfig(filename="image_server.log", level=logging.INFO, filemode='w')
from pymodm import MongoModel, EmbeddedMongoModel, fields, connect # Establish a connection to the database. connect('mongodb://localhost:27017/blog') class User(MongoModel): # Make all these fields required, so that if we try to save a User instance # that lacks one of these fields, we'll get a ValidationError, which we can # catch and render as an error on a form. # # Use the email as the "primary key" (will be stored as `_id` in MongoDB). email = fields.EmailField(primary_key=True, required=True) handle = fields.CharField(required=True) # `password` here will be stored in plain text! We do this for simplicity of # the example, but this is not a good idea in general. A real authentication # system should only store hashed passwords, and queries for a matching # user/password will need to hash the password portion before of the query. password = fields.CharField(required=True) # This is an EmbeddedMongoModel, which means that it will be stored *inside* # another document (i.e. a Post), rather than getting its own collection. This # makes it very easy to retrieve all comments with a Post, but we might consider # breaking out Comment into its own top-level MongoModel if we were expecting to # have very many comments for every Post. class Comment(EmbeddedMongoModel): # For comments, we just want an email. We don't require signup like we do # for a Post, which has an 'author' field that is a ReferenceField to User. # Again, we make all fields required so that we get a ValidationError if we
import os import sys import pymodm # Agregamos al path la ruta de misture, para poder acceder a sus módulos. sys.path.append('/home/chilli-mint/Dropbox/MiStuRe/misture_core/MISTURE') #sys.path.append('/home/chilli-mint/Dropbox/MiStuRe/misture_core/') # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # La conexión a mongoDB siempre antes de invocar los modelos bajo pymodm. pymodm.connect('mongodb://localhost:27017/' + 'misture_mbbd_pfc3') # .save() quedara grabado una columna _cls al documento y el import del model # influye -p.e. _cls=pack.modelos.ClaseModel en lugar de ClaseModel- from entities.pymdbodm import * # En los view: from misture_web.pymdbodm import modclase1, modclase2,... # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'hfysac6n8!9vrgqe_rf+_4kd9^qd5izhb!tugk1uee6+!y%m8+' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True