本文整理匯總了Python中tribal.model.DBSession.add方法的典型用法代碼示例。如果您正苦於以下問題:Python DBSession.add方法的具體用法?Python DBSession.add怎麽用?Python DBSession.add使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類tribal.model.DBSession
的用法示例。
在下文中一共展示了DBSession.add方法的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: update
# 需要導入模塊: from tribal.model import DBSession [as 別名]
# 或者: from tribal.model.DBSession import add [as 別名]
def update( self, **kw ):
old_object = self.serialize()
old_object_status = self.status
for key, dbobj in [( "project_own", Region ), ( "team", Team ), ( "customer", Customer ), ( "request_team", Team ),
( "item_category", PSItemCategory )]:
if key in kw :
val = DBSession.query( dbobj ).get( kw[key] ) if kw[key] else None
setattr( self, key, val )
for key in ["contact_person", "reference_code", "item_description", "item_code", "project_owner", "request_contact_number", "project"]:
if key in kw :
val = kw[key].strip() if kw[key] else None
setattr( self, key, val )
if "cc_to" in kw:
self.cc_to = ( kw["cc_to"] or '' ).replace( "\n", '' )
self.child_form = kw.get( "form_ids" )
# add the update log
if old_object_status != PS_DRAFT:
self.revision += 1
# if update from draft and save to status: new
if old_object_status == PS_DRAFT and not kw['is_draft']:
self.status = PS_NEW_REQUEST
new_object = self.serialize( False )
check_log = PSMainForm.compareObject( old_object, new_object )
log_str = []
for ( key, old_val, new_val ) in check_log['update']:
log_str.append( "Change [%s] from '%s' to '%s' " % ( key, old_val, new_val ) )
for ( key, new_val ) in check_log['new']:
log_str.append( "New [%s] '%s' " % ( key, new_val ) )
if log_str and old_object_status != PS_DRAFT: DBSession.add( PSDevelopmentLog( system_no = str( self ), main_form_id = self.id, sub_form_id = None, sub_form_type = None, action_type = 'UPDATE', remark = " .\n".join( log_str ) ) )
示例2: upload
# 需要導入模塊: from tribal.model import DBSession [as 別名]
# 或者: from tribal.model.DBSession import add [as 別名]
def upload( self, **kw ):
try:
print "*-" * 30
print type( kw["attachment"] )
print "*-" * 30
file_path = kw["attachment"].filename
( pre, ext ) = os.path.splitext( file_path )
path_prefix = os.path.join( config.download_dir, "sys" )
if not os.path.exists( path_prefix ) : os.makedirs( path_prefix )
file_name = "%s%.4d%s" % ( dt.now().strftime( "%Y%m%d%H%M%S" ), random.randint( 1, 1000 ), ext )
print file_name
print "*-" * 30
full_path = os.path.join( path_prefix, file_name )
f = open( full_path, "wb" )
f.write( kw["attachment"].file.read() )
f.close()
db_file_name = kw.get( "attachment_name", None ) or file_name
if db_file_name.find( "." ) < 0 : db_file_name = db_file_name + ext
obj = UploadObject( file_name = db_file_name, file_path = os.path.join( "sys", file_name ) )
DBSession.add( obj )
DBSession.flush()
return obj.id
except:
traceback.print_exc()
return None
示例3: add_attachments
# 需要導入模塊: from tribal.model import DBSession [as 別名]
# 或者: from tribal.model.DBSession import add [as 別名]
def add_attachments(self, attachments=[], key='attachment'):
ids = []
for att in attachments:
upObj = UploadObject(**{'_file_path':att, 'file_name': att.split('\\')[-1].split('/')[-1]})
DBSession.add(upObj)
DBSession.flush()
ids.append(upObj.id)
setattr(self, key, '|'.join(map(str, ids)))
示例4: create
# 需要導入模塊: from tribal.model import DBSession [as 別名]
# 或者: from tribal.model.DBSession import add [as 別名]
def create(cls, **kw):
params = cls.upload_attachments('logo', 'proof', **kw)
params = cls._resetKw(**params)
if params.has_key('logo'):
params['logo'] = '|'.join(map(str, params['logo'].split(',')))
elif params.has_key('proof'):
params['proof'] = '|'.join(map(str, params['proof'].split(',')))
obj = cls(**params)
DBSession.add(obj)
return obj
示例5: saveNew
# 需要導入模塊: from tribal.model import DBSession [as 別名]
# 或者: from tribal.model.DBSession import add [as 別名]
def saveNew(self, **kw):
params = {"issuedBy":request.identity["user"], "lastModifyBy":request.identity["user"], "lastModifyTime":dt.now()}
for f in self.formFields:
if f in kw : params[f] = kw[f]
params = self.beforeSaveNew(kw, params)
obj = self.dbObj(**params)
obj = self.afterSaveNew(obj,kw)
DBSession.add(obj)
flash("Save the new master successfully!")
redirect("/%s/index" % self.url)
示例6: _init_local_from_erp
# 需要導入模塊: from tribal.model import DBSession [as 別名]
# 或者: from tribal.model.DBSession import add [as 別名]
def _init_local_from_erp():
#insert newset so dtl and hdr
newest_date = MglobalSchedulerErp.get_last_date()
qi_start_date = newest_date.qi_date.strftime('%Y-%m-%d 00:00:00') if newest_date else '2013-01-24 00:00:00'
qi_end_date = dt.now().strftime('%Y-%m-%d 00:00:00')
so_list = MglobalErpSO.find_from_erp_by_date(qi_start_date, qi_end_date)
print 'add new so list size: %s' % len(so_list)
for record in so_list:
sod = MglobalErpSOD.merge(**{
'so_no':unicode(record[0]) if record[0] else None,
'cust_po_no':unicode(record[1]) if record[1] else None,
'customer_code':unicode(record[2]) if record[2] else None,
'customer_name':unicode(record[3]) if record[3] else None,
'line_no':unicode(record[4]) if record[4] else None,
'item_code':unicode(record[5]) if record[5] else None,
'order_qty':int(record[6]) if record[6] else None,
'create_date':record[7]
})
DBSession.add(MglobalSchedulerErp(**{'ci_date': dt.now(), 'qi_date': dt.now()}))
client_id_list = MglobalMasterItem.find_client_id_list()
mp_no_list = MglobalCustPo.find_cust_po_no(client_id_list)
MglobalErpSO.update_in_mp_order(mp_no_list)
#synchronize the uncomplete so hdr
so_undone_list = MglobalErpSO.find_undone_mp_so()
#so_undone_list = MglobalErpSO.find_undone_so()
print 'undone so size: %s' % len(so_undone_list)
so_undone_no_list = []
so_undone_map = {}
for i in so_undone_list:
so_undone_no_list.append(i.so_no)
so_undone_map[i.so_no] = i
soh_so_list = MglobalErpSO.find_so_from_erp_by_so(so_undone_no_list)
print 'search so size: %s' % len(soh_so_list)
for i in soh_so_list:
if so_undone_map[i[0]].so_qty != i[1]:
soh = so_undone_map[i[0]]
soh.has_update_so = True
soh.so_qty = i[1]
soh_si_list = MglobalErpSO.find_si_from_erp_by_so(so_undone_no_list)
print 'search si size: %s' % len(soh_si_list)
for i in soh_si_list:
if so_undone_map[i[0]].so_invoice_qty != i[1]:
soh = so_undone_map[i[0]]
soh.has_update_si = True
soh.so_invoice_qty = i[1]
soh.cp_so_si = so_undone_map[i[0]].so_invoice_qty >= so_undone_map[i[0]].so_qty
soh_dn_list = MglobalErpSO.find_dn_from_erp_by_so(so_undone_no_list)
print 'search dn size: %s' % len(soh_dn_list)
for i in soh_dn_list:
if so_undone_map[i[0]].so_dn_qty != i[1]:
soh = so_undone_map[i[0]]
soh.has_update_dn = True
soh.so_dn_qty = i[1]
soh.cp_so_dn = so_undone_map[i[0]].so_dn_qty >= so_undone_map[i[0]].so_qty
示例7: copyAttachments
# 需要導入模塊: from tribal.model import DBSession [as 別名]
# 或者: from tribal.model.DBSession import add [as 別名]
def copyAttachments( cls, ids ):
if isinstance( ids, str ) or isinstance( ids, unicode ):
ids = [ids]
objs = [DBSession.query( UploadObject ).get( int( id ) ) for id in ids if id]
attachments = []
for obj in objs:
if obj:
attachment = UploadObject( **{'file_name': obj.file_name, 'file_path': obj._file_path} )
DBSession.add( attachment )
DBSession.flush()
attachments.append( attachment.id )
return attachments
示例8: get_mglobal_upload_data
# 需要導入模塊: from tribal.model import DBSession [as 別名]
# 或者: from tribal.model.DBSession import add [as 別名]
def get_mglobal_upload_data():
results = []
_init_local_from_erp()
_process_local_so()
_proess_blank_awb()
#prepare the upload data to MglobalPack for cron
upload_list = MglobalErpDND.find_updated_dn()
upload_map = {}
for dnd in upload_list:
so_hdr = dnd.local_so
so_dtls = so_hdr.local_sods
dn_client = dnd.local_client
key = '%s-%s' % (so_hdr.cust_po_no, dn_client.client_id)
upload_dn = upload_map.get(key, None)
dnd_awb = dnd.get_awb()
if dnd_awb:
if not upload_dn:
upload_dn = {'MGOrderNumber': so_hdr.cust_po_no, 'MGClientNumber': dn_client.client_id, 'OptionalNote': '', 'Items': {}}
if so_hdr.has_done:
upload_dn.update({'MODE': 'C', 'InvoiceDate': dnd.dn_date.strftime('%Y-%m-%d %H:%M:%S'), 'InvoiceNumber': dnd.so_no,
'TrackingNumber': dnd_awb[1],
'TransportCompany': dnd_awb[0]})
else:
upload_dn.update({'MODE': 'P'})
upload_map[key] = upload_dn
if not upload_dn['Items'].has_key(dnd.local_item.mg_item_code):
upload_dn['Items'][dnd.local_item.mg_item_code] = {}
if not upload_dn['Items'][dnd.local_item.mg_item_code].has_key(dnd.dn_no):
upload_dn['Items'][dnd.local_item.mg_item_code][dnd.dn_no] = {
'ItemCode': dnd.local_item.mg_item_code,
'PartialDeliveryDocument': dnd.dn_no,
'PartialDeliveryDate': dnd.dn_date.strftime('%Y-%m-%d %H:%M:%S'),
'InvoicedQty': dnd.dn_qty
}
else:
item = upload_dn['Items'][dnd.local_item.mg_item_code][dnd.dn_no]
item['InvoicedQty'] += dnd.dn_qty
DBSession.add(MglobalSchedulerMg(**{'ci_date': dt.now(), 'qi_date': dt.now()}))
for k, v in upload_map.iteritems():
dn_items = []
mg_cust_po = MglobalCustPo.get_by_cust_po_no(v['MGOrderNumber'], v['MGClientNumber'])
if mg_cust_po:
for i in mg_cust_po.detail:
if v['Items'].has_key(i.item_no):
dn_items.extend(v['Items'][i.item_no].values())
v['Items'] = dn_items
results.append(v)
transaction.commit()
return results
示例9: create
# 需要導入模塊: from tribal.model import DBSession [as 別名]
# 或者: from tribal.model.DBSession import add [as 別名]
def create( cls, **kw ):
requiredFields = ["project_own", "contact_person", "team", "project", "project_own"]
is_draft = kw['is_draft']
if not is_draft:
for f in requiredFields:
if not kw.get( f, False ) :
raise Exception( 'Please Fill in the required field(s) before you submit the request!' )
hParam = {
'child_form': kw.get( "form_ids", '' ),
"contact_person" : kw.get( "contact_person", None ),
"reference_code" : kw.get( "reference_code", None ),
"item_description" : kw.get( "item_description", None ),
"item_code" : kw.get( "item_code", None ),
"request_contact_number" : kw.get( "request_contact_number", None ),
"team" : DBSession.query( Team ).get( kw["team"] ) if kw.get( "team", None ) else None,
"customer" : DBSession.query( Customer ).get( kw["customer"] ) if kw.get( "customer", False ) else None,
"item_category" : DBSession.query( PSItemCategory ).get( kw["item_category"] ) if kw.get( "item_category", False ) else None,
"project" : kw.get( "project", None ),
"project_own" : DBSession.query( Region ).get( kw["project_own"] ) if kw.get( "project_own", False ) else None,
"request_team" : DBSession.query( Team ).get( kw["request_team"] ) if kw.get( "request_team", None ) else None,
"project_owner" : kw.get( "project_owner", None ),
"rpt" : kw.get( "rpt", None ) or None,
"cc_to" : kw.get( "cc_to", None ) or None,
"status": PS_DRAFT if is_draft else PS_NEW_REQUEST,
"status_back": PS_DRAFT if is_draft else PS_NEW_REQUEST,
}
if hParam['cc_to'] : hParam['cc_to'] = hParam['cc_to'].strip().replace( "\n", '' )
hParam["request_type"] = "New"
def _getSystemNo():
s = Sequence( 'rp_main_form_seq' )
s.create( DBSession.bind, checkfirst = True ) # if the seq is existed ,don't create again
c = DBSession.execute( s )
prefix = 'OTHER'
for g in request.identity["user"].groups:
for profile in g.prepress_profiles:
if profile.region_id :
prefix = profile.region.code
break
# return "RP%s%.6d" % ( prefix, c )
return "RP%s%s" % ( prefix, c )
hParam["system_no"] = _getSystemNo()
h = PSMainForm( **hParam )
DBSession.add( h )
return h
示例10: merge
# 需要導入模塊: from tribal.model import DBSession [as 別名]
# 或者: from tribal.model.DBSession import add [as 別名]
def merge(cls, **kw):
def _update_awb(dnd):
dnd_awb = dnd.get_awb()
if dnd_awb:
dnd.awb_corp, dnd.awb_no = dnd_awb
return dnd
dnd = cls.get_dnd(kw['dn_no'], kw['dn_line_no'])
if not dnd:
dnd = cls(**kw)
local_so = MglobalErpSO.get_so(dnd.so_no)
dnd.local_so_id = local_so.id
dnd.cust_po_no = local_so.cust_po_no
item = MglobalMasterItem.get_by_erp_code(dnd.item_code)
if item:
dnd.local_item_id = item.id
dnd.local_client_id = item.local_client.id
dnd.client_id = item.local_client.client_id
dnd.has_update = True
else:
dnd.has_update = None
_update_awb(dnd)
DBSession.add(dnd)
elif not dnd.awb_no:
_update_awb(dnd)
# elif not self.compare(**kw):
# dnd.dn_qty = kw['dn_qty']
# dnd.dn_date = kw['dn_date']
# dnd.awb_no = kw['awb_no']
# dnd.item_code = kw['item_code']
# item = MglobalMasterItem.get_by_erp_code(dnd.item_code)
# if item:
# dnd.local_item_id = item.id
# dnd.has_update = True
# else:
# dnd.has_update = None
return dnd
示例11: _insert_result_db
# 需要導入模塊: from tribal.model import DBSession [as 別名]
# 或者: from tribal.model.DBSession import add [as 別名]
def _insert_result_db(result,data):
total_msg_mapping = {
"1" : "No error, all the orders was processed successfully.",
"2" : "Some orders have a specific error.",
"3" : "Internal error, we can’t finalize your orders.",
"4" : "No orders to finalize.",
}
level_msg_mapping = {
"0" : "Success",
"1" : "Finalized date is required",
"2" : "Invoice number is required",
"3" : "Invoice date must not be greater than two days from today.",
"4" : "Tracking number is required",
"5" : "Invoice date corresponds to a closed period.",
"10" : "Order is not at Received status.",
"11" : "Order is not a HK's order.",
"12" : "Order is not found",
"13" : "Internal error.",
"14" : "Order contains not matching items.",
"15" : "No items to finalize.",
}
mapping = {}
try:
header = MglobalTotalResult(
flag = unicode(result['GeneralResult']),
msg = unicode(total_msg_mapping.get(unicode(result['GeneralResult']), '')),
)
DBSession.add(header)
for d in data :
mapping['%s-%s' % (d['MGOrderNumber'], d['MGClientNumber'])] = d
if d.has_key('InvoceDate'):
si_date = d['InvoiceDate']
if si_date and isinstance(si_date, (date,dt)):
d['InvoiceDate'] = si_date.strftime(_datetime_format)
else:
d['InvoiceDate'] = unicode(si_date)
for item in d["Items"]:
tmp_date = item['PartialDeliveryDate']
if tmp_date and isinstance(tmp_date, (date,dt)):
item['PartialDeliveryDate'] = tmp_date.strftime(_datetime_format)
else:
item['PartialDeliveryDate'] = unicode(tmp_date)
for line in result['OrderResult']:
so_info = mapping.get('%s-%s' % (line['MGOrderNumber'], line['MGClientNumber']), '')
DBSession.add(MglobalResult(
total_result = header,
mglobal_no = unicode(line['MGOrderNumber']),
si_no = unicode(so_info.get('InvoiceNumber', None)),
flag = unicode(line['Result']),
cust_no = unicode(line['MGClientNumber']),
msg = unicode(level_msg_mapping.get(unicode(line['Result']),'')),
content = json.dumps(so_info),
))
after_send_dn(int(line['Result']), line['MGOrderNumber'], line['MGClientNumber'])
transaction.commit()
except:
traceback.print_exc()
transaction.doom()
示例12: create
# 需要導入模塊: from tribal.model import DBSession [as 別名]
# 或者: from tribal.model.DBSession import add [as 別名]
def create(cls, **kw):
obj = cls(**cls._resetKw(**kw))
DBSession.add(obj)
return obj