我正在开发一个Android应用程序,我想从Odoo服务器中检索数据。
为此,我在Odoo中开发了一个自定义模块,在其中创建了一个控制器。
import json
import xmlrpc.client as xmlrpclib
from odoo import http
from openerp.http import Response
class resUserController(http.Controller):
url = '<my url>'
db = '<name of my database>'
@http.route('/user/login', type='json', method='GET', auth='public')
def get_login(self, **kwargs):
username = kwargs.get('email')
password = kwargs.get('password')
common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(self.url), allow_none=True)
uid = common.authenticate(self.db, username, password, {})
if uid:
Response.status = '200 Succesful operation'
json_result = {'token': uid}
return json.dumps(json_result)
Response.status = '400 Invalid credentials'
return
当我从python脚本中调用它进行尝试时,它可以正常工作,并且我得到一个<Response [200]>
和一个json {u'jsonrpc': u'2.0', u'result': u'{"token": 8}', u'id': None}
,以及我连接到的帐户的ID。
但是我有另一个函数,我在同一控制器中用其他路由调用,但是这次是auth='user'
,因为我希望用户只能看到他有权使用的信息。
@http.route('/user/getInfo', type='json', method='GET', auth='user')
def get_info(self, **kwargs):
uid = 1
password = '<my admin password>'
models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(self.url), allow_none=True)
info = models.execute_kw(self.db, uid, password, 'res.users',
'search_read', [[['id', '=', kwargs.get('token')]]],
{'fields': ['info']})[0]['invite_code']
if info:
Response.status = '200 Succesful operation'
json_result = {'info': info}
return json.dumps(json_result)
Response.status = '404 User not found'
return
当我使用auth='public'
时,此功能工作正常,但是当我使用auth='user'
时,会收到以下json响应:
响应[200]
{ u'jsonrpc': u'2.0', u'id': None, u'error': { u'message': u'Odoo Session Expired', u'code': 100, u'data': { u'debug': u'Traceback (most recent call last): File "/usr/lib/python3/dist-packages/odoo/http.py", line 650, in _handle_exception return super(JsonRequest, self)._handle_exception(exception) File "/usr/lib/python3/dist-packages/odoo/http.py", line 310, in _handle_exception raise pycompat.reraise(type(exception), exception, sys.exc_info()[2]) File "/usr/lib/python3/dist-packages/odoo/tools/pycompat.py", line 87, in reraise raise value File "/usr/lib/python3/dist-packages/odoo/addons/http_routing/models/ir_http.py", line 342, in _dispatch cls._authenticate(func.routing[\'auth\']) File "/usr/lib/python3/dist-packages/odoo/addons/base/ir/ir_http.py", line 117, in _authenticate getattr(cls, "_auth_method_%s" % auth_method)() File "/usr/lib/python3/dist-packages/odoo/addons/base/ir/ir_http.py", line 90, in _auth_method_user raise http.SessionExpiredException("Session expired") odoo.http.SessionExpiredException: Session expired', u'exception_type': u'internal_error', u'message': u'Session expired', u'name': u'odoo.http.SessionExpiredException', u'arguments': [u'Session expired'] } } }
我的工作基于This documentation,这是Odoo的官方文档,但是这里有问题:
1 它要求我在每个功能中写管理员密码,这似乎很危险。
2 身份验证后,我得到了我的用户的ID,但没有会话令牌。然后如何通过auth='user'
通知我的功能我已连接以及与哪个用户有关?
这是我的脚本,可以测试我的通话:
import requests
import json
url_connect = "<my url>/user/login"
url = "<my url>/user/getInfo"
headers = {'Content-Type': 'application/json'}
data_connect = {
"params": {
"email": "<my test account email>",
"password": "<my test account password>",
}
}
data = {
"params": {
"token": <my test account id>,
}
}
data_json = json.dumps(data)
r = requests.get(url=url_connect, data=json.dumps(data_connect), headers=headers)
print(r)
print(r.json())
r = requests.get(url=url, data=data_json, headers=headers)
print(r)
print(r.json())
答案 0 :(得分:2)
注意事项:
以下是使用 / web / session / autenticate 的示例:
import requests
import json
url_connect = "http://localhost:8069/web/session/authenticate"
url = "http://localhost:8069/web/session/get_session_info"
headers = {'Content-Type': 'application/json'}
data_connect = {
"params": {
"db": "demo1",
"login": "admin",
"password": "admin",
}
}
data = {}
session = requests.Session()
r = session.post(url=url_connect, data=json.dumps(data_connect), headers=headers)
if r.ok:
result = r.json()['result']
if result.get('session_id'):
session.cookies['session_id'] = result.get('session_id')
r = session.post(url=url, data=json.dumps(data), headers=headers)
print(r)
print(r.json())
要从您的控制器获取信息,您可以使用request.env.user,它保留当前登录的用户,并且由于您指定auth ='user',因此必须是有效的。示例代码可能类似于:
from odoo.http import request
class UserController(http.Controller):
@http.route('/user/getInfo', type='json', method='POST', auth='user')
def get_info(self, **kwargs):
current_user = request.env.user
Response.status = '200 Succesful operation'
json_result = {'info': current_user.info}
return json.dumps(json_result)
答案 1 :(得分:1)
很好地写问题,您已经完成了作业。这对我来说可以使用api样式请求对移动用户会话进行身份验证。
@http.route([
'/m/login/email',
], type='http', auth="public", website=True, methods=["POST"], csrf=False)
def users_login_email(self, **kwargs):
if kwargs:
data = json.loads(kwargs.keys()[0])
else:
data = json.loads(request.httprequest.data)
email = data.get('email')
password = data.get('password')
if not request.session.db:
setup_db()
uid = request.session.authenticate(request.session.db, email, password)
if uid:
return self._user_details(uid)
body = json.dumps({"body": ["Credenciales Incorrectas"]})
return werkzeug.wrappers.Response(body, status=403, headers=[
('Content-Type', 'application/json'), ('Content-Length', len(body))
])
我也没有使用auth='user'
来让Odoo弄乱重定向和Web东西检查。我在需要经过身份验证的用户返回正确的HTTP错误状态代码的控制器路由中使用此注释包装器
def check_user(f):
@functools.wraps(f)
def wrap(*args, **kwargs):
if not request.session.db:
setup_db()
request.uid = request.session.uid
if not request.uid:
body = json.dumps({"body": ["Session Expired"]})
return werkzeug.wrappers.Response(body, status=403, headers=[
('Content-Type', 'application/json'), ('Content-Length', len(body))
])
return f(*args, **kwargs)
return wrap
您可以这样使用它:
@check_user
@http.route([
'/m/<int:shop_id>/cart/info',
], type='http', auth="public", website=True)
def cart_info(self, shop_id, **kwargs):