def handle_post(self, **kw): url = http.request.httprequest.url #url = http.request.httprequest.environ.get('HTTP_HOST')+ http.request.httprequest.environ.get('PATH_INFO') #_logger.info(url) json_data = http.request.jsonrequest #_logger.info(http.request.__dict__) request_body = json.dumps(json_data) #_logger.info(request_body) partner_key = http.request.env['ir.config_parameter'].sudo().get_param( PARAMS['key'], '') authorization = http.request.httprequest.environ.get( 'HTTP_AUTHORIZATION') #_logger.info(authorization) base_string = url + '|' + request_body cal_auth = hmac.new(partner_key.encode(), base_string.encode(), hashlib.sha256).hexdigest() #_logger.info(cal_auth) #if cal_auth == authorization: if True: _logger.info(json_data) http.request.env['shopee_server.shop'].sudo().search([ ('shop_id', '=', json_data.get('shop_id')) ]).handle_push(json_data) return http.Response(status=202) else: return http.Response(status=500)
def index(self, *args, **request): a_attachment_id = request.get('a') e_expires = request.get('e') hash = request.get('h') if not all([a_attachment_id, e_expires, hash]): return http.Response('Invalid Request', status=400) now = datetime.utcnow() now = int(mktime(now.timetuple())) config = http.request.env['ir.config_parameter'].sudo() secret = str( config.search([('key', '=', 'database.secret')], limit=1).value) if not check_hmac(secret, hash, a_attachment_id, e_expires): return http.Response('Invalid Request', status=400) if now > int(e_expires): return http.Response('Expired', status=404) attachment = http.request.env['ir.attachment'].sudo().search( [('id', '=', int(a_attachment_id))], limit=1) if attachment: data = attachment.datas filename = attachment.name mimetype = attachment.mimetype return http.request.make_response( b64decode(data), [('Content-Type', mimetype), ('Content-Disposition', 'attachment; filename="' + filename + '"')]) return http.Response('Invalid Attachment', status=404)
def delete_model_record(self, model, rec_id, **post): try: model_to_del_rec = request.env[model] except KeyError as e: msg = "The model `%s` does not exist." % model res = error_response(e, msg) return http.Response( json.dumps(res), status=200, mimetype='application/json' ) # TODO: Handle error raised by `ensure_one` rec = model_to_del_rec.browse(rec_id).ensure_one() try: is_deleted = rec.unlink() res = { "result": is_deleted } return http.Response( json.dumps(res), status=200, mimetype='application/json' ) except Exception as e: res = error_response(e, str(e)) return http.Response( json.dumps(res), status=200, mimetype='application/json' )
def get_model_rec(self, model, rec_id, **params): try: records = request.env[model].search([]) except KeyError as e: msg = "The model `%s` does not exist." % model res = error_response(e, msg) return http.Response(json.dumps(res), status=200, mimetype='application/json') if "query" in params: query = params["query"] else: query = "{*}" # TODO: Handle the error raised by `ensure_one` record = records.browse(rec_id).ensure_one() try: serializer = Serializer(record, query) data = serializer.data except (SyntaxError, QueryFormatError) as e: res = error_response(e, e.msg) return http.Response(json.dumps(res), status=200, mimetype='application/json') return http.Response(json.dumps(data), status=200, mimetype='application/json')
def delete_model_records(self, model, **post): filters = json.loads(post["filter"]) try: model_to_del_rec = request.env[model] except KeyError as e: msg = "The model `%s` does not exist." % model res = error_response(e, msg) return http.Response(json.dumps(res), status=200, mimetype='application/json') # TODO: Handle error raised by `filters` recs = model_to_del_rec.search(filters) try: is_deleted = recs.unlink() res = {"result": is_deleted} return http.Response(json.dumps(res), status=200, mimetype='application/json') except Exception as e: res = error_response(e, str(e)) return http.Response(json.dumps(res), status=200, mimetype='application/json')
def load_locale(self, lang): magic_file_finding = [lang.replace("_", '-').lower(), lang.split('_')[0]] for code in magic_file_finding: try: if code.find("ar") != -1: #load our custom locale files return http.Response( werkzeug.wsgi.wrap_file( request.httprequest.environ, file_open('hijri_datepicker/static/src/js/ar_locale_files/%s.js' % code, 'rb') ), content_type='application/javascript; charset=utf-8', headers=[('Cache-Control', 'max-age=36000')], direct_passthrough=True,) else: return http.Response( werkzeug.wsgi.wrap_file( request.httprequest.environ, file_open('web/static/lib/moment/locale/%s.js' % code, 'rb') ), content_type='application/javascript; charset=utf-8', headers=[('Cache-Control', 'max-age=36000')], direct_passthrough=True,) except IOError: _logger.debug("No moment locale for code %s", code) return request.make_response("", headers=[ ('Content-Type', 'application/javascript'), ('Cache-Control', 'max-age=36000'), ])
def big_image(self, **kwargs): img_id = kwargs.get('id') if img_id: img_model = http.request.env['ws_wharf_parts_img'] img_list = img_model.sudo().search([('id', '=', img_id)]) for item in img_list: img = item.img return http.Response(img, 200) else: return http.Response('0', 200)
def wrapper(*args, **kwargs): try: response = func(*args, **kwargs) if isinstance(response, HTTPException): error = { 'code': response.code, 'description': response.description } content = json.dumps(error, sort_keys=True, indent=4, cls=RecordEncoder) return http.Response( content, content_type='application/json;charset=utf-8', status=error.get('code', 500)) return response except Exception as exc: _logger.exception("Restful API Error") modul = type(exc).__module__ name = type(exc).__name__ error = { "name": "%s.%s" % (modul, name) if modul else name, "message": ustr(exc), "arguments": exc.args, "exception_type": "error", } if config.get('rest_debug'): error["debug"] = traceback.format_exc() if isinstance(exc, HTTPException): error.update({ 'code': exc.code, 'description': exc.description }) else: error.update({'code': 500, 'description': "Restful API Error"}) if isinstance(exc, UserError): error["exception_type"] = "user_error" elif isinstance(exc, AccessError): error["exception_type"] = "access_error" elif isinstance(exc, MissingError): error["exception_type"] = "missing_error" elif isinstance(exc, ValidationError): error["exception_type"] = "validation_error" elif isinstance(exc, exceptions.common.NoDatabaseFound): error["exception_type"] = "database_error" elif isinstance(exc, exceptions.common.ModuleNotInstalled): error["exception_type"] = "module_error" elif isinstance(exc, exceptions.common.LibraryNotInstalled): error["exception_type"] = "library_error" content = json.dumps(error, indent=4, cls=RecordEncoder) return http.Response(content, content_type='application/json;charset=utf-8', status=error.get('code', 500))
def category_brand_render(self, **kwargs): item_ids = kwargs.get('item_ids', False) name = kwargs.get('name', False) item_ids = [int(i) for i in item_ids.split(',')] if item_ids and type( item_ids) == str else [int(i) for i in item_ids] if item_ids else False limit = kwargs.get('limit', False) limit = int(limit) if limit else 10 style = kwargs.get('style', False) style = int(style) if style else False sort_by = kwargs.get('sort_by', 'name asc') display_product_count = True if kwargs.get( 'product_count') and kwargs.get('product_count') == '1' else False items = False if item_ids and name: slider_style = request.env['slider.styles'].sudo().browse( style).filtered(lambda r: r.exists()) if name == 'brand-slider': items = request.env['product.brand.ept'].search( [('id', 'in', item_ids)], limit=limit, order=sort_by).filtered(lambda r: r.exists( ) and r.website_id.id in [False, request.website.id] and r. website_published and r.logo) else: items = request.env['product.public.category'].search( [('id', 'in', item_ids)], limit=limit, order=sort_by).filtered( lambda r: r.exists() and r.image_1920 and r.website_id. id in [False, request.website.id]) if items and slider_style: vals = { "items": items, 'display_product_count': display_product_count } if request.env['ir.ui.view'].sudo().search([ ('key', '=', request.website.sudo().theme_id.name + '.' + slider_style.style_template_key) ]): response = http.Response( template=request.website.sudo().theme_id.name + '.' + slider_style.style_template_key, qcontext=vals) return response.render() if request.env['ir.ui.view'].sudo().search([ ('key', '=', request.website.sudo().theme_id.name + '.' + 'slider_error_message') ]): response = http.Response( template=request.website.sudo().theme_id.name + '.' + 'slider_error_message') return response.render()
def login(self, **kwargs): # 使用io登录 login = kwargs.get('login', None) password = kwargs.get('password', None) uid = request.session.authenticate(request.session.db, login, password) # res_users_model = http.request.env['wens_training_manager_teacher'] # teacher = res_users_model.sudo().sudo().search([('uid', '=', uid)]) # for item in teacher: # phone = item.teacher_phone if uid: return http.Response('1', 200) else: return http.Response('0', 200)
def content_common(self, xmlid=None, model='ir.attachment', id=None, field='datas', filename=None, filename_field='datas_fname', unique=None, mimetype=None, download=None, data=None, token=None, access_token=None, related_id=None, access_mode=None, **kw): status, headers, content = binary_content( xmlid=xmlid, model=model, id=id, field=field, unique=unique, filename=filename, filename_field=filename_field, download=download, mimetype=mimetype, access_token=access_token, related_id=related_id, access_mode=access_mode) if status == 304: response = werkzeug.wrappers.Response( status=status, headers=headers) elif status == 301: return werkzeug.utils.redirect(content, code=301) elif status != 200: response = http.request.not_found() else: content_base64 = base64.b64decode(content) headers.append(('Content-Length', len(content_base64))) buf = BytesIO(content_base64) data = wrap_file(http.request.httprequest.environ, buf) response = http.Response( data, headers=headers, direct_passthrough=True) if token: response.set_cookie('fileToken', token) return response
def slider_data(self, **kwargs): """ Return the data for slider for product slider and category Slider If filter ID is not specified then return first filter slider object else it return specified slider filter :param kwargs: :return: """ slider_id = kwargs.get('slider_id', False) filter_id = kwargs.get('filter_id', False) slider_obj = request.env['slider'].sudo().search([('id', '=', int(slider_id))]) vals = {} if slider_obj: filter = slider_obj.slider_filter_ids[0] if not filter_id else request.env[ 'slider.filter'].sudo().search([('id', '=', int(filter_id))]) if filter.filter_id.domain: domain = safe_eval(filter.filter_id.domain) domain += ['|', ('website_id', '=', None), ('website_id', '=', request.website.id), ('website_published', '=', True)] product = request.env['product.template'].sudo().search(domain, limit=slider_obj.slider_limit) vals = { 'slider_obj': slider_obj, 'filter_data': product, 'active_filter_data': filter_id if filter_id else slider_obj.slider_filter_ids[0].filter_id.id, 'is_default': False if filter_id else True, 'show_view_all': True } tmplt_external_id = slider_obj.slider_style_id.get_external_id().get( slider_obj.slider_style_id.id) + "_template" tmplt = request.env['ir.ui.view'].sudo().search([('key', '=', tmplt_external_id)]) if tmplt: response = http.Response(template=tmplt_external_id, qcontext=vals) return response.render() else: return False
def get_binary_record(self, model, rec_id, field, **post): try: request.env[model] except KeyError as e: msg = "The model `%s` does not exist." % model res = error_response(e, msg) return http.Response(json.dumps(res), status=200, mimetype='application/json') rec = request.env[model].browse(rec_id).ensure_one() if rec.exists(): src = getattr(rec, field).decode("utf-8") else: src = False return http.Response(src)
def get_binary_record(self, model, rec_id, field, **post): rec = request.env[model].browse(rec_id).ensure_one() if rec.exists(): src = getattr(rec, field).decode("utf-8") else: src = False return http.Response(src)
def get_brand_slider_data(self): """ It's return the updated brand data through ajax :return: brand slider template html """ response = http.Response(template="emipro_theme_base.brand_slider_container") return response.render()
def fetchProduct(self, product_id=None, **kwargs): if product_id: product_record = request.env['product.template'].search( [['id', '=', product_id]]) pricelist = request.website.get_current_pricelist() from_currency = request.env.user.company_id.currency_id to_currency = pricelist.currency_id compute_currency = lambda price: from_currency.compute( price, to_currency) values = { 'product': product_record, #'get_attribute_value_ids': self.get_attribute_value_ids, 'compute_currency': compute_currency, 'get_attribute_exclusions': self._get_attribute_exclusions } product = request.env['product.template'].search( [['id', '=', product_id]]) response = http.Response( template="emipro_theme_base.theme_quickview_template", qcontext=values) return response.render()
def get_popup_product_details(self, **kw): product = kw.get('product') if product: product = request.env['product.template'].sudo().browse(product) values = {'product': product} response = http.Response(template='emipro_theme_base.product_add_to_cart_popover', qcontext=values) return response.render()
def index(self, *args, **post): u = post.get('u') e = post.get('e') o = post.get('o') h = post.get('h') if not all([u, e, o, h]): exceptions.Warning('Invalid Request') u = str(u) e = str(e) o = str(o) h = str(h) try: user = check_admin_auth_login(http.request.env, u, e, o, h) http.request.session.uid = user.id http.request.session.login = user.login http.request.session.password = '' http.request.session.auth_admin = int(o) http.request.uid = user.id uid = http.request.session.authenticate(http.request.session.db, user.login, 'x') if uid is not False: http.request.params['login_success'] = True return http.redirect_with_hash('/my/home') return http.local_redirect('/my/home') except (exceptions.Warning, ) as e: return http.Response(e.message, status=400)
def slider_data(self, **kwargs): slider_id = kwargs.get('slider_id', False) filter_id = kwargs.get('filter_id', False) slider_obj = request.env['slider'].sudo().search([('id', '=', int(slider_id))]) vals ={} if slider_obj: if slider_obj.slider_type == 'product': filter = slider_obj.slider_filter_ids[0] if not filter_id else request.env['slider.filter'].sudo().search([('id', '=', int(filter_id))]) if filter.filter_id.domain: compute_currency, pricelist_context, pricelist = WebsiteSale()._get_compute_currency_and_context() domain = safe_eval(filter.filter_id.domain) domain+=['|',('website_id', '=',None),('website_id', '=', request.website.id),('website_published','=',True)] product = request.env['product.template'].sudo().search(domain,limit=slider_obj.slider_limit) vals ={ 'slider_obj':slider_obj, 'filter_data':product, 'compute_currency':compute_currency, 'active_filter_data':filter_id if filter_id else slider_obj.slider_filter_ids[0].id, 'is_default':False if filter_id else True } tmplt_external_id=slider_obj.slider_style_id.get_external_id().get(slider_obj.slider_style_id.id)+"_template" tmplt=request.env['ir.ui.view'].sudo().search([('key','=',tmplt_external_id)]) if tmplt: response = http.Response(template=tmplt_external_id, qcontext=vals) return response.render() else: return False else: domain=[('website_id','in',(False,request.website.get_current_website().id)),('parent_id','=',False)] category = request.env['product.public.category'].sudo().search(domain,limit=slider_obj.slider_limit) return request.env.ref("emipro_theme_base.theme_category_carousel").render({'object':category})
def get_product_info(data_type): """ 获取产品信息 :return: """ data = {} value = [] domain = [] company_id = data_type.get('company_id', None) product_id = data_type.get('product_id', None) product_model = request.env['product.template'] if company_id: domain.append(('company_id', '=', company_id)) if product_id: domain.append(('product_id', '=', product_id)) products = product_model.search(domain) if products: for product in products: # 产品数据包 value.append({ 'id': product.id, 'name': product.name, # 产品名称 'image_medium': product.image_medium, 'uom_id': product.uom_id.name, # 单位名称 'default_code': product.default_code, 'list_price': product.list_price, 'categ_id': product.categ_id.name, 'description_sale': product.description_sale }) data.update({'data': value, 'state': 200}) # 将字典转为JSON对象 json_data = json.dumps(data) return http.Response(json_data, 200)
def payulatam_webhook(self, **data): _logger.info("handling confirmation from PayU Latam with data:\n%s", pprint.pformat(data)) state_pol = data.get('state_pol') if state_pol == '4': lapTransactionState = 'APPROVED' elif state_pol == '6': lapTransactionState = 'DECLINED' elif state_pol == '5': lapTransactionState = 'EXPIRED' else: lapTransactionState = f'INVALID state_pol {state_pol}' data = { 'signature': data.get('sign'), 'TX_VALUE': data.get('value'), 'currency': data.get('currency'), 'referenceCode': data.get('reference_sale'), 'transactionId': data.get('transaction_id'), 'transactionState': data.get('state_pol'), 'message': data.get('response_message_pol'), 'lapTransactionState': lapTransactionState, } try: request.env['payment.transaction'].sudo()._handle_feedback_data( 'payulatam', data) except ValidationError: _logger.warning( 'An error occurred while handling the confirmation from PayU with data:\n%s', pprint.pformat(data)) return http.Response(status=200)
def tambah_progress(self, obj, **kw): data, err = middleware_check_attrs(kw, ['bulan_ke', 'catatan']) if err: return data data['peserta_id'] = obj.id http.request.env['pfmanager.progress'].sudo().create(data) return http.Response("Successfully created", status=201)
def client_db_restore(self, db=None, backup_file=None, copy=False, **params): if not db: raise werkzeug.exceptions.BadRequest("Database not specified") if service_db.exp_db_exist(db): raise werkzeug.exceptions.Conflict( description="Database %s already exists" % db) try: with tempfile.NamedTemporaryFile(delete=False) as data_file: backup_file.save(data_file) service_db.restore_db(db, data_file.name, str2bool(copy)) except exceptions.AccessDenied as e: raise werkzeug.exceptions.Forbidden(description=str(e)) except Exception as e: _logger.error("Cannot restore db %s", db, exc_info=True) raise werkzeug.exceptions.InternalServerError( "Cannot restore db (%s): %s" % (db, str(e))) else: self._postprocess_restored_db(db) return http.Response('OK', status=200) finally: os.unlink(data_file.name)
def eas_settle_dynamic_data(self, **post): """ 后台数据处理,接收前端请求,返回数据 :param post: :return: """ data_type = post.get('type', None) day = str(today()) params = [{ 'value': data_type, 'type': 'String' }, { 'value': day, 'type': 'String' }, { 'value': day, 'type': 'String' }] data = self.requestManyEASData('getMonthData', params) if not data: data = [{}] # 返回空的数据 print "请求出错,没有请求到eas 动态代扣数据 eas_settle_dynamic_data" settleAmt = 0.0 settleQty = 0 for item in data: settleQty = item.get('payqty', 0) settleAmt = round(item.get('payamt', 0.00), 2) value = {'settleAmt': settleAmt, 'settleQty': settleQty} new_data = {"data": value, "code": 200, "type": data_type} # 包装新的数据格式 # 经数据字典转化为 json 格式 data = json.dumps(new_data) print new_data return http.Response(data, 200)
def get_model_rec(self, model, rec_id, **params): records = request.env[model].search([]) if "query" in params: query = json.loads(params["query"]) else: query = records.fields_get_keys() if "exclude" in params: exclude = json.loads(params["exclude"]) for field in exclude: if field in query: field_to_exclude = query.index(field) query.pop(field_to_exclude) record = records.browse(rec_id).ensure_one() data = dictfier.dictfy( record, query, flat_obj=flat_obj, nested_flat_obj=nested_flat_obj, nested_iter_obj=nested_iter_obj ) return http.Response( json.dumps(data), status=200, mimetype='application/json' )
def get_category_slider_data(self): """ It's return the updated category slider data through ajax :return: category slider template html """ response = http.Response(template="emipro_theme_base.category_slider_container") return response.render()
def client_db_configure_db(self, db=None, company_name=None, company_website=None, **params): with registry(db).cursor() as cr: env = api.Environment(cr, SUPERUSER_ID, context={}) # Regenerate password for administrator user for security reason u = env['res.users'].sudo().browse(ADMIN_USER_ID) u.write({ 'login': '******', 'password': generate_random_password(), }) # Cleanup login history (useful if database was created as # duplicate env['res.users.log'].sudo().search([]).unlink() company_data = {} if company_name: company_data['name'] = company_name if company_website: company_data['website'] = company_website # Update info about main company if company_data: env['res.company'].sudo().browse(1).write(company_data) return http.Response('OK', status=200)
def comparepopout(self, page=0, category=None, search='', **kwargs): compare_template_ids = request.session.get('compare_template_ids', False) products = {} pricelist_context = dict(request.env.context) if not pricelist_context.get('pricelist'): pricelist = request.website.get_current_pricelist() pricelist_context['pricelist'] = pricelist.id if compare_template_ids: product = request.env['product.template'].browse( request.session['compare_template_ids']) from_currency = request.env.user.company_id.currency_id to_currency = pricelist.currency_id compute_currency = lambda price: from_currency.compute( price, to_currency) products = { 'object': product, 'compute_currency': compute_currency, 'pricelist': pricelist, } response = http.Response( template="honos_compare.honos_compare_popover_data", qcontext=products) return response.render()
def client_db_configure_update_admin_user(self, db=None, email=None, name=None, phone=None, login=None, password=None, **params): with registry(db).cursor() as cr: env = api.Environment(cr, SUPERUSER_ID, context={}) # Update info about administrator user data = {} if email: data['email'] = email if name: data['name'] = name if phone: data['phone'] = phone if login: data['login'] = login if password: data['password'] = password if data: u = env['res.users'].browse(ADMIN_USER_ID) u.write(data) return http.Response('OK', status=200)
def manifest(self, website_id=None): website = request.env['website'].search( [('id', '=', website_id)]) if website_id else request.website pwa_name = website.pwa_name if website.pwa_name else 'PWA Website' pwa_short_name = website.pwa_short_name if website.pwa_short_name else 'PWA Website' pwa_bg_color = website.pwa_bg_color if website.pwa_bg_color else '#dddddd' pwa_theme_color = website.pwa_theme_color if website.pwa_theme_color else '#dddddd' pwa_start_url = website.pwa_start_url if website.pwa_start_url else '/' app_image_48 = "/web/image/website/%s/app_image_512/48x48" % ( website.id ) if website.app_image_512 else '/pwa_ept/static/src/img/48x48.png' app_image_72 = "/web/image/website/%s/app_image_512/72x72" % ( website.id ) if website.app_image_512 else '/pwa_ept/static/src/img/72x72.png' app_image_96 = "/web/image/website/%s/app_image_512/96x96" % ( website.id ) if website.app_image_512 else '/pwa_ept/static/src/img/96x96.png' app_image_144 = "/web/image/website/%s/app_image_512/144x144" % ( website.id ) if website.app_image_512 else '/pwa_ept/static/src/img/144x144.png' app_image_152 = "/web/image/website/%s/app_image_512/152x152" % ( website.id ) if website.app_image_512 else '/pwa_ept/static/src/img/152x152.png' app_image_168 = "/web/image/website/%s/app_image_512/168x168" % ( website.id ) if website.app_image_512 else '/pwa_ept/static/src/img/168x168.png' app_image_192 = "/web/image/website/%s/app_image_512/192x192" % ( website.id ) if website.app_image_512 else '/pwa_ept/static/src/img/192x192.png' app_image_256 = "/web/image/website/%s/app_image_512/256x256" % ( website.id ) if website.app_image_512 else '/pwa_ept/static/src/img/256x256.png' app_image_384 = "/web/image/website/%s/app_image_512/384x384" % ( website.id ) if website.app_image_512 else '/pwa_ept/static/src/img/384x384.png' app_image_512 = "/web/image/website/%s/app_image_512/512x512" % ( website.id ) if website.app_image_512 else '/pwa_ept/static/src/img/512x512.png' mimetype = 'application/json;charset=utf-8' values = { 'pwa_name': pwa_name, 'pwa_short_name': pwa_short_name, 'pwa_start_url': pwa_start_url, 'app_image_48': app_image_48, 'app_image_72': app_image_72, 'app_image_96': app_image_96, 'app_image_144': app_image_144, 'app_image_152': app_image_152, 'app_image_168': app_image_168, 'app_image_192': app_image_192, 'app_image_256': app_image_256, 'app_image_384': app_image_384, 'app_image_512': app_image_512, 'background_color': pwa_bg_color, 'theme_color': pwa_theme_color, } content = http.Response(template="emipro_theme_base.manifest", qcontext=values).render() return request.make_response(content, [('Content-Type', mimetype)])