Error Backup odoo - odoo

Any help please I'am beginner in odoo
I do this code for backup (odoo10)
class db_backup_manual(models.Model):
_name = "db.backup.manual.ept"
db_id = fields.Many2one('db.autobackup.ept', required=True, domain=[('active','=','True')], help="Select a database for which you want to generate manual backup.")
def data_save(self, context=None):
data = self.read(self)
#print str(data[0]['db_id'])
confs = self.pool.get('db.autobackup.ept').browse(self,[data[0]['db_id'][0]])
for rec in confs:
db_list = self.pool.get('db.autobackup.ept').get_db_list(self, [], rec.host, rec.port)
if rec.name in db_list:
try:
if not os.path.isdir(rec.backup_dir):
os.makedirs(rec.backup_dir)
except:
raise
result = self.pool.get('db.autobackup.ept').ept_backup(self,[rec.id], rec.name, rec.backup_dir,False,rec.ftp_enable,rec.FTP_id,rec,rec.keep_backup_local)
return {'type': 'ir.actions.act_window_close'}
db_backup_manual()
in line :
confs = self.pool.get('db.autobackup.ept').browse(self,[data[0]['db_id'][0]])
I have this error :
Exception during JSON request handling
KeyError: 'db_id'

Related

Why am I getting 'Key Error' at for my file I am doing

Receiving a key error:
KeyError at /
'entries'
Request Method: GET
Request URL: http://localhost:8000/
Django Version: 3.2.14
Exception Type: KeyError
Exception Value:
'entries'
Exception Location: /home/project/agfzb-CloudAppDevelopment_Capstone/server/djangoapp/restapis.py, line 50, in get_all_dealerships_from_cf
Python Executable: /usr/bin/python3
Python Version: 3.6.9
Python Path:
['/home/project/agfzb-CloudAppDevelopment_Capstone/server',
'/usr/lib/python36.zip',
'/usr/lib/python3.6',
'/usr/lib/python3.6/lib-dynload',
'/home/theia/.local/lib/python3.6/site-packages',
'/usr/local/lib/python3.6/dist-packages',
'/usr/lib/python3/dist-packages']
Error message from Theia Labs:
File "/home/project/agfzb-CloudAppDevelopment_Capstone/server/djangoapp/views.py", line 42, in get_all_dealerships
dealer = get_all_dealerships_from_cf(dealer_url, id=id)
File "/home/project/agfzb-CloudAppDevelopment_Capstone/server/djangoapp/restapis.py", line 50, in get_all_dealerships_from_cf
dealers = json_result["entries"]
KeyError: 'entries'
from my views py file:
get_all_dealerships(request):
if request.method == "GET":
context = {}
dealer_url = "https://2d6871f8.us-south.apigw.appdomain.cloud/api/dealership/dealership"
apikey="xxxxxxxxxxxxxxx"
dealer = get_all_dealerships_from_cf(dealer_url, id=id)
context["dealer"] = dealer
review_url = "https://2d6871f8.us-south.apigw.appdomain.cloud/api/get_review/review"
reviews = get_allReviews_byID_from_cf(review_url, id=id)
print(reviews)
context["reviews"] = reviews
return render(request, 'djangoapp/dealer_details.html', context)
from my restapis file:
def get_all_dealerships_from_cf(url, **kwargs):
results = []
# Call get_request with a URL parameter
json_result = get_request(url)
if json_result:
# Get the row list in JSON as dealers
dealers = json_result["entries"]
# For each dealer object
for dealer in dealers:
# Get its content in `doc` object
dealer_doc = dealer["doc"]
# Create a CarDealer object with values in `doc` object
dealer_obj = CarDealer(address=dealer_doc["address"], city=dealer_doc["city"], id=dealer_doc["id"], lat=dealer_doc["lat"], long=dealer_doc["long"],
short_name=dealer_doc["short_name"],
st=dealer_doc["st"], zip=dealer_doc["zip"])
results.append(dealer_obj)
return results
Can't figure it out...

Unable to use 'read_sql' to call a SQL query class

I am trying to pull results from the database with the following code:
import pandas as pd
import pyodbc
class DataManagement(object):
def __init__(self, database = None, server=None, trusted_connection=True, database_driver=ODBC_SQL2005_2012, uid=None, pwd=None):
self.server = server
self.database = database
self.uid = uid
self.pwd = pwd
# Use default server name none supplied - assumed to be localhost
if self.server is None:
self.server = SERVER
if self.database is None:
self.database = DATABASE
# Use default sql credentials if none provided
if self.uid is None or self.pwd is None:
self.uid = DEFAULT_UID
self.pwd = DEFAULT_PASSWORD
if trusted_connection:
self.connectionstring = "DRIVER={0};SERVER={1};DATABASE={2};Trusted_Connection=yes;".format(database_driver, self.server, self.database)
else:
self.connectionstring = 'DRIVER={0};SERVER={1};DATABASE={2};UID={3};PWD={4};'.format(database_driver, self.server, self.database, uid, pwd)
self.connection = pyodbc.connect(self.connectionstring)
self.cursor = self.connection.cursor()
def __enter__(self):
return self
def __exit__(self, ctx_type, ctx_value, ctx_traceback):
self.connection.commit()
self.connection.close()
qq = DataManagement()
sql =("select * from ***** ")
data_df = pd.read_sql(sql, qq)
I get an error:
Traceback (most recent call last):
File "<ipython-input-94-453876631fe0>", line 3, in <module>
data_df = pd.read_sql(sql, qq)
File "***\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\sql.py", line 380, in read_sql
chunksize=chunksize)
File "***\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\sql.py", line 1468, in read_query
cursor = self.execute(*args)
File "***\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\sql.py", line 1426, in execute
cur = self.con.cursor()
TypeError: 'pyodbc.Cursor' object is not callable
I saw a similar question at TypeError: 'pyodbc.Cursor' object is not callable (Python 3.6) but unable to get an answer from there.
I got it to work by editing the class from
self.cursor = self.connection.cursor()
into
self.cursor = self.connection.cursor

Odoo 9 context value missing in override method

in odoo9 I override the search_read method. The super method works ok. With the data returned I want to make a filter, the filter is on the context, the value was asigned on the click of the button comming from the view.
<button name="status_instalacion" string="Instalación" type="action" icon="fa-wrench fa-2x" context="{'stage_id' : 1, 'current_id': active_id}"/>
The problem occurs when I query the context in the search_read method. It exists but doesn't have the values I placed
context on click of button:
self._context
{u'lang': u'en_US', u'stage_id': 1, u'tz': False, u'uid': 1, u'current_id': 40, u'tipo_validacion': u'Sistemas Cr\xedticos', u'sistema_critico': u'AGUA'}
the stage_id is the value I want
context on read_search:
self._context
{u'lang': u'en_US', u'bin_size': True, u'tipo_validacion': u'Sistemas Cr\xedticos', u'tz': False, u'uid': 1,
u'active_test': False, u'sistema_critico': u'AGUA'}
as you can see the 'stage_id' value is missing
Tried also assigning the value to a property of the class, but the value never changes it is always the initial value.
from logging import getLogger
from openerp import api, fields, models
_logger = getLogger(__name__)
class MgmtsystemSistemasEquipos(models.Model):
""" Equipos."""
_name = 'mgmtsystem.sistemas.equipos'
dmy = 99 # ---> this value never changes
def dummy(self): # ---> tried calling a function. not work
return self.dmy
def set_dummy(self, id): # ----> set the value
self.dmy = id or self.dmy
codigo = fields.Char(
string=u'Código',
help=u"Código equipo",
required=True,
size=30)
name = fields.Char(
string=u'Nombre equipo',
required=True,
readonly=False,
index=True,
help="Nombre corto equipo",
size=30)
stage_id = fields.Many2one(
'mgmtsystem.action.stage',
'Fase',
default=_default_stage,
readonly=True)
#api.multi
def status_instalacion(self):
import pudb
pu.db
# save value to variable dmy to retrieve later
id = self._context.get('stage_id')
self.set_dummy(id)
#api.model
def search_read(
self, domain=None, fields=None, offset=0,
limit=None, order=None):
import pudb
pu.db
# here the variable allways has the original value (99)
current_stage_id = self.dmy
current_stage_id = self.dummy()
current_stage_id = getattr(self, dmy)
res = super(MgmtsystemSistemasEquipos, self).search_read(
domain, fields, offset, limit, order)
current_id = res[0]['id']
valid_protocols_ids = self._get_ids(
current_stage_id, current_id,
'mgmtsystem_equipos_protocolos',
'mgmtsystem_equipos_protocolos_rel',
'protocolo_id')
# # remove ids
res[0]['protocolos_ids'] = valid_protocols_ids
res[0]['informes_ids'] = valid_informes_ids
res[0]['anexos_ids'] = valid_anexos_ids
return res
# #api.multi
def _get_ids(self, current_stage_id, current_id, model, model_rel, field_rel):
import pudb
pu.db
# in this method the value of the variable is allways the original
current_stage_id = self.dummy()
sql = """ select a.id from
%s as a
join %s as b
on a.id = b.%s where b.equipo_id = %s
and a.stage_id = %s; """ % (model, model_rel, field_rel,
current_id, current_stage_id)
import psycopg2
try:
self.env.cr.execute(sql)
except psycopg2.ProgrammingError, ex:
message = 'Error trying to download data from server. \n {0} \n {1}'.format(ex.pgerror, sql)
_logger.info(message)
return False
rows = self.env.cr.fetchall()
list_of_ids = []
for row in rows:
list_of_ids.append(row[0])
return list_of_ids
I don't know Python very well, and thats the cause of my misunderstanding of how to read the value of the variable.
But then again, Why is the context modified in the search_read method?.
Thank you.
You should try following.
#api.model
def search_read(self, domain=None, fields=None, offset=0, limit=None, order=None):
import pudb
pu.db
# Here you need to get the value from the context.
current_stage_id = self._context.get('stage_id', getattr(self, dmy))
res = super(MgmtsystemSistemasEquipos, self).search_read(domain=domain, fields=fields, offset=offset, limit=limit, order=order)
current_id = res[0]['id']
valid_protocols_ids = self._get_ids(
current_stage_id, current_id,
'mgmtsystem_equipos_protocolos',
'mgmtsystem_equipos_protocolos_rel',
'protocolo_id')
# # remove ids
res[0]['protocolos_ids'] = valid_protocols_ids
res[0]['informes_ids'] = valid_informes_ids
res[0]['anexos_ids'] = valid_anexos_ids
return res
In your code those lines won't work just because there is no recordset available in self (it's correct behaviour search_read must have #api.model decorator).
# here the variable allways has the original value (99)
current_stage_id = self.dmy
current_stage_id = self.dummy()
current_stage_id = getattr(self, dmy)
So just remove those and lines and apply some other logic to get data.

How to override create methode in odoo 10

i want to use same create method in odoo 10 as below means i want to convert below code in odoo 10, below code is working well for odoo 8
def create(self, cr, uid, vals, context=None):
phase_obj = self.pool.get('hr_evaluation.plan.phase')
survey_id = phase_obj.read(cr, uid, vals.get('phase_id'), fields=['survey_id'], context=context)['survey_id'][0]
if vals.get('user_id'):
user_obj = self.pool.get('res.users')
partner_id = user_obj.read(cr, uid, vals.get('user_id'), fields=['partner_id'], context=context)['partner_id'][0]
else:
partner_id = None
user_input_obj = self.pool.get('survey.user_input')
if not vals.get('deadline'):
vals['deadline'] = (datetime.now() + timedelta(days=28)).strftime(DF)
ret = user_input_obj.create(cr, uid, {'survey_id': survey_id,
'deadline': vals.get('deadline'),
'type': 'link',
'partner_id': partner_id}, context=context)
vals['request_id'] = ret
return super(hr_evaluation_interview, self).create(cr, uid, vals, context=context)
i am trying below code:
def create(self, vals):
survey_id = self.env['hr_evaluation.plan.phase'].read(vals.get('phase_id'),fields=['survey_id'])['survey_id'][0]
if vals.get('user_id'):
partner_id = self.env['res.users'].read(vals.get('user_id'), fields=['partner_id'])['partner_id'][0]
else:
partner_id = None
if not vals.get('deadline'):
vals['deadline'] = (datetime.now() + timedelta(days=28)).strftime(DF)
ret = self.env['survey.user_input'].create({'survey_id': survey_id,
'deadline': vals.get('deadline'),
'type': 'link',
'partner_id': partner_id})
vals['request_id'] = ret
return super(hr_evaluation_interview, self).create(vals)
but it is giving me error like TypeError: read() got multiple values for keyword argument 'fields' so please guide me how can i remove this error?
read method accept fields as argument and you give it two arguments.
read([fields])
Reads the requested fields for the records in self, low-level/RPC method. In Python code, prefer browse().
Parameters
fields -- list of field names to return (default is all fields)
Returns
a list of dictionaries mapping field names to their values, with one dictionary per record
Raises
AccessError -- if user has no read rights on some of the given records
Instead of calling read method it's better to call browse() method, you can read Browse() vs read() performance in Odoo 8
Your code should be:
def create(self, vals):
survey_id = self.env['hr_evaluation.plan.phase'].browse(vals.get('phase_id'))
if vals.get('user_id'):
partner_id = self.env['res.users'].browse(vals.get('user_id'))
else:
partner_id = None
if not vals.get('deadline'):
vals['deadline'] = (datetime.now() + timedelta(days=28)).strftime(DF)
ret = self.env['survey.user_input'].create({'survey_id': survey_id.id,
'deadline': vals.get('deadline'),
'type': 'link',
'partner_id': partner_id.id})
vals['request_id'] = ret.id
return super(hr_evaluation_interview, self).create(vals)

Auto fill on2many field on form load odoo 8

I have tried to create a functional field with type="one2many" and auto fill on form load. I tried below code:
Code 1:
'flat_members1': fields.function(_get_flat_members, relation="family.info", method=True, type="one2many", multi='flat_fkk'),
def _get_flat_members(self, cr, uid, ids, name, arg, context=None):
cr.execute("Select * from family_info where flat="+str(flat_id)+"")
cr_res = cr.dictfetchall()
res = {}
for data in self.browse(cr,uid,ids):
res[data.id] = self.pool.get('family.info').search(cr,uid,[('flat', '=', flat_id)])
return values
Code 2:
member_ids = []
for res in cr_res:
member_ids.append((0,0,{'name':res.get('name'),
'flat':res.get('flat'),
}))
values.update(family_members1=member_ids)
return values
In both way i got an error:
AttributeError: 'list' object has no attribute 'iteritems'
Please suggest me a solution thanks.
Use Odoo8 new api:
flat_members1 = fields.One2many(compute='_get_flat_members',
comodel_name='family.info',
string='flat_members1',
store=True)
#api.one
#api.depends('flat_id')
def _get_flat_members(self):
member_ids = []
# get member_ids
self.flat_members1 = member_ids