Skip to Content
Menu
This question has been flagged
2 Replies
2301 Views

I write an API to create user in odoo database

if I enter username and password for existing user at first time I receive the message that i add in this case in second time i receive conflict message and status code and the server stop receive any thing what ever I request I receive conflict and the problem need restart the server 

any solution ??

my code:

 @http.route('/register',  auth="public",csrf=False, website=True, methods=['POST'],type="json")

    defregister(self,idd= None, **kw):

        un='perla'

        password1 = 'perla'

        db = 'perla'

        body = request.jsonrequest

        username = body['body']['username']

        password = body['body']['password']


        common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(self.url))

        print(common)

        g = True

        try:

            print('uid')
            uid = common.authenticate(db,un, password1, {})

            print(uid)

            print('uid')

        except:

            response = json.dumps({ 'jsonrpc': '2.0', 'message': 'Unauthorized!'})

            return Response(            response, status=401,            headers=[('Content-Type', 'application/json'), ('Content-Length', 100)]                )

           
        if(g== False):

            print("false")

            print(Response)

                     print('false 222 ')


            # return Response

            response = json.dumps({ 'jsonrpc': '2.0', 'message': 'Unauthordecfedceized!'})

            returnResponse(            response, status=401,            headers=[('Content-Type', 'application/json'), ('Content-Length', 100)]

                )

                    else:

            print("else")
            models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(self.url))

            print("EMP")

        try:

            print('try')

            is_there= models.execute_kw(self.db, uid, self.password, 'res.users', 'search_count', [[['login', '=', username]]])

            ifis_there :

                response=json.dumps({ 'jsonrpc': '2.0', 'message': 'This User is already exist'})

                Response.status = '409'

                returnresponse

            else :

                user_id = models.execute_kw(self.db, uid, password1, 'res.users', 'create', [{'name': username, 'password' : password, 'login' :username ,'sel_groups_1_9_10':9, 'sel_groups_25_26_27' : 26,'is_active' :False}])

            print('user_id' + str(user_id))


        exceptExceptionase :

                        response=json.dumps({ 'jsonrpc': '2.0', 'message': 'This User is already exist'})            Response.status = '409'

            return Response( response, status=409,            headers=[('Content-Type', 'application/json'), ('Content-Length', 100)]                )

        ifuser_id :

            date_now = str(datetime.today())

            print('date_now  >>>'  +str(date_now))


            payload = {                'id': user_id,

                'username': username

               'password': password,

                'login' :username ,

                'is_active':False,

                'timestamp' : date_now,}

            # user_details = '{"id" :"%s" , "username" : "%s" , "timestamp":"%s"}'  %(user_id ,username,date_now)

            SECRET='ali.ammar'

            enc = jwt.encode(payload, SECRET)

              new_user_id_count =models.execute_kw(self.db, uid, password1, 'user.token', 'search_count', [[['name' , '=', user_id]]])

              create_user_verification = models.execute_kw(self.db, uid, password1, 'user.verification', 'create', [{'name': user_id,'is_valid' : True}])

            print("create_user_verification" + str(create_user_verification))

            ifnew_user_id_count:

                models.execute_kw(self.db, uid, password1, 'user.token', 'write', [['name' , '=' , user_id], {'token': enc}])

            else :

                models.execute_kw(self.db, uid, password1, 'user.token', 'create', [{'name': user_id, 'token': enc }])

            uid=0

            return json.dumps({"details":payload})

                    else:

            return json.dumps({'Error': "Invalid credentials"})  

Avatar
Discard
Author Best Answer

the error come from werkzeug.wrappers  when I set :

Response.status = '409' 

all Response will blocked 

the solution is in use :

 response = json.dumps({ 'jsonrpc': '2.0', 'message': 'This User is already exist!'})

 return Response(            response, status=409,headers=[('Content-Type', 'application/json'), ('Content-Length', 100)]        )  

Avatar
Discard
Best Answer

hey...
first of all, you DON'T have to use XMLRPC to create new records in the odoo (the controller LIVE in side odoo) 
your can just use some thing like this:

@http.route('/create', auth='public')
    def index(self, **kw):
    s = http.request.env['hr.res'].sudo()
    vals ={
            'name':'bo mohamad',
            'password':'cola_bandora',
           }
    s.create(vals)
second of all, the table 'res.usres' is very sensitive to odoo, you can't create users programmatically.
odoo will redirect you with warning that you can only create users from configuration pannel (which is the res.users table)

Avatar
Discard
Author

the error is not come from create
it com from here uid = common.authenticate(db,un, password1, {})
after tow request it fail the server and go in conflict status

for that specific problem i can tell you this:
1- common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(self.url))
it's preferred to hold the URL of your database in a variable, because "self.url" can change from page to page. try 'localhost:8069' instead.
2- double check the authentication credentials (db , username and password)
3- remove try-catch statement or print the error to have more visual on the error messages
4- avoid using json.dumps and mush as possible. odoo will use this function any way ander the hood for you.

Related Posts Replies Views Activity
0
Dec 24
1
1
Oct 22
4396
2
Jul 22
1193
3
Jun 22
4899
1
May 22
2018