I need to get the data from relational table and check whether the given data is there. I used this code tho do that. Even though there is a search data it gives result as false.
user_category_id = self.env['ir.module.category'].search([('name', '=', 'Company')])
user_new_id = self.env['res.groups'].search(
[('category_id', '=', user_category_id.id),('name','=',"Manager")])
query = """SELECT p.gid from res_groups_users_rel p where p.uid=%d """ % user_id.id
self.env.cr.execute(query)
result = self.env.cr.fetchall()
print result
if user_tiq_id in result:
print "True"
else:
print "false"
Please help me to solve this error
get count instead of select...
user_id= self.env['res.users'].search([('id','=',self.env.user.id)])
user_category_id = self.env['ir.module.category'].search([('name', '=', 'Company')])
user_new_id = self.env['res.groups'].search(
[('category_id', '=', user_category_id.id),('name','=',"Manager")]).id
query = """select COUNT(*) from res_groups_users_rel where uid=%d and gid=%d """ % (user_id.id,user_tiq_id)
self.env.cr.execute(query)
result = self.env.cr.fetchall()
json_result = json.dumps(result, ensure_ascii=False)
count = json_result.strip('\' \" [] ')
str_count = str(count)
int_count = int(str_count)
if int_count==0:
print "fail"
else:
print "pass"
Related
I am getting an error "unhashable dict" for tmp_str = [{category : name }]. category and name are variables.
Tried options are
tmp_str = [{category : name }]
tmp_str = {category : name }
Complete code is here
def isAttributesIntheName(file_name,message):
table = db_client.Table(table_name)
count = table.item_count
json_msg = json.dumps(message)
print (json_msg)
numCount = 0
loop = 0
print (count)
for numCount in range (count):
name = table.scan()['Items'][numCount]['name']
result = file_name.lower().find(name)
category = table.get_item(Key={'name':name})
if result > 0:
tmp_str = [{category : name }]
json_str1 = dict(**json_str,**{tmp_str })
loop = loop + 1
print (json.dumps(json_str1))
For the specific error you are asking about, the variable category (results of querying your database table) is not a hashable type - e.g. is mutable type such as a dict or list. Dict keys need to be immutable so they can be hashed form a hash key.
It looks like you are querying a DynamoDB and the datatype returned by get_item is a dict, and within that dict there is a key 'Item' that has the data you are requesting in another dict. Here are the docs for get_item:
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html#DynamoDB.Table.get_item
Here is more info on "hashable":
What does "hashable" mean in Python?
I did the code for insert records from so_parts table to so_bo table using Query...How can I use ORM method to do this kind of job. Is there any other way(best)to do that? Here is my code`
`
#api.multi
def save_rapair_parts(self, vals):
#get todays date and convert it to string
created_date = datetime.datetime.today().strftime("%m/%d/%Y")
str_date = str(created_date)
so_p_id = self.so_p_id.id
bo_status = self.bo_status
so_part_t = self.so_part_t
so_part_sno = self.so_part_sno
product = self.so_part_product
product_str = 'Repair '+str(product)
part_id = self.id
bench_order_table.search(['id','bo_sno','created_date','bo_number','rep_description','bo_status'])
#insert details intoso bench orders
`
if so_part_t=='r_b':
try:
sequence = self.env['ir.sequence'].next_by_code('so.benchorder') or '/'
str_sequence = str(sequence)
query = """SELECT so_work_authorization FROM my_depots_so WHERE id=%d """ % (so_p_id)
self.env.cr.execute(query)
result = self.env.cr.fetchall()
result_number = json.dumps(result, ensure_ascii=False)
strip_number = result_number.strip('\' \" [] ')
work_auth_no = str(strip_number)
work_auth_no += "-"
work_auth_no += str_sequence
insert ="""INSERT INTO my_depots_so_bo(id,so_bo_id,bo_sno,created_date,bo_number,rep_description,bo_status) values %s """
parameters = (part_id,so_p_id,so_part_sno,str_date,work_auth_no,product_str,bo_status)
self.env.cr.execute(insert,(parameters,))
my_depots_bo(id,bo_sno,created_date,bo_number,rep_description,bo_status) values %s """
# self.env.cr.execute(insert_query, (parameters,))
except Exception:
print "Error in inserting values"`
yes there is a better way because when you use ORM
method you also checks access right for user to:
for your select query:
rec = self.env['my.depots.so'].search_read(['id', '=', so_p_id], ['so_work_authorization'])
if rec:
rec = rec[0] # search_read return a list of dictionary
so_work_authorization = rec['so_work_authorization']
# and do what ever you want with the result
# to create
# call create method witch accept a dictionary
# field_name : value
new_rec = self.env['my.depots.so.bo'].create({
'so_bo_id': so_p_id, # many2one must be an integer value
'bo_sno': bo_nso_value,
'bo_number': value_of_number,
# ....
# ....
# add al field
}) # create return the new created record as model object
for inserting use: self.env['model.name'].create(vals)
for updating use : self.env['model.name'].write(vals)
using ORM method makes sure that user don't pass the security access rigths
Hope you get the idea
So this is my code it is strying tomease car registration plates, start times and end times (In the complete code it would be printed at the bottom).
data = str(list)
sdata = str(list)
edata = str(list)
current = 0
repeats = input ('How many cars do you want to measure?')
def main():
global current
print (current)
print ''
print ''
print '---------------------------------------'
print '---------------------------------------'
print 'Enter the registration number.'
data[current] = raw_input(' ')
print 'Enter the time it passed Camera 1. In this form HH:MM:SS'
sdata[current] = raw_input(' ')
print 'Enter the time it passed Camera 2. In this form HH:MM:SS'
edata[current] = raw_input (' ')
print '---------------------------------------'
print''
print''
print''
print 'The Registration Number is :'
print data[current]
print''
print 'The Start Time Is:'
print sdata[current]
print''
print 'The End Time Is:'
print edata[current]
print''
print''
raw_input('Press enter to confirm.')
print'---------------------------------------'
d = d + 1
s = s + 1
a = a + 1
current = current = 1
while current < repeats:
main()
When I run it and it gets to:
data[current] = raw_input(' ')
I get the error message 'TypeError: 'str' object does not support item assignment'
Thank you in advance for the help. :D
The error is clear. str object does not support item assignment
Strings in python are immutable. You have converted the data to a string when you do
data = str(list)
So, by
data["current"] = raw_input()
you are trying to assign some value to a string, which is not supported in python.
If you want data to be a list,
data = list()
or
data = []
will help, thus preventing the error
Dont use str during assignment
data = str(list)
sdata = str(list)
edata = str(list)
Instead use
data = []
sdata = []
edata = []
and later while printing use str if u want
print str(data[current])
as aswin said its immutable so dont complex it
I am trying to use web2py to build an app. I have a simple print function that a user submits a key word . The string or int key word is directed to an sqlite db to retrieve a row and output the data. I need to know
1. how to use the print on html.
2. How to split the string...so far i did the list:string
Here is my code:
def first():
form = SQLFORM.factory(Field('visitor_name',
label = 'Please Type Your keyword here!',
requires= [IS_NOT_EMPTY(), IS_LOWER(),'list:string']))
form.element('input[type=submit]')['_onclick'] = "return \
confirm('Are you sure you want to submit:');"
if form.process().accepted:
session.visitor_name = form.vars.visitor_name
redirect(URL('main'))
return dict(form=form)
def main():
while True:
name = request.vars.visitor_name or redirect(URL('first'))
name2 = name[:]
for item in name2:break
name3 = ' '.join(name2)
import sqlite3
id = 0
location = ""
conn = sqlite3.connect("keywords.db")
c = conn.cursor()
c.execute('select * from kmedicals')
records = c.fetchall()
for record in records:
id = record[0]
location = record[15]
if id == name3:
print name3.capitalize(),':' '\n',location
break
sys.exit()
return dict(name=name)
my view...default/main.html:
{{extend 'layout.html'}}
{{=name}}
I'm trying to do a Raw SELECT in Django using LIKE in the PostgreSQL database with Psycopg2 driver.
I've tested pretty much what I've found on the web, but nothing have worked.
The situation is the following. I need to perform a SELECT like this:
select distinct on (name, adm1.name, adm2.name_local)
gn.geonameid,
case when altnm.iso_language = 'pt' then altnm.alternate_name else gn.name end as name,
adm1.name as zona,
adm2.name_local as municipio
from location_geonameslocal gn
join location_geonameszone adm1 on adm1.code = gn.country || '.' || gn.admin1
join location_geonamesmunicipality adm2 on adm2.code = gn.country || '.' || gn.admin1 || '.' || gn.admin2
left join location_geonamesalternatenames altnm on altnm.geonameid = gn.geonameid
where
(gn.fclass = 'P' or gn.fclass = 'A')
and (altnm.iso_language = 'pt' or altnm.iso_language = 'link' or altnm.iso_language is null or altnm.iso_language = '')
and gn.country = 'PT'
and (gn.name like '%Lisboa%' or altnm.alternate_name like '%Lisboa%')
order by name, adm1.name, adm2.name_local;
The important/problem part of the SELECT is this one:
and (gn.name like '%Lisboa%' or altnm.alternate_name like '%Lisboa%')
I've write a simple view to test the SELECT, it looks like this:
def get_citiesjson_view(request):
word = "Lisboa"
term = "%" + word + "%"
cursor = connection.cursor()
cursor.execute("select distinct on (name, adm1.name, adm2.name_local)\
gn.geonameid,\
case when altnm.iso_language = 'pt' then altnm.alternate_name else gn.name end as name,\
adm1.name as zona,\
adm2.name_local as municipio\
from location_geonameslocal gn\
join location_geonameszone adm1 on adm1.code = gn.country || '.' || gn.admin1\
join location_geonamesmunicipality adm2 on adm2.code = gn.country || '.' || gn.admin1 || '.' || gn.admin2\
left join location_geonamesalternatenames altnm on altnm.geonameid = gn.geonameid\
where\
(gn.fclass = 'P' or gn.fclass = 'A')\
and (altnm.iso_language = 'pt' or altnm.iso_language = 'link' or altnm.iso_language is null or altnm.iso_language = '')\
and gn.country = 'PT'\
and (gn.name like %s or altnm.alternate_name like %s)\
order by name, adm1.name, adm2.name_local;", [term, term])
data = cursor.fetchone()
mimetype = 'application/json'
return HttpResponse(data, mimetype)
Unfortunately this does not work and I can't find way to make it work. Some clues?
UPDATE: This form is actually working:
cursor.execute("... and (gn.name like %s or altnm.alternate_name like %s)... ", ['%'+term+'%', '%'+term+'%'])
This form is actually working:
cursor.execute("... and (gn.name like %s or altnm.alternate_name like %s)... ", ['%'+term+'%', '%'+term+'%'])
You should not use the default Python formatting to construct SQL query with parameters, to use the raw SQL LIKE clause you could do something like this:
sql = 'SELECT id FROM table WHERE 1 = 1'
params = []
if 'descricao' in args.keys(): # your validation
# build sql query and params correctly
sql += ' AND descricao LIKE %s'
params.append('%'+args['descricao']+'%')
with connections['default'].cursor() as cursor:
cursor.execute(sql, params)
This way you will be safe agaist SQL Injection vulnerability