예제 #1
0
 def set_value(self, model, field, record_id, value):
     ctime = time.strftime("%Y-%m-%d %H:%M:%S")
     db = get_connection()
     db.execute(
         "DELETE FROM field_cache WHERE model=%s AND field=%s AND record_id=%s",
         model, field, record_id)
     db.execute(
         "INSERT INTO field_cache (model,field,record_id,value,ctime) VALUES (%s,%s,%s,%s,%s)",
         model, field, record_id, utils.json_dumps(value), ctime)
예제 #2
0
def get_report_jasper(report, data, params={}, format="pdf"):
    report_path = _get_report_path(report)
    data2 = conv_jasper_data(data, report_path)
    params = {
        "report": report_path,
        "format": format,
        "data": utils.json_dumps(data2),
    }
    url = "http://localhost:9990/"
    r = requests.post(url, data=params)
    report_dir = os.path.dirname(report_path)
    shutil.rmtree(report_dir)
    if r.status_code != 200:
        raise Exception("Failed to download report (%s)" % r.status_code)
    return r.content
예제 #3
0
파일: report.py 프로젝트: nfco/netforce
def get_report_jasper(report, data, params={}, format="pdf"):
    report_path = _get_report_path(report)
    data2 = conv_jasper_data(data, report_path)
    params = {
        "report": report_path,
        "format": format,
        "data": utils.json_dumps(data2),
    }
    url = "http://localhost:9990/"
    r = requests.post(url, data=params)
    report_dir = os.path.dirname(report_path)
    shutil.rmtree(report_dir)
    if r.status_code != 200:
        raise Exception("Failed to download report (%s)" % r.status_code)
    return r.content
예제 #4
0
def report_render_jsx(tmpl_body, data, orientation="portrait"):
    print("report_render_jsx", data)
    tmpl_path = "/tmp/template.jsx"
    f = open(tmpl_path, "wb")
    f.write(tmpl_body.encode("utf-8"))
    f.close()
    params = {
        "template": tmpl_path,
        "data": utils.json_dumps(data),
        "orientation": orientation,
    }
    url = "http://localhost:9991/"
    r = requests.post(url, data=params, timeout=15)
    if r.status_code != 200:
        raise Exception("Failed to render JSX report (%s)" % r.status_code)
    return r.content
예제 #5
0
파일: report.py 프로젝트: nfco/netforce
def report_render_jsx(tmpl_body, data, orientation="portrait"):
    print("report_render_jsx", data)
    tmpl_path="/tmp/template.jsx"
    f=open(tmpl_path,"wb")
    f.write(tmpl_body.encode("utf-8"))
    f.close()
    params = {
        "template": tmpl_path,
        "data": utils.json_dumps(data),
        "orientation": orientation,
    }
    url = "http://localhost:9991/"
    r = requests.post(url, data=params, timeout=15)
    if r.status_code != 200:
        raise Exception("Failed to render JSX report (%s)" % r.status_code)
    return r.content
예제 #6
0
def get_report_jasper_multi_page(report, datas, params={}, format="pdf"):
    print("get_report_jasper_multi_page")
    report_path = _get_report_path(report)
    datas2 = [conv_jasper_data(data, report_path) for data in datas]
    params = {
        "report": report_path,
        "format": format,
        "multi_page": True,
    }
    for i, data in enumerate(datas2):
        params["data_%d" % i] = utils.json_dumps(data)
    print("params", params)
    url = "http://localhost:9990/"
    r = requests.post(url, data=params)
    report_dir = os.path.dirname(report_path)
    shutil.rmtree(report_dir)
    if r.status_code != 200:
        raise Exception("Failed to download report (%s)" % r.status_code)
    return r.content
예제 #7
0
파일: report.py 프로젝트: nfco/netforce
def get_report_jasper_multi_page(report, datas, params={}, format="pdf"):
    print("get_report_jasper_multi_page")
    report_path = _get_report_path(report)
    datas2 = [conv_jasper_data(data, report_path) for data in datas]
    params = {
        "report": report_path,
        "format": format,
        "multi_page": True,
    }
    for i, data in enumerate(datas2):
        params["data_%d" % i] = utils.json_dumps(data)
    print("params", params)
    url = "http://localhost:9990/"
    r = requests.post(url, data=params)
    report_dir = os.path.dirname(report_path)
    shutil.rmtree(report_dir)
    if r.status_code != 200:
        raise Exception("Failed to download report (%s)" % r.status_code)
    return r.content
예제 #8
0
    def post(self):
        req = json.loads(self.request.body.decode())
        # open("/tmp/json_rpc.log","a").write(self.request.body.decode()+"\n###############################################################\n")
        db = database.get_connection()
        if db:
            db.begin()
        try:
            clear_cache()
            method = req["method"]
            params = req["params"]
            if method == "execute":
                model = params[0]
                method = params[1]
                if method.startswith("_"):
                    raise Exception("Invalid method")
                args = params[2]
                if len(params) >= 4:
                    opts = params[3] or {}
                else:
                    opts = {}
                user_id = access.get_active_user()
                rpc_log.info(
                    "EXECUTE db=%s model=%s method=%s user=%s" % (database.get_active_db(), model, method, user_id)
                )
                m = get_model(model)
                f = getattr(m, method)
                ctx = {"request_handler": self, "request": self.request}
                ctx.update(self.get_cookies())
                opts.setdefault("context", {}).update(ctx)
                with timeout(seconds=300):  # XXX: can make this faster? (less signal sys handler overhead)
                    t0 = time.time()
                    res = f(*args, **opts)
                    t1 = time.time()
                    dt = (t1 - t0) * 1000
                    rpc_log.info("<<< %d ms" % dt)
                resp = {"result": res, "error": None, "id": req["id"]}
            else:
                raise Exception("Invalid method: %s" % method)
            if db:
                db.commit()
        except Exception as e:
            try:
                msg = translate(str(e))
            except:
                print("WARNING: Failed to translate error message")
                msg = str(e)
            rpc_log.error(msg)
            if db:
                db.rollback()
            rpc_log.error(traceback.format_exc())
            err = {"message": msg}
            error_fields = getattr(e, "error_fields", None)
            if error_fields:
                err["error_fields"] = error_fields
            resp = {"result": None, "error": err, "id": req["id"]}
        access.clear_active_user()
        try:
            data = json_dumps(resp)
            self.add_header("Access-Control-Allow-Origin", "*")
            self.write(data)
        except:
            print("JSONRPC ERROR: invalid response")
            from pprint import pprint

            pprint(resp)
            traceback.print_exc()
예제 #9
0
 def get(self):
     db = get_connection()
     try:
         ctx = self.context
         website_id=self.request.headers.get("X-Website-ID")
         if website_id:
             website_id=int(website_id)
         else:
             res=get_model("website").search([["state","=","active"]])
             if not res:
                 raise Exception("No website found")
             website_id=res[0]
         self.website_id=website_id
         website=get_model("website").browse(website_id)
         browse_ctx={
             "website_id": website.id,
             "theme_id": website.theme_id.id,
             "sale_channel_id": website.sale_channel_id.id,
             "pricelist_id": website.sale_channel_id.pricelist_id.id if website.sale_channel_id else None,
         }
         user_id=self.get_cookie("user_id",None)
         if user_id:
             user_id=int(user_id)
             user=get_model("base.user").browse(user_id)
             contact = user.contact_id
             pricelist_ids=[website.sale_channel_id.pricelist_id.id]
             if contact.groups:
                 for group in contact.groups:
                     if group.sale_price_list_id:
                         pricelist_ids.append(group.sale_price_list_id.id)
             browse_ctx["pricelist_ids"]=pricelist_ids
         product_id = self.get_argument("product_id")
         product_id = int(product_id)
         prod = get_model("product").browse([product_id],context=browse_ctx)[0]
         if not prod.is_published and not access.check_permission_other("ecom_preview_product"):
             raise Exception("Product is not published")
         ctx["product"] = prod
         prod_vals = {
             "name": prod.name,
             "code": prod.code,
             "decription": prod.description,
             "image": prod.image,
             "sale_price": prod.customer_price,
             "variants": [],
             "images": [],
             "custom_options": [],
             "attributes": [],
             "type": prod.type,
         }
         if prod.customer_has_discount:
             prod_vals["old_price"] = prod.sale_price
         for img in prod.images:
             img_vals = {
                 "image": img.image,
                 "title": img.title,
             }
             prod_vals["images"].append(img_vals)
         for var in prod.variants:
             var_vals = {
                 "id": var.id,
                 "name": var.name,
                 "price": var.customer_price,
                 "stock_qty": var.stock_qty,
                 "image": var.image,
                 "images": [prod_image.image for prod_image in var.images],
                 "attributes": [],
             }
             if var.customer_has_discount:
                 var_vals["old_price"] = var.sale_price
             for attr in var.attributes:
                 attr_vals = {
                     "name": attr.attribute_id.name if attr.attribute_id else None,
                     "code": attr.attribute_id.code if attr.attribute_id else None,
                     "value": attr.option_id.code if attr.option_id else None,
                 }
                 var_vals["attributes"].append(attr_vals)
             prod_vals["variants"].append(var_vals)
         for attr in prod.attributes:
             attr_vals = {
                 "name": attr.attribute_id.name if attr.attribute_id else None,
                 "code": attr.attribute_id.code if attr.attribute_id else None,
                 "value": attr.option_id.code if attr.option_id else None,
             }
             prod_vals["attributes"].append(attr_vals)
         ctx["parent_categ_list"] = list_categ_parent(prod.categ_id, categ_list=[])
         ctx["product_json"] = utils.json_dumps(prod_vals)
         content = render("ecom_product", ctx)
         ctx["content"] = content
         html = render("cms_layout", ctx)
         self.write(html)
         db.commit()
     except:
         self.redirect("/cms_page_not_found")
         import traceback
         traceback.print_exc()
         db.rollback()
예제 #10
0
 def post(self):
     req = json.loads(urllib.parse.unquote(self.get_argument("request")))
     db = database.get_connection()
     if db:
         db.begin()
     try:
         clear_cache()
         method = req["method"]
         params = req["params"]
         if method == "execute":
             model = params[0]
             method = params[1]
             if method.startswith("_"):
                 raise Exception("Invalid method")
             args = params[2]
             if len(params) >= 4:
                 opts = params[3] or {}
             else:
                 opts = {}
             user_id = access.get_active_user()
             rpc_log.info("EXECUTE db=%s model=%s method=%s user=%s" %
                          (database.get_active_db(), model, method, user_id))
             m = get_model(model)
             f = getattr(m, method)
             ctx = {
                 "request_handler": self,
                 "request": self.request,
             }
             ctx.update(self.get_cookies())
             opts.setdefault("context", {}).update(ctx)
             with timeout(seconds=300):  # XXX: can make this faster? (less signal sys handler overhead)
                 t0 = time.time()
                 res = f(*args, **opts)
                 t1 = time.time()
                 dt = (t1 - t0) * 1000
                 rpc_log.info("<<< %d ms" % dt)
             resp = {
                 "result": res,
                 "error": None,
                 "id": req["id"],
             }
         else:
             raise Exception("Invalid method: %s" % method)
         db = database.get_connection()
         if db:
             db.commit()
     except Exception as e:
         try:
             msg = translate(str(e))
         except:
             print("WARNING: Failed to translate error message")
             msg = str(e)
         rpc_log.error(msg)
         db = database.get_connection()
         if db:
             db.rollback()
         rpc_log.error(traceback.format_exc())
         err = {
             "message": msg,
         }
         error_fields = getattr(e, "error_fields", None)
         if error_fields:
             err["error_fields"] = error_fields
         resp = {
             "result": None,
             "error": err,
             "id": req["id"],
         }
     access.clear_active_user()
     try:
         data = urllib.parse.quote(json_dumps(resp))
     except:
         print("JSONRPC ERROR: invalid response")
         from pprint import pprint
         pprint(resp)
     print("json_rpc_iframe result", data)
     self.write(data)
예제 #11
0
 def get(self):
     db = get_connection()
     try:
         ctx = self.context
         website_id = self.request.headers.get("X-Website-ID")
         if website_id:
             website_id = int(website_id)
         else:
             res = get_model("website").search([["state", "=", "active"]])
             if not res:
                 raise Exception("No website found")
             website_id = res[0]
         self.website_id = website_id
         website = get_model("website").browse(website_id)
         browse_ctx = {
             "website_id":
             website.id,
             "theme_id":
             website.theme_id.id,
             "sale_channel_id":
             website.sale_channel_id.id,
             "pricelist_id":
             website.sale_channel_id.pricelist_id.id
             if website.sale_channel_id else None,
         }
         user_id = self.get_cookie("user_id", None)
         if user_id:
             user_id = int(user_id)
             user = get_model("base.user").browse(user_id)
             contact = user.contact_id
             pricelist_ids = [website.sale_channel_id.pricelist_id.id]
             if contact.groups:
                 for group in contact.groups:
                     if group.sale_price_list_id:
                         pricelist_ids.append(group.sale_price_list_id.id)
             browse_ctx["pricelist_ids"] = pricelist_ids
         product_id = self.get_argument("product_id")
         product_id = int(product_id)
         prod = get_model("product").browse([product_id],
                                            context=browse_ctx)[0]
         if not prod.is_published and not access.check_permission_other(
                 "ecom_preview_product"):
             raise Exception("Product is not published")
         ctx["product"] = prod
         prod_vals = {
             "name": prod.name,
             "code": prod.code,
             "decription": prod.description,
             "image": prod.image,
             "sale_price": prod.customer_price,
             "variants": [],
             "images": [],
             "custom_options": [],
             "attributes": [],
             "type": prod.type,
         }
         if prod.customer_has_discount:
             prod_vals["old_price"] = prod.sale_price
         for img in prod.images:
             img_vals = {
                 "image": img.image,
                 "title": img.title,
             }
             prod_vals["images"].append(img_vals)
         for var in prod.variants:
             var_vals = {
                 "id": var.id,
                 "name": var.name,
                 "price": var.customer_price,
                 "stock_qty": var.stock_qty,
                 "image": var.image,
                 "images": [prod_image.image for prod_image in var.images],
                 "attributes": [],
             }
             if var.customer_has_discount:
                 var_vals["old_price"] = var.sale_price
             for attr in var.attributes:
                 attr_vals = {
                     "name":
                     attr.attribute_id.name if attr.attribute_id else None,
                     "code":
                     attr.attribute_id.code if attr.attribute_id else None,
                     "value":
                     attr.option_id.code if attr.option_id else None,
                 }
                 var_vals["attributes"].append(attr_vals)
             prod_vals["variants"].append(var_vals)
         for attr in prod.attributes:
             attr_vals = {
                 "name":
                 attr.attribute_id.name if attr.attribute_id else None,
                 "code":
                 attr.attribute_id.code if attr.attribute_id else None,
                 "value": attr.option_id.code if attr.option_id else None,
             }
             prod_vals["attributes"].append(attr_vals)
         ctx["parent_categ_list"] = list_categ_parent(prod.categ_id,
                                                      categ_list=[])
         ctx["product_json"] = utils.json_dumps(prod_vals)
         content = render("ecom_product", ctx)
         ctx["content"] = content
         html = render("cms_layout", ctx)
         self.write(html)
         db.commit()
     except:
         self.redirect("/cms_page_not_found")
         import traceback
         traceback.print_exc()
         db.rollback()
예제 #12
0
 def set_value(self, model, field, record_id, value):
     ctime = time.strftime("%Y-%m-%d %H:%M:%S")
     db = get_connection()
     db.execute("DELETE FROM field_cache WHERE model=%s AND field=%s AND record_id=%s", model, field, record_id)
     db.execute("INSERT INTO field_cache (model,field,record_id,value,ctime) VALUES (%s,%s,%s,%s,%s)",
                model, field, record_id, utils.json_dumps(value), ctime)
예제 #13
0
파일: json_rpc.py 프로젝트: nfco/netforce
 def get(self):
     db = database.get_connection()
     if db:
         db.begin()
     try:
         clear_cache()
         print(self)
         method = self.get_argument("method")
         model = self.get_argument("model")
         if method.startswith("_"):
             raise Exception("Invalid method")
         args = self.get_argument("args",None)
         if args:
             args=json.loads(args)
         else:
             args=[]
         opts = self.get_argument("opts",None)
         if opts:
             opts=json.loads(opts)
         else:
             opts={}
         cookies = self.get_argument("cookies",None)
         if cookies:
             cookies = json.loads(cookies)
         else:
             cookies = {}
         if "locale" in cookies:
             set_active_locale(cookies["locale"])
         user_id = access.get_active_user()
         rpc_log.info("EXECUTE db=%s model=%s method=%s user=%s" %
                      (database.get_active_db(), model, method, user_id))
         m = get_model(model)
         f = getattr(m, method)
         ctx = {
             "request_handler": self,
             "request": self.request,
         }
         ctx.update(self.get_cookies())
         opts.setdefault("context", {}).update(ctx)
         with timeout(seconds=900):  # XXX: can make this faster? (less signal sys handler overhead)
             t0 = time.time()
             res = f(*args, **opts)
             t1 = time.time()
             dt = (t1 - t0) * 1000
             rpc_log.info("<<< %d ms" % dt)
         resp = {
             "result": res,
             "error": None,
             "id": self.get_argument("id"),
         }
         if db:
             db.commit()
     except Exception as e:
         try:
             msg = translate(str(e))
         except:
             print("WARNING: Failed to translate error message")
             msg = str(e)
         rpc_log.error(msg)
         if db:
             db.rollback()
         rpc_log.error(traceback.format_exc())
         err = {
             "message": msg,
         }
         error_fields = getattr(e, "error_fields", None)
         if error_fields:
             err["error_fields"] = error_fields
         resp = {
             "result": None,
             "error": err,
             "id": self.get_argument("id",None),
         }
     access.clear_active_user()
     try:
         data = json_dumps(resp)
         self.add_header("Access-Control-Allow-Origin","*")
         self.add_header("Last-Modified",datetime.utcnow())
         self.write(data)
     except:
         print("JSONRPC ERROR: invalid response")
         from pprint import pprint
         pprint(resp)
         traceback.print_exc()
예제 #14
0
 def post(self):
     req = json.loads(self.request.body.decode())
     # open("/tmp/json_rpc.log","a").write(self.request.body.decode()+"\n###############################################################\n")
     db = database.get_connection()
     if db:
         db.begin()
     try:
         clear_cache()
         method = req["method"]
         params = req["params"]
         if method == "execute":
             model = params[0]
             method = params[1]
             if method.startswith("_"):
                 raise Exception("Invalid method")
             args = params[2]
             if len(params) >= 4:
                 opts = params[3] or {}
             else:
                 opts = {}
             if len(params) >= 5:
                 cookies = params[4] or {}
             else:
                 cookies = {}
             if "locale" in cookies:
                 set_active_locale(cookies["locale"])
             if "user_id" in cookies:
                 user_id = int(cookies["user_id"])
                 token = cookies.get("token")
                 dbname = database.get_active_db()
                 schema = database.get_active_schema()
                 if check_token(dbname, user_id, token, schema=schema):
                     access.set_active_user(user_id)
             user_id = access.get_active_user()
             rpc_log.info(
                 "EXECUTE db=%s model=%s method=%s user=%s" %
                 (database.get_active_db(), model, method, user_id))
             m = get_model(model)
             f = getattr(m, method)
             ctx = {
                 "request_handler": self,
                 "request": self.request,
             }
             ctx.update(self.get_cookies())
             ctx.update(cookies)
             ctx.update(opts.get("context", {}))
             opts["context"] = ctx
             with timeout(
                     seconds=900
             ):  # XXX: can make this faster? (less signal sys handler overhead)
                 t0 = time.time()
                 res = f(*args, **opts)
                 t1 = time.time()
                 dt = (t1 - t0) * 1000
                 rpc_log.info("<<< %d ms" % dt)
             resp = {
                 "result": res,
                 "error": None,
                 "id": req["id"],
             }
         else:
             raise Exception("Invalid method: %s" % method)
         if db:
             db.commit()
     except Exception as e:
         try:
             msg = translate(str(e))
         except:
             print("WARNING: Failed to translate error message")
             msg = str(e)
         rpc_log.error(msg)
         if db:
             db.rollback()
         rpc_log.error(traceback.format_exc())
         err = {
             "message": msg,
         }
         error_fields = getattr(e, "error_fields", None)
         if error_fields:
             err["error_fields"] = error_fields
         resp = {
             "result": None,
             "error": err,
             "id": req["id"],
         }
     access.clear_active_user()
     try:
         data = json_dumps(resp)
         self.add_header("Access-Control-Allow-Origin", "*")
         self.write(data)
     except:
         print("JSONRPC ERROR: invalid response")
         from pprint import pprint
         pprint(resp)
         traceback.print_exc()
예제 #15
0
 def get(self):
     db = database.get_connection()
     if db:
         db.begin()
     try:
         clear_cache()
         print(self)
         method = self.get_argument("method")
         model = self.get_argument("model")
         if method.startswith("_"):
             raise Exception("Invalid method")
         args = self.get_argument("args", None)
         if args:
             args = json.loads(args)
         else:
             args = []
         opts = self.get_argument("opts", None)
         if opts:
             opts = json.loads(opts)
         else:
             opts = {}
         cookies = self.get_argument("cookies", None)
         if cookies:
             cookies = json.loads(cookies)
         else:
             cookies = {}
         if "locale" in cookies:
             set_active_locale(cookies["locale"])
         user_id = access.get_active_user()
         rpc_log.info("EXECUTE db=%s model=%s method=%s user=%s" %
                      (database.get_active_db(), model, method, user_id))
         m = get_model(model)
         f = getattr(m, method)
         ctx = {
             "request_handler": self,
             "request": self.request,
         }
         ctx.update(self.get_cookies())
         opts.setdefault("context", {}).update(ctx)
         with timeout(
                 seconds=900
         ):  # XXX: can make this faster? (less signal sys handler overhead)
             t0 = time.time()
             res = f(*args, **opts)
             t1 = time.time()
             dt = (t1 - t0) * 1000
             rpc_log.info("<<< %d ms" % dt)
         resp = {
             "result": res,
             "error": None,
             "id": self.get_argument("id"),
         }
         if db:
             db.commit()
     except Exception as e:
         try:
             msg = translate(str(e))
         except:
             print("WARNING: Failed to translate error message")
             msg = str(e)
         rpc_log.error(msg)
         if db:
             db.rollback()
         rpc_log.error(traceback.format_exc())
         err = {
             "message": msg,
         }
         error_fields = getattr(e, "error_fields", None)
         if error_fields:
             err["error_fields"] = error_fields
         resp = {
             "result": None,
             "error": err,
             "id": self.get_argument("id", None),
         }
     access.clear_active_user()
     try:
         data = json_dumps(resp)
         self.add_header("Access-Control-Allow-Origin", "*")
         self.add_header("Last-Modified", datetime.utcnow())
         self.write(data)
     except:
         print("JSONRPC ERROR: invalid response")
         from pprint import pprint
         pprint(resp)
         traceback.print_exc()