def _wrapped(*args, **kwargs): request.session = db.Session() if hasattr(request, 'user') and request.user: db.set_session_schema(session, request.user.organization.pg_schema) # close the session before we return the content content = next(*args, **kwargs) request.session.close() return content
def post_organization(): # TODO: if the requesting user already has an organization_id then raise an error # create a copy of the request data with only the columns data = { col: request.json[col] for col in request.json.keys() if col in org_mutable } # use an admin session for creating the organization and importing data # into the public schema admin_session = db.Session() try: organization = Organization(**data) owner = admin_session.merge(request.user) organization.owners.append(owner) owner.is_org_owner = True admin_session.add(organization) admin_session.commit() pg_schema = organization.pg_schema # once the organization has been created it should have it's own # postgresql schema if not pg_schema: bottle.abort(500, "Couldn't create the organization's schema") metadata = Model.metadata tables = metadata.sorted_tables for table in tables: table.schema = pg_schema metadata.create_all(admin_session.get_bind(), tables=tables) for table in tables: table.schema = None # import the default data db.set_session_schema(admin_session, pg_schema) base_path = os.path.join(os.path.join(*bauble.__path__), 'data') for sql_file in ['family.sql', 'genus.sql', 'habit.sql']: sql = open(os.path.join(base_path, sql_file)).read() admin_session.execute(sql) admin_session.commit() response.status = 201 return organization.json() finally: if admin_session: admin_session.close()
def post_organization(): # TODO: if the requesting user already has an organization_id then raise an error # create a copy of the request data with only the columns data = {col: request.json[col] for col in request.json.keys() if col in org_mutable} # use an admin session for creating the organization and importing data # into the public schema admin_session = db.Session() try: organization = Organization(**data) owner = admin_session.merge(request.user) organization.owners.append(owner) owner.is_org_owner = True admin_session.add(organization) admin_session.commit() pg_schema = organization.pg_schema # once the organization has been created it should have it's own # postgresql schema if not pg_schema: bottle.abort(500, "Couldn't create the organization's schema") metadata = Model.metadata tables = metadata.sorted_tables for table in tables: table.schema = pg_schema metadata.create_all(admin_session.get_bind(), tables=tables) for table in tables: table.schema = None # import the default data db.set_session_schema(admin_session, pg_schema) base_path = os.path.join(os.path.join(*bauble.__path__), 'data') for sql_file in ['family.sql', 'genus.sql', 'habit.sql']: sql = open(os.path.join(base_path, sql_file)).read() admin_session.execute(sql) admin_session.commit() response.status = 201 return organization.json() finally: if admin_session: admin_session.close()
def _wrapped(*args, **kwargs): auth = request.auth if not auth: bottle.abort(401, "No Authorization header.") email, password = auth request.session = db.Session() request.user = request.session.query(User).filter(sa.func.lower(User.email) == email.lower()).first() if (not request.user) or (not password): bottle.abort(401) # not authorized # basic_auth authorizes agains the users access token rather than the password # only /login uses the password if request.user.access_token == password and datetime.datetime.now() < request.user.access_token_expiration: tmp_session = db.Session() try: # update the last accessed column in a separate session so we # don't dirty our request session and inadvertantly commit something tmp_user = tmp_session.query(User).get(request.user.id) tmp_user.last_accesseed = datetime.datetime.now() tmp_session.commit() # make sure the request.user picks up the last_accessed # property in case its accessed request.session.expire(request.user) finally: tmp_session.close() else: bottle.abort(401) # if not request.user.is_sysadmin and not request.user.organization: # bottle.abort(401, "User does not belong to an organization") # should only get here if the user either has an organization or the user is a # sysadmin if request.user.organization: db.set_session_schema(request.session, request.user.organization.pg_schema) # make sure the session is always closed before we return try: content = next(*args, **kwargs) except: raise finally: request.session.close() return content
def from_csv(filemap, schema): """ Import a list of files files to tables where <filemap> is a dict of tablenames to file names. schema: the name of the schema for the tables in filemap """ session = db.Session() db.set_session_schema(session, schema) table_name = '' current_row = [] try: # import the files in order of their dependency sorted_tables = list(filter(lambda t: t.name in filemap, Model.metadata.sorted_tables)) for table in sorted_tables: table_name = table.name # mostly for error reporting print('importing into {} ...'.format(table_name)) if isinstance(filemap[table_name], str): import_file = open(filemap[table_name], newline='', encoding='utf-8') else: import_file = filemap[table_name] reader = csv.DictReader(import_file, quotechar=QUOTE_CHAR, quoting=QUOTE_STYLE) rows = [] for row in reader: current_row = row rows.append({key: value if value != "" else None for key, value in row.items()}) print('importing {} rows in to {}'.format(len(rows), table_name)) session.execute(table.insert(), rows) session.commit() except: print("Error importing into ", table_name) print('current_row: ', current_row) if len(rows) != 0: print(rows[len(rows) - 1]) session.rollback() raise finally: session.close()
def setup(request, organization, session): setup.organization = session.merge(organization) setup.user = setup.organization.owners[0] setup.session = session db.set_session_schema(session, setup.organization.pg_schema) setup.family = Family(family=api.get_random_name()) setup.genus = Genus(family=setup.family, genus=api.get_random_name()) setup.session.add_all([setup.family, setup.genus]) setup.session.commit() def cleanup(): setup.session.delete(setup.genus) setup.session.delete(setup.family) setup.session.commit() request.addfinalizer(cleanup) return setup
def test_import(organization, session): fields = ["family"] family_data = [("SomeFamily",), ("AnotherFamily",)] file_handle, filename = mkstemp() export_file = os.fdopen(file_handle, "w") csv_writer = csv.writer(export_file, fields) csv_writer.writerow(fields) for row in family_data: csv_writer.writerow(row) export_file.close() org = session.merge(organization) db.set_session_schema(session, org.pg_schema) from_csv({"family": filename}, org.pg_schema) families = session.query(Family) assert families.count() == 2 family1 = families.filter_by(family=family_data[0][0]).one() assert family1.family == family_data[0][0]
def invitation_setup(organization, session): invitation_setup.organization = session.merge(organization) invitation_setup.user = invitation_setup.organization.owners[0] invitation_setup.session = session db.set_session_schema(session, invitation_setup.organization.pg_schema) return invitation_setup
def setup(organization, session): setup.organization = session.merge(organization) setup.user = setup.organization.owners[0] setup.session = session db.set_session_schema(session, setup.organization.pg_schema) return setup