本文整理汇总了Python中database.DBSession.add方法的典型用法代码示例。如果您正苦于以下问题:Python DBSession.add方法的具体用法?Python DBSession.add怎么用?Python DBSession.add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类database.DBSession
的用法示例。
在下文中一共展示了DBSession.add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: user_create
# 需要导入模块: from database import DBSession [as 别名]
# 或者: from database.DBSession import add [as 别名]
def user_create():
if not can_create_user(current_user):
abort(401)
form = UserForm(request.form)
# Need to add the Required flag back as it is globally removed during user_edit()
add_validator(form.password, Required)
fill_user_privileges(form.privilege.choices)
if request.method == 'POST' and form.validate():
db_session = DBSession()
user = get_user(db_session, form.username.data)
if user is not None:
return render_template('user/edit.html', form=form, duplicate_error=True)
user = User(
username=form.username.data,
password=form.password.data,
privilege=form.privilege.data,
fullname=form.fullname.data,
email=form.email.data)
user.preferences.append(Preferences())
db_session.add(user)
db_session.commit()
return redirect(url_for('home'))
else:
# Default to Active
form.active.data = True
return render_template('user/edit.html', form=form)
示例2: software_profile_create
# 需要导入模块: from database import DBSession [as 别名]
# 或者: from database.DBSession import add [as 别名]
def software_profile_create():
# if not can_create_user(current_user):
# abort(401)
db_session = DBSession()
form = SoftwareProfileForm(request.form)
server_dialog_form = ServerDialogForm(request.form)
fill_servers(server_dialog_form.server_dialog_server.choices, get_server_list(db_session), False)
if request.method == 'POST' and form.validate():
software_profile = get_software_profile(db_session, form.profile_name.data)
if software_profile is not None:
return render_template('conformance/profile_edit.html',
form=form, system_option=SystemOption.get(db_session), duplicate_error=True)
software_profile = SoftwareProfile(
name=form.profile_name.data,
description=form.description.data,
packages=','.join([l for l in form.software_packages.data.splitlines() if l]),
created_by=current_user.username)
db_session.add(software_profile)
db_session.commit()
return redirect(url_for('conformance.home'))
else:
return render_template('conformance/profile_edit.html',
form=form, server_dialog_form=server_dialog_form,
system_option=SystemOption.get(db_session))
示例3: command_profile_create
# 需要导入模块: from database import DBSession [as 别名]
# 或者: from database.DBSession import add [as 别名]
def command_profile_create():
db_session = DBSession()
form = CustomCommandProfileForm(request.form)
if request.method == 'POST' and form.validate():
command_profile = get_command_profile(db_session, form.profile_name.data)
if command_profile is not None:
return render_template('custom_command/command_profile_edit.html',
form=form, duplicate_error=True)
command_profile = CustomCommandProfile(
profile_name=form.profile_name.data,
command_list=','.join([l for l in form.command_list.data.splitlines() if l]),
created_by=current_user.username
)
db_session.add(command_profile)
db_session.commit()
return redirect(url_for('custom_command.home'))
else:
return render_template('custom_command/command_profile_edit.html',
form=form)
示例4: get_smu_info_from_cco
# 需要导入模块: from database import DBSession [as 别名]
# 或者: from database.DBSession import add [as 别名]
def get_smu_info_from_cco(self, platform, release):
save_to_db = True
db_session = DBSession()
platform_release = platform + '_' + release
try:
self.smu_meta = SMUMeta(platform_release=platform_release)
# Load data from the SMU XML file
self.load()
# This can happen if the given platform and release is not valid.
# The load() method calls get_smu_info_from_db and failed.
if not self.is_valid:
logger.error('get_smu_info_from_cco() hit exception, platform_release=' + platform_release)
return
db_smu_meta = db_session.query(SMUMeta).filter(SMUMeta.platform_release == platform_release).first()
if db_smu_meta:
if db_smu_meta.created_time == self.smu_meta.created_time:
save_to_db = False
else:
# Delete the existing smu_meta and smu_info for this platform and release
db_session.delete(db_smu_meta)
db_session.commit()
if save_to_db:
db_session.add(self.smu_meta)
else:
db_smu_meta.retrieval_time = datetime.datetime.utcnow()
db_session.commit()
except Exception:
logger.exception('get_smu_info_from_cco() hit exception, platform_release=' + platform_release)
示例5: api_create_tar_job
# 需要导入模块: from database import DBSession [as 别名]
# 或者: from database.DBSession import add [as 别名]
def api_create_tar_job():
db_session = DBSession()
form = CreateTarForm(request.form)
server_id = request.args.get('server')
server_directory = request.args.get('server_directory')
source_tars = request.args.getlist('source_tars[]')
contents = request.args.getlist('tar_contents[]')
additional_packages = request.args.getlist('additional_packages[]')
new_tar_name = request.args.get('new_tar_name').strip('.tar')
create_tar_job = CreateTarJob(
server_id = server_id,
server_directory = server_directory,
source_tars = (',').join(source_tars),
contents = (',').join(contents),
additional_packages = (',').join(additional_packages),
new_tar_name = new_tar_name,
created_by = current_user.username,
status = 'Job Submitted.')
db_session.add(create_tar_job)
db_session.commit()
job_id = create_tar_job.id
return jsonify({'status': 'OK', 'job_id': job_id})
示例6: refresh_all
# 需要导入模块: from database import DBSession [as 别名]
# 或者: from database.DBSession import add [as 别名]
def refresh_all(cls):
"""
Retrieves all the catalog data and SMU XML file data and updates the database.
"""
db_session = DBSession()
catalog = SMUInfoLoader.get_catalog_from_cco()
if len(catalog) > 0:
system_option = SystemOption.get(db_session)
try:
# Remove all rows first
db_session.query(CCOCatalog).delete()
for platform in catalog:
releases = catalog[platform]
for release in releases:
cco_catalog = CCOCatalog(platform=platform,release=release)
db_session.add(cco_catalog)
SMUInfoLoader(platform, release)
system_option.cco_lookup_time = datetime.datetime.utcnow()
db_session.commit()
return True
except Exception:
logger.exception('refresh_all() hit exception')
db_session.rollback()
return False
示例7: init_encrypt
# 需要导入模块: from database import DBSession [as 别名]
# 或者: from database.DBSession import add [as 别名]
def init_encrypt():
global encrypt_dict
db_session = DBSession()
if db_session.query(Encrypt).count() == 0:
db_session.add(Encrypt())
db_session.commit()
encrypt_dict = dict(Encrypt.get(db_session).__dict__)
示例8: init_sys_time
# 需要导入模块: from database import DBSession [as 别名]
# 或者: from database.DBSession import add [as 别名]
def init_sys_time():
db_session = DBSession()
if db_session.query(System).count() == 0:
db_session.add(System())
db_session.commit()
else:
system = db_session.query(System).first()
system.start_time = datetime.datetime.utcnow()
db_session.commit()
示例9: convert_config_file
# 需要导入模块: from database import DBSession [as 别名]
# 或者: from database.DBSession import add [as 别名]
def convert_config_file():
filename = request.args.get('filename', '', type=str)
filename = secure_filename(filename)
config_conversion_path = get_config_conversion_path()
db_session = DBSession()
convert_config_job = ConvertConfigJob(file_path=os.path.join(config_conversion_path, filename),
status='Preparing the conversion')
db_session.add(convert_config_job)
db_session.commit()
job_id = convert_config_job.id
return jsonify({'status': 'OK', 'job_id': job_id})
示例10: emit
# 需要导入模块: from database import DBSession [as 别名]
# 或者: from database.DBSession import add [as 别名]
def emit(self, record):
trace = traceback.format_exc() if record.__dict__['exc_info'] else None
args = record.__dict__['args']
msg = record.__dict__['msg']
if len(args) >= 1:
msg = msg % args
log = Log(
level=record.__dict__['levelname'],
trace=trace,
msg=msg,
created_time=datetime.datetime.utcnow())
db_session = DBSession()
db_session.add(log)
db_session.commit()
示例11: get_smu_info_from_cco
# 需要导入模块: from database import DBSession [as 别名]
# 或者: from database.DBSession import add [as 别名]
def get_smu_info_from_cco(self, platform, release):
same_as_db = False
db_session = DBSession()
platform_release = platform + '_' + release
try:
self.smu_meta = SMUMeta(platform_release=platform_release)
# Load data from the SMU XML file
self.load()
# This can happen if the given platform and release is not valid.
# The load method calls get_smu_info_from_db and failed.
if self.smu_meta is None:
return
db_smu_meta = db_session.query(SMUMeta).filter(SMUMeta.platform_release == platform + '_' + release).first()
if db_smu_meta is not None:
if db_smu_meta.created_time == self.smu_meta.created_time:
same_as_db = True
else:
# Delete the existing smu_meta and smu_info for this platform and release
db_session.delete(db_smu_meta)
if not same_as_db:
db_session.add(self.smu_meta)
else:
db_smu_meta.retrieval_time = datetime.datetime.utcnow()
# Use Flush to detect concurrent saving condition. It is
# possible that another process may perform the same save.
# If this happens, Duplicate Key may result.
db_session.flush()
db_session.commit()
except IntegrityError:
db_session.rollback()
except Exception:
db_session.rollback()
logger.exception('get_smu_info_from_cco() hit exception')
示例12: api_create_software_profile
# 需要导入模块: from database import DBSession [as 别名]
# 或者: from database.DBSession import add [as 别名]
def api_create_software_profile():
profile_name = request.form['profile_name']
description = request.form['description']
software_packages = request.form['software_packages']
db_session = DBSession()
software_profile = get_software_profile(db_session, profile_name)
if software_profile is not None:
return jsonify({'status': 'Software profile "' + profile_name +
'" already exists. Use a different name instead.'})
software_profile = SoftwareProfile(
name=profile_name,
description=description,
packages=','.join([l for l in software_packages.splitlines() if l]),
created_by=current_user.username)
db_session.add(software_profile)
db_session.commit()
return jsonify({'status': 'OK'})
示例13: api_import_hosts
# 需要导入模块: from database import DBSession [as 别名]
# 或者: from database.DBSession import add [as 别名]
def api_import_hosts():
region_id = int(request.form['region_id'])
jump_host_id = int(request.form['jump_host_id'])
software_profile_id = int(request.form['software_profile_id'])
data_list = request.form['data_list']
db_session = DBSession()
if region_id == -1:
return jsonify({'status': 'Region has not been specified.'})
if region_id > 0:
region = get_region_by_id(db_session, region_id)
if region is None:
return jsonify({'status': 'Region is no longer exists in the database.'})
if jump_host_id > 0:
jump_host = get_jump_host_by_id(db_session, jump_host_id)
if jump_host is None:
return jsonify({'status': 'Jump Host is no longer exists in the database.'})
if software_profile_id > 0:
software_profile = get_software_profile_by_id(db_session, software_profile_id)
if software_profile is None:
return jsonify({'status': 'Software Profile is no longer exists in the database.'})
error = []
reader = csv.reader(data_list.splitlines(), delimiter=',')
header_row = next(reader)
# header_row: ['hostname', 'location', 'roles', 'ip', 'username', 'password', 'connection', 'port']
# Check mandatory data fields
if HEADER_FIELD_HOSTNAME not in header_row:
error.append('"hostname" is missing in the header.')
if HEADER_FIELD_IP not in header_row:
error.append('"ip" is missing in the header.')
if HEADER_FIELD_CONNECTION not in header_row:
error.append('"connection" is missing in the header.')
for header_field in header_row:
if header_field not in HEADER_FIELDS:
error.append('"' + header_field + '" is not a correct header field.')
if error:
return jsonify({'status': '\n'.join(error)})
error = []
data_list = list(reader)
region_dict = get_region_name_to_id_dict(db_session)
# Check if each row has the same number of data fields as the header
row = 2
for row_data in data_list:
if len(row_data) != len(header_row):
error.append('line {} has wrong number of data fields - {}.'.format(row, row_data))
else:
hostname = get_acceptable_string(get_row_data(row_data, header_row, HEADER_FIELD_HOSTNAME))
if is_empty(hostname):
error.append('line {} has invalid hostname - {}.'.format(row, row_data))
# Validate the connection type
connection_type = get_row_data(row_data, header_row, HEADER_FIELD_CONNECTION)
if is_empty(connection_type) or connection_type not in [ConnectionType.TELNET, ConnectionType.SSH]:
error.append('line {} has a wrong connection type (should either be "telnet" or "ssh") - {}.'.format(row, row_data))
region_name = get_acceptable_string(get_row_data(row_data, header_row, HEADER_FIELD_REGION))
if region_name is not None:
# No blank region is allowed
if len(region_name) == 0:
error.append('line {} has no region specified - {}.'.format(row, row_data))
else:
if region_name not in region_dict.keys():
# Create the new region
try:
region = Region(name=region_name, created_by=current_user.username)
db_session.add(region)
db_session.commit()
# Add to region dictionary for caching purpose.
region_dict[region_name] = region.id
except Exception as e:
logger.exception('api_import_hosts() hit exception')
error.append('Unable to create region {} - {}.'.format(region_name, e.message))
row += 1
if error:
return jsonify({'status': '\n'.join(error)})
# Import the data
row = 2
for row_data in data_list:
try:
created_by = current_user.username
hostname = get_acceptable_string(get_row_data(row_data, header_row, HEADER_FIELD_HOSTNAME))
# Check if the host already exists in the database.
host = get_host(db_session, hostname)
#.........这里部分代码省略.........
示例14: api_import_hosts
# 需要导入模块: from database import DBSession [as 别名]
# 或者: from database.DBSession import add [as 别名]
def api_import_hosts():
importable_header = [HEADER_FIELD_HOSTNAME, HEADER_FIELD_REGION, HEADER_FIELD_ROLES, HEADER_FIELD_IP,
HEADER_FIELD_USERNAME, HEADER_FIELD_PASSWORD, HEADER_FIELD_CONNECTION, HEADER_FIELD_PORT]
region_id = request.form['region']
data_list = request.form['data_list']
db_session = DBSession()
selected_region = get_region_by_id(db_session, region_id)
if selected_region is None:
return jsonify({'status': 'Region is no longer exists in the database.'})
# Check mandatory data fields
error = []
reader = csv.reader(data_list.splitlines(), delimiter=',')
header_row = next(reader)
if HEADER_FIELD_HOSTNAME not in header_row:
error.append('"hostname" is missing in the header.')
if HEADER_FIELD_IP not in header_row:
error.append('"ip" is missing in the header.')
if HEADER_FIELD_CONNECTION not in header_row:
error.append('"connection" is missing in the header.')
for header_field in header_row:
if header_field not in importable_header:
error.append('"' + header_field + '" is not a correct header field.')
if error:
return jsonify({'status': ','.join(error)})
# Check if each row has the same number of data fields as the header
error = []
data_list = list(reader)
row = 2
COLUMN_CONNECTION = get_column_number(header_row, HEADER_FIELD_CONNECTION)
COLUMN_REGION = get_column_number(header_row, HEADER_FIELD_REGION)
for row_data in data_list:
if len(row_data) > 0:
if len(row_data) != len(header_row):
error.append('line %d has wrong number of data fields.' % row)
else:
if COLUMN_CONNECTION >= 0:
# Validate the connection type
data_field = row_data[COLUMN_CONNECTION]
if data_field != ConnectionType.TELNET and data_field != ConnectionType.SSH:
error.append('line %d has a wrong connection type (should either be "telnet" or "ssh").' % row)
if COLUMN_REGION >= 0:
# Create a region if necessary
data_field = get_acceptable_string(row_data[COLUMN_REGION])
region = get_region(db_session, data_field)
if region is None and data_field:
try:
db_session.add(Region(name=data_field,
created_by=current_user.username))
db_session.commit()
except Exception:
db_session.rollback()
error.append('Unable to create region %s.' % data_field)
row += 1
if error:
return jsonify({'status': ','.join(error)})
# Import the data
error = []
im_regions = {}
for data in data_list:
if len(data) == 0:
continue
db_host = None
im_host = Host()
im_host.region_id = selected_region.id
im_host.created_by = current_user.username
im_host.inventory_job.append(InventoryJob())
im_host.context.append(HostContext())
im_host.connection_param.append(ConnectionParam())
im_host.connection_param[0].username = ''
im_host.connection_param[0].password = ''
im_host.connection_param[0].port_number = ''
for column in range(len(header_row)):
header_field = header_row[column]
data_field = data[column].strip()
if header_field == HEADER_FIELD_HOSTNAME:
hostname = get_acceptable_string(data_field)
db_host = get_host(db_session, hostname)
im_host.hostname = hostname
elif header_field == HEADER_FIELD_REGION:
region_name = get_acceptable_string(data_field)
if region_name in im_regions:
im_host.region_id = im_regions[region_name]
#.........这里部分代码省略.........
示例15: home
# 需要导入模块: from database import DBSession [as 别名]
# 或者: from database.DBSession import add [as 别名]
def home():
if current_user.privilege != UserPrivilege.ADMIN:
abort(401)
db_session = DBSession()
smtp_form = SMTPForm(request.form)
admin_console_form = AdminConsoleForm(request.form)
smtp_server = get_smtp_server(db_session)
system_option = SystemOption.get(db_session)
fill_user_privileges(admin_console_form.ldap_default_user_privilege.choices)
if request.method == 'POST' and \
smtp_form.validate() and \
admin_console_form.validate():
if smtp_server is None:
smtp_server = SMTPServer()
db_session.add(smtp_server)
smtp_server.server = smtp_form.server.data
smtp_server.server_port = smtp_form.server_port.data if len(smtp_form.server_port.data) > 0 else None
smtp_server.sender = smtp_form.sender.data
smtp_server.use_authentication = smtp_form.use_authentication.data
smtp_server.username = smtp_form.username.data
if len(smtp_form.password.data) > 0:
smtp_server.password = smtp_form.password.data
smtp_server.secure_connection = smtp_form.secure_connection.data
system_option.inventory_threads = admin_console_form.num_inventory_threads.data
system_option.install_threads = admin_console_form.num_install_threads.data
system_option.download_threads = admin_console_form.num_download_threads.data
system_option.can_schedule = admin_console_form.can_schedule.data
system_option.can_install = admin_console_form.can_install.data
system_option.enable_email_notify = admin_console_form.enable_email_notify.data
system_option.enable_inventory = admin_console_form.enable_inventory.data
# The LDAP UI may be hidden if it is not supported.
# In this case, the flag is not set.
if not is_empty(admin_console_form.enable_ldap_auth.data):
system_option.enable_ldap_auth = admin_console_form.enable_ldap_auth.data
system_option.ldap_server_url = admin_console_form.ldap_server_url.data
system_option.ldap_default_user_privilege = admin_console_form.ldap_default_user_privilege.data
system_option.ldap_server_distinguished_names = admin_console_form.ldap_server_distinguished_names.data.strip()
system_option.inventory_hour = admin_console_form.inventory_hour.data
system_option.inventory_history_per_host = admin_console_form.inventory_history_per_host.data
system_option.download_history_per_user = admin_console_form.download_history_per_user.data
system_option.install_history_per_host = admin_console_form.install_history_per_host.data
system_option.total_system_logs = admin_console_form.total_system_logs.data
system_option.enable_default_host_authentication = admin_console_form.enable_default_host_authentication.data
system_option.default_host_authentication_choice = admin_console_form.default_host_authentication_choice.data
system_option.enable_cco_lookup = admin_console_form.enable_cco_lookup.data
system_option.use_utc_timezone = admin_console_form.use_utc_timezone.data
system_option.default_host_username = admin_console_form.default_host_username.data
if len(admin_console_form.default_host_password.data) > 0:
system_option.default_host_password = admin_console_form.default_host_password.data
system_option.enable_user_credential_for_host = admin_console_form.enable_user_credential_for_host.data
db_session.commit()
return redirect(url_for('home'))
else:
admin_console_form.num_inventory_threads.data = system_option.inventory_threads
admin_console_form.num_install_threads.data = system_option.install_threads
admin_console_form.num_download_threads.data = system_option.download_threads
admin_console_form.can_schedule.data = system_option.can_schedule
admin_console_form.can_install.data = system_option.can_install
admin_console_form.enable_email_notify.data = system_option.enable_email_notify
admin_console_form.enable_ldap_auth.data = system_option.enable_ldap_auth
admin_console_form.ldap_server_url.data = system_option.ldap_server_url
admin_console_form.ldap_default_user_privilege.data = system_option.ldap_default_user_privilege
admin_console_form.ldap_server_distinguished_names.data = system_option.ldap_server_distinguished_names
admin_console_form.enable_inventory.data = system_option.enable_inventory
admin_console_form.inventory_hour.data = system_option.inventory_hour
admin_console_form.inventory_history_per_host.data = system_option.inventory_history_per_host
admin_console_form.download_history_per_user.data = system_option.download_history_per_user
admin_console_form.install_history_per_host.data = system_option.install_history_per_host
admin_console_form.total_system_logs.data = system_option.total_system_logs
admin_console_form.enable_default_host_authentication.data = system_option.enable_default_host_authentication
admin_console_form.default_host_authentication_choice.data = system_option.default_host_authentication_choice
admin_console_form.default_host_username.data = system_option.default_host_username
admin_console_form.enable_cco_lookup.data = system_option.enable_cco_lookup
admin_console_form.use_utc_timezone.data = system_option.use_utc_timezone
admin_console_form.cco_lookup_time.data = get_datetime_string(system_option.cco_lookup_time)
admin_console_form.enable_user_credential_for_host.data = system_option.enable_user_credential_for_host
if not is_empty(system_option.default_host_password):
admin_console_form.default_host_password_placeholder = 'Use Password on File'
else:
admin_console_form.default_host_password_placeholder = 'No Password Specified'
if smtp_server is not None:
smtp_form.server.data = smtp_server.server
smtp_form.server_port.data = smtp_server.server_port
#.........这里部分代码省略.........