本文整理汇总了Python中tools.file_open函数的典型用法代码示例。如果您正苦于以下问题:Python file_open函数的具体用法?Python file_open怎么用?Python file_open使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了file_open函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _send_mail
def _send_mail(self, cr, uid, data, context):
ptrn = re.compile('(\[email protected]\w+(?:\.\w+)+)')
result = ptrn.search(data['form']['email'])
if result==None:
raise wizard.except_wizard('Error !', 'Enter Valid E-Mail Address.')
fields=['Id','Name','Partner','Related Type of Carnet','Emission Date','Validity Date','Holder Name','Holder Address','Holder City','Representer Name','Representer Address','Representer City','Usage','Goods','Area','Insurer Agreement','Own Risks','Goods Value','Double Signature','Initial No. of Pages','Additional No. of Pages','Warranty','Related Warranty Product','Date of Return','State','Date of Closure','Date of Sending to the Federation','Apply the Member Price']
# For First CSV
month=data['form']['month']
yr=int(time.strftime('%Y'))
self.first_day=datetime.date(yr,int(month),1)
self.last_day=datetime.date(yr,int(month),lengthmonth(yr, int(month)))
period="to_date('" + self.first_day.strftime('%Y-%m-%d') + "','yyyy-mm-dd') and to_date('" + self.last_day.strftime('%Y-%m-%d') +"','yyyy-mm-dd')"
cr.execute('select id from cci_missions_ata_carnet where federation_sending_date is null and ok_state_date between %s'%(period))
res_file1=cr.fetchall()
lines=[]
root_path=tools.config.options['root_path']
if res_file1:
lines=self.make_csv(cr, uid,res_file1,file2=0)
self.write_csv(root_path+'/carnet_1.csv',fields,lines)
# First CSV created
# Process for second CSV -Start
today=datetime.datetime.today()
_date=datetime.date(today.year-2,today.month,today.day)
comp_date=_date.strftime('%Y-%m-%d')
cr.execute('select id from cci_missions_ata_carnet where federation_sending_date is null and state='"'pending'"' and return_date <='"'%s'"''%(str(comp_date)))
res_file2=cr.fetchall()
lines=[]
if res_file2:
lines=self.make_csv(cr, uid,res_file2,file2=1)
self.write_csv(root_path+'/carnet_2.csv',fields,lines)
# Second CSV created.
if res_file1==[] and res_file2==[]:
raise wizard.except_wizard('Notification !', 'No Records Found to make the CSV files.Choose other criteria.')
files_attached=[]
if res_file1:
file_csv1=tools.file_open(root_path+'/carnet_1.csv','rb',subdir=None)
files_attached=[('Ata_carnet_csv_1.csv',file_csv1.read())]
if res_file2:
file_csv2=tools.file_open(root_path+'/carnet_2.csv','rb',subdir=None)
files_attached.append(('Ata_carnet_csv_2.csv',file_csv2.read()))
src=tools.config.options['smtp_user']
dest=[data['form']['email']]
body="Hello,\nHere are the CSV files for Federation Sending.\nThanks You For Using TinyERP.\nThink Big Use Tiny."
tools.email_send_attach(src,dest,"Federation Sending Files From TinyERP",body,attach=files_attached)
return {}
示例2: sxwtorml
def sxwtorml(self,cr, uid, file_sxw,file_type):
'''
The use of this function is to get rml file from sxw file.
'''
sxwval = StringIO(base64.decodestring(file_sxw))
if file_type=='sxw':
fp = tools.file_open('normalized_oo2rml.xsl',
subdir='addons/base_report_designer/wizard/tiny_sxw2rml')
if file_type=='odt':
fp = tools.file_open('normalized_odt2rml.xsl',
subdir='addons/base_report_designer/wizard/tiny_sxw2rml')
return {'report_rml_content': str(sxw2rml(sxwval, xsl=fp.read()))}
示例3: check
def check(self, cr, uid, ids, context=None):
config_obj = self.pool['oo.config']
data = self.read(cr, uid, ids, ['soffice', 'dir_tmp'])[0]
del data['id']
config_id = config_obj.search(cr, 1, [], context=context)
if config_id:
config_obj.write(cr, 1, config_id, data, context=context)
else:
config_id = config_obj.create(cr, 1, data, context=context)
try:
with tools.file_open('report_aeroo_loffice/test_temp.odt', mode='rb') as fp:
file_data = fp.read()
DC = netsvc.Service._services.setdefault(
'openoffice',
OpenOffice_service(cr, data['soffice'], data['dir_tmp'])
)
with aeroo_lock:
DC.putDocument(file_data)
data = DC.saveByStream(u'writer_pdf_Export')
DC.closeDocument()
del DC
except DocumentConversionException, e:
netsvc.Service.remove('openoffice')
error_details = str(e)
state = 'error'
示例4: default_get
def default_get(self, cr, uid, fields_list=None, context=None):
ret = super(base_setup_company, self).default_get(cr, uid, fields_list, context)
if not ret.get('name'):
ret.update({'name': 'MSF', 'street': 'Rue de Lausanne 78', 'street2': 'CP 116', 'city': 'Geneva', 'zip': '1211', 'phone': '+41 (22) 849.84.00'})
company = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id
ret['name'] = company.name
addresses = self.pool.get('res.partner').address_get(cr, uid, company.id, ['default'])
default_id = addresses.get('default', False)
# Default address
if default_id:
address = self.pool.get('res.partner.address').browse(cr, uid, default_id, context=context)
for field in ['street','street2','zip','city','email','phone']:
ret[field] = address[field]
for field in ['country_id','state_id']:
if address[field]:
ret[field] = address[field].id
# Currency
cur = self.pool.get('res.currency').search(cr, uid, [('name','=','EUR')])
if company.currency_id:
ret['currency'] = company.currency_id.id
elif cur:
ret['currency'] = cur[0]
fp = tools.file_open(opj('msf_profile', 'data', 'msf.jpg'), 'rb')
ret['logo'] = base64.encodestring(fp.read())
fp.close()
return ret
示例5: create_states
def create_states(self, cr, uid, state_type, context=None):
"""It imports spanish states information trough an XML file."""
file_name = 'l10n_es_toponyms_states_%s.xml' %state_type
try:
fp = tools.file_open(os.path.join('l10n_es_toponyms', os.path.join('wizard', file_name)))
except IOError, e:
fp = None
示例6: execute_simple
def execute_simple(self, cr, uid, ids, context=None):
if context is None:
context = {}
fy_obj = self.pool.get('account.fiscalyear')
for res in self.read(cr, uid, ids, context=context):
if 'charts' in res and res['charts'] == 'configurable':
#load generic chart of account
fp = tools.file_open(opj('account', 'configurable_account_chart.xml'))
tools.convert_xml_import(cr, 'account', fp, {}, 'init', True, None)
fp.close()
if 'date_start' in res and 'date_stop' in res:
f_ids = fy_obj.search(cr, uid, [('date_start', '<=', res['date_start']), ('date_stop', '>=', res['date_stop']), ('company_id', '=', res['company_id'][0])], context=context)
if not f_ids:
name = code = res['date_start'][:4]
if int(name) != int(res['date_stop'][:4]):
name = res['date_start'][:4] +'-'+ res['date_stop'][:4]
code = res['date_start'][2:4] +'-'+ res['date_stop'][2:4]
vals = {
'name': name,
'code': code,
'date_start': res['date_start'],
'date_stop': res['date_stop'],
'company_id': res['company_id'][0]
}
fiscal_id = fy_obj.create(cr, uid, vals, context=context)
if res['period'] == 'month':
fy_obj.create_period(cr, uid, [fiscal_id])
elif res['period'] == '3months':
fy_obj.create_period3(cr, uid, [fiscal_id])
示例7: check
def check(self, cr, uid, ids, context=None):
config_obj = self.pool.get('oo.config')
data = self.read(cr, uid, ids, ['host', 'port', 'ooo_restart_cmd'])[0]
del data['id']
config_id = config_obj.search(cr, 1, [], context=context)
if config_id:
config_obj.write(cr, 1, config_id, data, context=context)
else:
config_id = config_obj.create(cr, 1, data, context=context)
try:
fp = tools.file_open('report_aeroo_ooo/test_temp.odt', mode='rb')
file_data = fp.read()
DC = netsvc.Service._services.setdefault('openoffice', \
OpenOffice_service(cr, data['host'], data['port']))
with aeroo_lock:
DC.putDocument(file_data)
DC.saveByStream()
fp.close()
DC.closeDocument()
del DC
except DocumentConversionException, e:
netsvc.Service.remove('openoffice')
error_details = str(e)
state = 'error'
示例8: create
def create(self, cr, uid, ids, data, context=None):
pool = pooler.get_pool(cr.dbname)
ir_obj = pool.get('ir.actions.report.xml')
report_xml_ids = ir_obj.search(cr, uid,
[('report_name', '=', self.name[7:])], context=context)
if report_xml_ids:
report_xml = ir_obj.browse(cr, uid, report_xml_ids[0], context=context)
else:
title = ''
rml = tools.file_open(self.tmpl, subdir=None).read()
report_type= data.get('report_type', 'pdf')
class a(object):
def __init__(self, *args, **argv):
for key,arg in argv.items():
setattr(self, key, arg)
report_xml = a(title=title, report_type=report_type, report_rml_content=rml, name=title, attachment=False, header=self.header)
report_type = report_xml.report_type
report_type = 'xls'
if report_type in ['sxw','odt']:
fnct = self.create_source_odt
elif report_type in ['pdf','raw','html']:
fnct = self.create_source_pdf
elif report_type=='html2html':
fnct = self.create_source_html2html
elif report_type == 'xls':
fnct = self.create_source_xls
else:
raise 'Unknown Report Type'
fnct_ret = fnct(cr, uid, ids, data, report_xml, context)
if not fnct_ret:
return (False,False)
return fnct_ret
示例9: upload_report
def upload_report(self, cr, uid, ids, context=None):
from base_report_designer import openerp_sxw2rml
import StringIO
data=self.read(cr,uid,ids)[0]
sxwval = StringIO.StringIO(base64.decodestring(data['file_sxw_upload']))
fp = tools.file_open('normalized_oo2rml.xsl',subdir='addons/base_report_designer/openerp_sxw2rml')
newrmlcontent = str(openerp_sxw2rml.sxw2rml(sxwval, xsl=fp.read()))
report = self.pool.get('ir.actions.report.xml').write(cr, uid, [data['report_id']], {
'report_sxw_content': base64.decodestring(data['file_sxw_upload']),
'report_rml_content': newrmlcontent
})
cr.commit()
data_obj = self.pool.get('ir.model.data')
id2 = data_obj._get_id(cr, uid, 'base_report_designer', 'view_base_report_file_rml')
report = self.pool.get('ir.actions.report.xml').browse(cr, uid, data['report_id'], context=context)
if id2:
id2 = data_obj.browse(cr, uid, id2, context=context).res_id
return {
'view_type': 'form',
'view_mode': 'form',
'res_model': 'base.report.rml.save',
'views': [(id2, 'form')],
'view_id': False,
'type': 'ir.actions.act_window',
'target': 'new',
}
示例10: upgrade_graph
def upgrade_graph(graph, cr, module_list, force=None):
if force is None:
force = []
packages = []
len_graph = len(graph)
for module in module_list:
mod_path = get_module_path(module)
terp_file = get_module_resource(module, '__openerp__.py')
if not terp_file or not os.path.isfile(terp_file):
terp_file = get_module_resource(module, '__terp__.py')
if not mod_path or not terp_file:
logger.notifyChannel('init', netsvc.LOG_WARNING, 'module %s: not found, skipped' % (module))
continue
if os.path.isfile(terp_file) or zipfile.is_zipfile(mod_path+'.zip'):
try:
info = eval(tools.file_open(terp_file).read())
except:
logger.notifyChannel('init', netsvc.LOG_ERROR, 'module %s: eval file %s' % (module, terp_file))
raise
if info.get('installable', True):
packages.append((module, info.get('depends', []), info))
else:
logger.notifyChannel('init', netsvc.LOG_WARNING, 'module %s: not installable, skipped' % (module))
dependencies = dict([(p, deps) for p, deps, data in packages])
current, later = set([p for p, dep, data in packages]), set()
while packages and current > later:
package, deps, data = packages[0]
# if all dependencies of 'package' are already in the graph, add 'package' in the graph
if reduce(lambda x, y: x and y in graph, deps, True):
if not package in current:
packages.pop(0)
continue
later.clear()
current.remove(package)
graph.addNode(package, deps)
node = Node(package, graph)
node.data = data
for kind in ('init', 'demo', 'update'):
if package in tools.config[kind] or 'all' in tools.config[kind] or kind in force:
setattr(node, kind, True)
else:
later.add(package)
packages.append((package, deps, data))
packages.pop(0)
graph.update_from_db(cr)
for package in later:
unmet_deps = filter(lambda p: p not in graph, dependencies[package])
logger.notifyChannel('init', netsvc.LOG_ERROR, 'module %s: Unmet dependencies: %s' % (package, ', '.join(unmet_deps)))
result = len(graph) - len_graph
if result != len(module_list):
logger.notifyChannel('init', netsvc.LOG_WARNING, 'Not all modules have loaded.')
return result
示例11: parse
def parse(self, filename, ids, model, context=None):
if not context:
context={}
# parses the xml template to memory
self.dom = etree.XML(tools.file_open(filename).read())
self.doc = etree.Element(self.dom.tag)
self.parse_tree(ids, model, context)
示例12: create_zipcodes
def create_zipcodes(self, cr, uid, context=None):
"""Import spanish zipcodes information through an XML file."""
file_name = 'l10n_es_toponyms_zipcodes.xml'
try:
fp = tools.file_open(os.path.join('l10n_es_toponyms', os.path.join('wizard', file_name)))
except IOError, e:
fp = None
示例13: init
def init(self, cr):
"""
Load data (product_data.xml) before self
"""
if hasattr(super(purchase_order, self), 'init'):
super(purchase_order, self).init(cr)
logging.getLogger('init').info('HOOK: module product: loading product_data.xml')
pathname = path.join('product', 'product_data.xml')
file = tools.file_open(pathname)
tools.convert_xml_import(cr, 'product', file, {}, mode='init', noupdate=False)
logging.getLogger('init').info('HOOK: module product_attributes: loading data/sale_data.yml')
pathname = path.join('product_attributes', 'data', 'sale_data.yml')
file = tools.file_open(pathname)
tools.convert_yaml_import(cr, 'product_attributes', file, {}, mode='init', noupdate=False)
示例14: create_rml
def create_rml(self, cr, xml, uid, context=None):
if self.tmpl=='' and not self.internal_header:
self.internal_header=True
if not context:
context={}
pool = pooler.get_pool(cr.dbname)
ir_translation_obj = pool.get('ir.translation')
# In some case we might not use xsl ...
if not self.xsl:
return xml
stylesheet_file = tools.file_open(self.xsl)
try:
stylesheet = etree.parse(stylesheet_file)
xsl_path, _ = os.path.split(self.xsl)
for import_child in stylesheet.findall('./import'):
if 'href' in import_child.attrib:
imp_file = import_child.get('href')
_, imp_file = tools.file_open(imp_file, subdir=xsl_path, pathinfo=True)
import_child.set('href', urllib.quote(str(imp_file)))
imp_file.close()
finally:
stylesheet_file.close()
#TODO: get all the translation in one query. That means we have to:
# * build a list of items to translate,
# * issue the query to translate them,
# * (re)build/update the stylesheet with the translated items
def translate(doc, lang):
for node in doc.xpath('//*[@t]'):
if not node.text:
continue
translation = ir_translation_obj._get_source(cr, uid, self.name2, 'xsl', lang, node.text)
if translation:
node.text = translation
if context.get('lang', False):
translate(stylesheet, context['lang'])
transform = etree.XSLT(stylesheet)
xml = etree.tostring(
transform(etree.fromstring(xml)))
return xml
示例15: _add_header
def _add_header(self, node):
nom=self.__class__.__name__
try:
rml_head = tools.file_open('custom/'+nom+'.header.rml',subdir='addons/report_account_fr/report').read()
except:
rml_head = tools.file_open('custom/corporate_rml_header.rml').read()
head_dom = xml.dom.minidom.parseString(rml_head)
node2 = head_dom.documentElement
for tag in node2.childNodes:
if tag.nodeType==tag.ELEMENT_NODE:
found = self._find_node(node, tag.localName)
if found:
if tag.hasAttribute('position') and (tag.getAttribute('position')=='inside'):
found.appendChild(tag)
else:
found.parentNode.replaceChild(tag, found)
return True