本文整理汇总了Python中nextgisbio.models.DBSession.add方法的典型用法代码示例。如果您正苦于以下问题:Python DBSession.add方法的具体用法?Python DBSession.add怎么用?Python DBSession.add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类nextgisbio.models.DBSession
的用法示例。
在下文中一共展示了DBSession.add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: add_from_file
# 需要导入模块: from nextgisbio.models import DBSession [as 别名]
# 或者: from nextgisbio.models.DBSession import add [as 别名]
def add_from_file(filename):
"""
Добавить данные в таблицу таксонов из файла filename (разделители - табуляция).
Файл filename в формате csv, колонки:
id parent_id old_id taxon_type name russian_name author source
"""
import transaction
with transaction.manager:
dbsession = DBSession()
reader = csv.reader(open(filename), delimiter="\t")
row = reader.next() # пропускаем заголовки
records = [line for line in reader]
for row in records:
id, parent_id, old_id, taxon_type, name, russian_name, author, source = [
None if x == "" else x for x in row
]
taxon = Taxon(
parent_id=parent_id,
old_id=old_id,
taxon_type=taxon_type,
name=name,
russian_name=russian_name,
author=author,
source=source,
)
dbsession.add(taxon)
示例2: add_from_file
# 需要导入模块: from nextgisbio.models import DBSession [as 别名]
# 或者: from nextgisbio.models.DBSession import add [as 别名]
def add_from_file(filename):
'''
Добавить данные в таблицу из файла с разделителями filename.
Файл filename в формате csv, колонки:
id name fullname speciality degree organization position email phone address
'''
import transaction
with transaction.manager:
dbsession = DBSession()
reader = csv.reader(open(filename), delimiter='\t')
row = reader.next() # пропускаем заголовки
records = [line for line in reader]
for (id, name, fullname, speciality, degree, organization, position, email, phone, address) in records:
person = Person(
name=name,
fullname=fullname,
speciality=speciality,
degree=degree,
organization=organization,
position=position,
email=email,
phone=phone,
address=address
)
dbsession.add(person)
示例3: add_from_file
# 需要导入模块: from nextgisbio.models import DBSession [as 别名]
# 或者: from nextgisbio.models.DBSession import add [as 别名]
def add_from_file(associations_filename, shp_filename):
'''
Добавить данные из shp-файла shp_filename. Первое поле аттрибутивной таблицы--идентификатор.
Одновременно добавляются в таблицу связи данные из файла с разделителями associations_filename.
Файл filename в формате csv (разделитель табуляция), колонки:
square_id key_area_id
'''
import transaction
with transaction.manager:
dbsession = DBSession()
ogrData = ogr.Open(shp_filename)
layer = ogrData.GetLayer(0)
sq = layer.GetNextFeature()
while sq is not None:
id = sq.GetFieldAsString(0)
geom = sq.GetGeometryRef()
geom = geom.ExportToWkt()
square = Squares(id=id, geom=WKTSpatialElement(geom, srid=3857))
dbsession.add(square)
sq = layer.GetNextFeature()
dbsession.flush()
reader = csv.reader(open(associations_filename), delimiter='\t')
reader.next()
records = [line for line in reader]
for id, key_area_id in records:
# Определим ключевоq уч-к по его id
key_a = dbsession.query(Key_area).filter_by(id=key_area_id).one()
# Определим полигон по его id
square = dbsession.query(Squares).filter_by(id=id).one()
square.key_areas.append(key_a)
示例4: new_card
# 需要导入模块: from nextgisbio.models import DBSession [as 别名]
# 或者: from nextgisbio.models.DBSession import add [as 别名]
def new_card(request):
with transaction.manager:
dbsession = DBSession()
card = Cards()
_update_card_attributes(card, dict(request.POST))
card.added_date = datetime.now()
card.edited_date = card.added_date
dbsession.add(card)
return {}
示例5: table_item_save
# 需要导入模块: from nextgisbio.models import DBSession [as 别名]
# 或者: from nextgisbio.models.DBSession import add [as 别名]
def table_item_save(request):
session = DBSession()
session.expire_on_commit = False
if ('person_id' in request.POST) and request.POST['person_id'].isdigit():
person_id = int(request.POST['person_id'])
person = session.query(Person) \
.options(joinedload('user')) \
.filter(Person.id == person_id) \
.all()[0]
user = person.user
else:
person = Person()
user = User()
session.add(user)
person.user = user
for attr in request.POST:
table_name, field = attr.split('_')
if field == 'id':
continue
if table_name == 'person':
setattr(person, field, request.POST[attr])
if table_name == 'user':
setattr(user, field, request.POST[attr])
if 'user_active' in request.POST and request.POST['user_active']:
user.active = True
else:
user.active = False
if 'user_password' in request.POST and request.POST['user_password']:
user.password = User.password_hash(request.POST['user_password'])
session.add(person)
try:
transaction.commit()
except IntegrityError:
transaction.abort()
return {
'Result': 'Error',
'Message': u'Такой логин уже присутствует в системе'
}
person_json = person.as_json_dict('person_')
user_json = user.as_json_dict('user_')
item_json = person_json.copy()
item_json.update(user_json)
session.close()
return {
'Result': 'OK',
'Record': item_json
}
示例6: put
# 需要导入模块: from nextgisbio.models import DBSession [as 别名]
# 或者: from nextgisbio.models.DBSession import add [as 别名]
def put(self):
new_synonym_dict = dict(self.request.POST)
with transaction.manager:
dbsession = DBSession()
synonym = Synonym()
for k, v in new_synonym_dict.items():
if v == '': v = None
if hasattr(synonym, k): setattr(synonym, k, v)
synonym.species_id = int(self.request.matchdict['taxon_id'])
dbsession.add(synonym)
示例7: import_from_csv
# 需要导入模块: from nextgisbio.models import DBSession [as 别名]
# 或者: from nextgisbio.models.DBSession import add [as 别名]
def import_from_csv(path_to_file):
with transaction.manager:
session = DBSession()
reader = csv.reader(open(path_to_file), delimiter='\t')
reader.next() # пропускаем заголовки
records = [line for line in reader]
for row in records:
id_image, name, description, url, local, size = [None if x == '' else x for x in row]
image = Images(name=name, description=description, url=url, local=local, size=size)
session.add(image)
示例8: create_taxon
# 需要导入模块: from nextgisbio.models import DBSession [as 别名]
# 或者: from nextgisbio.models.DBSession import add [as 别名]
def create_taxon(request):
new_data = dict(request.POST)
dbsession = DBSession()
taxon = Taxon()
for k, v in new_data.items():
if v == '': v = None
if hasattr(taxon, k): setattr(taxon, k, v)
dbsession.add(taxon)
dbsession.flush()
dbsession.refresh(taxon)
return {'item': taxon.as_json_dict()}
示例9: gen_sql
# 需要导入模块: from nextgisbio.models import DBSession [as 别名]
# 或者: from nextgisbio.models.DBSession import add [as 别名]
def gen_sql(records):
with transaction.manager:
for r in records:
id = None
for t in 'Kingdom', 'Phylum', 'Class', 'Order', 'Family', 'Genus', 'Species':
try:
print t, r[t]
taxon = DBSession.query(Taxon).filter_by(taxon_type = t, name = r[t], parent_id = id).one()
print taxon
except NoResultFound:
taxon = Taxon(taxon_type = t, name = r[t], parent_id = id, author=r[t+'_author'], source=r[t+'_source'])
DBSession.add(taxon)
DBSession.flush()
id = taxon.id
print taxon.id, taxon.taxon_type, taxon.name, taxon.parent_id
示例10: new_anlist
# 需要导入模块: from nextgisbio.models import DBSession [as 别名]
# 或者: from nextgisbio.models.DBSession import add [as 别名]
def new_anlist(request):
new_data = dict(request.POST)
success = True
try:
import transaction
with transaction.manager:
dbsession = DBSession()
anlist = Annotation()
for k,v in new_data.items():
if v == '': v = None
if hasattr(anlist, k): setattr(anlist, k, v)
dbsession.add(anlist)
except:
success = False
return {'success': success}
示例11: upload_image
# 需要导入模块: from nextgisbio.models import DBSession [as 别名]
# 或者: from nextgisbio.models.DBSession import add [as 别名]
def upload_image(request):
filename = request.POST['file'].filename
input_file = request.POST['file'].file
obj_id = request.matchdict['id']
obj_type = request.matchdict['type']
path_to_images = os.path.join(os.path.dirname(nextgisbio.__file__), 'static/data/images')
date_now = datetime.datetime.now().strftime('%Y-%m-%d')
path_to_images_now = os.path.join(path_to_images, date_now)
if not os.path.exists(path_to_images_now):
os.mkdir(path_to_images_now)
# from http://stackoverflow.com/questions/2782229/most-lightweight-way-to-create-a-random-string-and-a-random-hexadecimal-number
random_file_name = str(uuid.uuid4())
base_file_path = os.path.join(path_to_images_now, '.'.join([random_file_name, 'jpg']))
with open(base_file_path, 'wb') as output_file:
shutil.copyfileobj(input_file, output_file)
for key_size in THUMBNAIL_SIZES:
try:
im = Image.open(base_file_path)
im.thumbnail(THUMBNAIL_SIZES[key_size], Image.BICUBIC)
im.save(os.path.join(path_to_images_now, '.'.join([random_file_name + '_' + key_size, 'jpg'])), 'JPEG',
quality=70)
except IOError:
print "cannot create thumbnail for '%s'" % base_file_path
with transaction.manager:
dbSession = DBSession()
image = Images()
image.name = filename
image.url = '/static/data/images/%s/%s.jpg' % (date_now, random_file_name)
image.size = os.path.getsize(base_file_path)
image.local = base_file_path
dbSession.add(image)
if obj_type == 'card':
card_image = CardsImages()
card_image.image = image
card_image.card = dbSession.query(Cards).filter_by(id=obj_id).one()
dbSession.add(card_image)
photo_json = image.as_json_dict()
return photo_json
示例12: add_from_file
# 需要导入模块: from nextgisbio.models import DBSession [as 别名]
# 或者: from nextgisbio.models.DBSession import add [as 别名]
def add_from_file(users_csv_file_path, md5_pass):
import transaction
with transaction.manager:
dbsession = DBSession()
reader = csv.reader(open(users_csv_file_path), delimiter='\t')
reader.next()
records = [line for line in reader]
for row in records:
(id, login, password, person_id, role) = [None if x == '' else x for x in row]
user = User(
login=login,
password=password if md5_pass else User.password_hash(password),
role=role,
person_id=person_id,
active=True
)
dbsession.add(user)
示例13: add_from_file
# 需要导入模块: from nextgisbio.models import DBSession [as 别名]
# 或者: from nextgisbio.models.DBSession import add [as 别名]
def add_from_file(filename):
'''
Добавить данные в таблицу из файла с разделителями filename.
Файл filename в формате csv, колонки:
id species key_area identifier collecter biblioref original_name location lon lat biotop difference substrat status frequency quantity annotation infosourse year month day exposure
'''
import transaction
with transaction.manager:
dbsession = DBSession()
reader = csv.reader(open(filename), delimiter='\t')
row = reader.next() # пропускаем заголовки
records = [line for line in reader]
for row in records:
x = [None if x == '' else x for x in row]
print str(len(x)) + ' - ' + str(x[0])
(
id, species, inserter, key_area, identifier, collecter,
biblioref,
original_name, location, lon, lat,
biotop, difference, substrat, status,
frequency, quantity, annotation,
infosourse, year, month, day, exposure
) = [None if x == '' else x for x in row]
ann = Annotation(
species=species,
inserter=inserter,
key_area=key_area,
identifier=identifier,
collecter=collecter,
biblioref=biblioref,
original_name=original_name, location=location, lon=lon, lat=lat,
biotop=biotop, difference=difference, substrat=substrat, status=status,
frequency=frequency, quantity=quantity, annotation=annotation,
infosourse=infosourse, year=year, month=month, day=day, exposure=exposure
)
dbsession.add(ann)
示例14: table_item_save
# 需要导入模块: from nextgisbio.models import DBSession [as 别名]
# 或者: from nextgisbio.models.DBSession import add [as 别名]
def table_item_save(request):
session = DBSession()
table, table_name = helpers.get_table_by_name(request)
if ('id' in request.POST) and request.POST['id'].isdigit():
item_id = int(request.POST['id'])
item = session.query(table).get(item_id)
else:
item = table()
for attr in request.POST:
if attr == 'id':
continue
setattr(item, attr, request.POST[attr])
session.add(item)
item_as_json = item.as_json_dict()
transaction.commit()
session.close()
return {
'Result': 'OK',
'Record': item_as_json
}
示例15: import_from_csv
# 需要导入模块: from nextgisbio.models import DBSession [as 别名]
# 或者: from nextgisbio.models.DBSession import add [as 别名]
def import_from_csv(path_to_file):
session = DBSession()
log = {
'not_found': [],
'duplicates': [],
'multiple': []
}
reader = csv.reader(open(path_to_file), delimiter='\t')
reader.next()
records = [line for line in reader]
red_books = {}
for region, orig_name, lat_name, author, population, status, univ_status, year, bibl in records:
if bibl in red_books:
continue
else:
red_books[bibl] = True
with transaction.manager:
for red_book_name in red_books.keys():
red_book = RedBook(
name=red_book_name
)
session.add(red_book)
red_books_db = session.query(RedBook).all()
red_books = {}
for red_book_db in red_books_db:
red_books[red_book_db.name.encode('utf8')] = red_book_db.id
with transaction.manager:
for region, orig_name, lat_name, author, population, status, univ_status, year, bibl in records:
lat_name = lat_name.strip()
taxons = session.query(Taxon).filter_by(name=lat_name).all()
taxons_count = len(taxons)
if taxons_count == 1:
taxon_id = taxons[0].id
elif taxons_count > 1:
taxons = session.query(Taxon).filter_by(name=lat_name).filter_by(author=author).all()
taxon_id = taxons[0].id
if len(taxons) > 1:
log['multiple'].append(lat_name)
continue
else:
log['not_found'].append(lat_name)
continue
red_book_id = red_books[bibl]
count = session.query(func.count(RedBookSpecies.specie_id)) \
.filter(RedBookSpecies.red_book_id == red_book_id) \
.filter(RedBookSpecies.specie_id == taxon_id).scalar()
if count > 0:
log['duplicates'].append(taxons[0].name)
continue
red_book_specie = RedBookSpecies(
red_book_id=red_book_id,
specie_id=taxon_id,
population=population,
status=status,
univ_status=univ_status,
year=int(year) if year else None,
region=region,
author=author,
orig_name=orig_name.strip()
)
session.add(red_book_specie)
session.flush()
print '\n\rMULTIPLE:\n\r{0}'.format('\n\r'.join(log['multiple']))
print '\n\rNOT FOUND:\n\r{0}'.format('\n\r'.join(log['not_found']))
print '\n\rDUPLICATES:\n\r{0}'.format('\n\r'.join(log['duplicates']))