def __decode_tuple_response(self, ctr_res): status_code = None headers = Headers() cks = cookies.SimpleCookie() body = None for item in ctr_res: if isinstance(item, int): if status_code is None: status_code = item elif isinstance(item, Headers): headers.update(item) elif isinstance(item, cookies.BaseCookie): cks.update(item) elif type(item) in (str, dict, StaticFile, bytes): if body is None: body = item return status_code, headers, cks, body
def __get_params_(self, arg, arg_type, val=None, type_check=True): if val is not None: kws = {"val": val} else: kws = {} if arg_type == Request: param = self.request elif arg_type == Session: param = self.request.get_session(True) elif arg_type == Response: param = self.response elif arg_type == Headers: param = Headers(self.request.headers) elif arg_type == RegGroups: param = RegGroups(self.request.reg_groups) elif arg_type == Header: param = self.__build_header(arg, **kws) elif inspect.isclass(arg_type) and issubclass(arg_type, cookies.BaseCookie): param = self.request.cookies elif arg_type == Cookie: param = self.__build_cookie(arg, **kws) elif arg_type == MultipartFile: param = self.__build_multipart(arg, **kws) elif arg_type == Parameter: param = self.__build_param(arg, **kws) elif arg_type == PathValue: param = self.__build_path_value(arg, **kws) elif arg_type == Parameters: param = self.__build_params(arg, **kws) elif arg_type == RegGroup: param = self.__build_reg_group(**kws) elif arg_type == JSONBody: param = self.__build_json_body() elif arg_type == str: param = self.__build_str(arg, **kws) elif arg_type == bool: param = self.__build_bool(arg, **kws) elif arg_type == int: param = self.__build_int(arg, **kws) elif arg_type == float: param = self.__build_float(arg, **kws) elif arg_type in (list, List, List[str], List[Parameter], List[int], List[float], List[bool], List[dict], List[Dict]): param = self.__build_list(arg, target_type=arg_type, **kws) elif arg_type == ModelDict: param = self.__build_model_dict() elif arg_type in (dict, Dict): param = self.__build_dict(arg, **kws) elif type_check: raise HttpError( 400, f"Parameter[{arg}] with Type {arg_type} is not supported yet.") else: param = val return param
def my_ctrl4(user_name, password=Parameter(name="passwd", required=True), remember_me=True, locations=[], json_param={}, lcs=Parameters(name="locals", required=True), content_type=Header("Content-Type", default="application/json"), connection=Header("Connection"), ua=Header("User-Agent"), headers=Headers() ): return f"""<!DOCTYPE html>
def html(path_val=PathValue()): with open(dt.path + "html/" + path_val, "r", encoding="utf-8") as f: read = f.read() f.close() ext = path_val[(path_val.rfind(".") + 1):] if ext == "html" or ext == "css": mime = "text/" + ext elif ext == "js": mime = "text/javascript" elif ext == "json": mime = "application/json" else: mime = "application/octet-stream" return 200, Headers({"Content-Type": mime}), read
def __prepare_kwargs(self): kwargs = _get_kwargs_(self.__controller) if kwargs is None: return None kwarg_vals = {} for k, v in kwargs.items(): if v is None: kwarg_vals[k] = self.__build_str(k, v) elif isinstance(v, Request): kwarg_vals[k] = self.request elif isinstance(v, Response): kwarg_vals[k] = self.response elif isinstance(v, Headers): kwarg_vals[k] = Headers(self.request.headers) elif isinstance(v, Header): kwarg_vals[k] = self.__build_header(k, v) elif isinstance(v, cookies.BaseCookie): kwarg_vals[k] = self.request.cookies elif isinstance(v, Cookie): kwarg_vals[k] = self.__build_cookie(k, v) elif isinstance(v, MultipartFile): kwarg_vals[k] = self.__build_multipart(k, v) elif isinstance(v, Parameter): kwarg_vals[k] = self.__build_param(k, v) elif isinstance(v, PathValue): kwarg_vals[k] = self.__build_path_value(k, v) elif isinstance(v, Parameters): kwarg_vals[k] = self.__build_params(k, v) elif isinstance(v, JSONBody): kwarg_vals[k] = self.__build_json_body() elif isinstance(v, str) or isinstance(v, unicode): kwarg_vals[k] = self.__build_str(k, v) elif isinstance(v, bool): kwarg_vals[k] = self.__build_bool(k, v) elif isinstance(v, int): kwarg_vals[k] = self.__build_int(k, v) elif isinstance(v, long): kwarg_vals[k] = self.__build_long(k, v) elif isinstance(v, list): kwarg_vals[k] = self.__build_list(k, v) elif isinstance(v, dict): kwarg_vals[k] = self.__build_dict(k, v) else: kwarg_vals[k] = v return kwarg_vals
def tuple_with_cookies(headers=Headers(), all_cookies=Cookies(), cookie_sc=Cookie("sc")): print("=====>headers") print(headers) print("=====> cookies ") print(all_cookies) print("=====> cookie sc ") print(cookie_sc) print("======<") import datetime expires = datetime.datetime(2018, 12, 31) cks = Cookies() # cks = cookies.SimpleCookie() # you could also use the build-in cookie objects cks["ck1"] = "keijack" cks["ck1"]["path"] = "/" cks["ck1"]["expires"] = expires.strftime(Cookies.EXPIRE_DATE_FORMAT) return 200, Header({"xx": "yyy"}), cks, "<html><body>OK</body></html>"
def settings(): data = "<body>\n" data += fn.header("تنظیمات") data += '<center id="main">\n' data += '<div id="settings">\n' data += ' <ul class="list-group">\n' for tfr in fn.all_timeframes: checked = "" for ctf in dt.config["timeframes"]: if tfr["name"] == ctf["name"]: checked = " checked" data += ' <label class="form-check-label text-light" for="check_' + tfr["name"] + '">' \ + '<li class="list-group-item list-group-item-action list-group-item-dark">' \ + '<input class="form-check-input" type="checkbox" value="" id="check_' + tfr["name"] + '"' \ + checked + '><span>' + tfr["visName"] + '<span></li></label>\n' data += ' </ul>\n' data += '</div>\n' data += '</center>\n' data += '<script type="text/javascript" src="./html/settings.js"></script>\n' data += "</body>" htm = fn.template("سام: تنظیمات", "settings", data) return 200, Headers({"Content-Type": "text/html"}), htm
def search(): if classifier is not None and classifier.active: return "installing... please wait..." c = dt.cur(True) c.execute("SELECT id, name, branch FROM symbol") every = list(c) dt.cur(False) every.sort(key=lambda k: k[1]) data = "<body>\n" data += '<center id="header">\n' data += ' <input type="text" id="search" placeholder="جستجو">\n' data += '</center>\n' data += '<center id="main">\n' for s in every: data += '<p onclick="goTo(\'' + str(s[2]) + '\', \'' + str(s[0]) + '\');">' \ + str(every.index(s) + 1) + '. ' + s[1] + '</p>\n' data += '</center>\n' data += '<script type="text/javascript" src="./html/search.js"></script>\n' data += "</body>" htm = fn.template("سام: جستجو", "search", data) return 200, Headers({"Content-Type": "text/html"}), htm
def index(): if not dt.mofid: data = "<body>\n" data += fn.header("ورود به مفید تریدر") with open(dt.path + "html/login.html", "r", encoding="utf-8") as f: data += f.read() f.close() data += '<script type="text/javascript" src="./html/login.js"></script>\n' data += "</body>" htm = fn.template("سام: ورود به مفید تریدر", "login", data) return 200, Headers({"Content-Type": "text/html"}), htm global classifier if classifier is not None and classifier.active: status = "installing" else: c = dt.cur(True) c.execute("SELECT name FROM sqlite_master WHERE type ='table' AND name NOT LIKE 'sqlite_%';") tables = fn.tables(c) dt.cur(False) all_set = True for k, v in fn.required_tables.items(): if k not in tables: all_set = False else: c = dt.cur(True) c.execute("SELECT id FROM " + k) rowCount = len(list(c)) fuck_all = False if rowCount <= dt.config["minimumRowInRequiredTables"]: for kk in fn.required_tables.keys(): c.execute("DROP TABLE IF EXISTS " + kk) all_set = False fuck_all = True dt.cur(False) if fuck_all: break if all_set: status = "yes" else: status = "no" if status == "no": with open(dt.path + "html/installing.html", "r", encoding="utf-8") as f: installing = f.read() f.close() htm = fn.template("سام: راه اندازی", "install") htm = htm.replace("<center />", installing) elif status == "yes": data = "<body>\n" data += '<img src="./html/img/settings_1.png" class="fixedIcon" id="settings" ' \ + 'data-bs-toggle="dropdown" aria-expanded="false">' data += '<ul class="dropdown-menu dropdown-menu-dark" aria-labelledby="settings">\n' \ + ' <li class="dropdown-item" onclick="updateAll();">ازسرگیری کلی</li>\n' \ + ' <li class="dropdown-item" onclick="reset();">نصب و راه اندازی مجدد</li>\n' \ + ' <li class="dropdown-item" onclick="settings();">تنظیمات</li>\n' \ + ' <li class="dropdown-item" onclick="shutdown();">خاموش</li>\n' \ + '</ul>\n' data += '<img src="./html/img/search_1.png" class="fixedIcon" id="search" onclick="search();">' data += fn.header("گروه ها") data += '<center id="main">\n' c = dt.cur(True) c.execute("SELECT * FROM branch") load = list() for b in list(c): c.execute("SELECT id FROM symbol WHERE branch = '" + str(b[0]) + "'") load.append({"i": b[0], "n": b[1], "s": len(list(c))}) dt.cur(False) load.sort(key=lambda r: r["n"]) for b in load: data += '<p style="opacity: 0;" onclick="branch(' + str(b["i"]) + ');">' \ + str(load.index(b) + 1) + ". " + str(b["n"]) \ + ' <span class="badge bg-secondary">' + str(b["s"]) + '</span></p>\n' data += '</center>\n' data += '<script type="text/javascript" src="./html/branch.js"></script>\n' data += "</body>" htm = fn.template("سام: گروه ها", "branch", data) elif status == "installing": data = '<body>\n' data += '<center id="installer">\n' with open(dt.path + "html/installing.html", "r", encoding="utf-8") as f: data += f.read().replace(" invisible", "") + '\n' f.close() data += '</center>\n' data += '<script type="text/javascript" src="./html/installing.js"></script>\n' data += '</body>' htm = fn.template("سام: راه اندازی", "install", data) else: return 500 return 200, Headers({"Content-Type": "text/html"}), htm
def view(i: str): if classifier is not None and classifier.active: return "installing... please wait..." c = dt.cur(True) c.execute("SELECT name FROM symbol WHERE id = '" + str(i) + "' LIMIT 1") name = c.fetchone() dt.cur(False) if len(name) == 0: raise dt.SaamError("نماد موردنظر در پایگاه داده یافت نشد!" + " در این مواقع بهتر است «نصب و راه اندازی مجدد» را انجام دهید.") name = name[0] data = "<body>\n" data += '<img src="./html/img/settings_1.png" class="fixedIcon" id="settings" ' \ + 'data-bs-toggle="dropdown" aria-expanded="false">\n' data += '<ul class="dropdown-menu dropdown-menu-dark" aria-labelledby="settings">\n' \ + ' <li class="dropdown-item" onclick="updateTable();">ازسرگیری جدول فعلی</li>\n' \ + ' <li class="dropdown-item" onclick="omit();">حذف براساس زمان</li>\n' \ + ' <li class="dropdown-item" onclick="truncate();">حذف براساس تایم فریم</li>\n' \ + ' <li class="dropdown-item" onclick="destroy();">حذف همه</li>\n' \ + '</ul>\n' data += fn.header(name) data += '<center id="main" data-symbol="' + i + '">\n' tf = dt.config["timeframes"] data += '<nav>\n <div class="nav nav-tabs flex-column flex-sm-row" id="nav-tab" role="tablist">\n' badge_classes = 'badge bg-light text-dark' for t in tf: con = 'nav-' + t["name"] active = '' if t == tf[0]: active = ' active' data += ' <button class="nav-link flex-sm-fill text-sm-center' + active + '" ' \ + 'id="nav-' + t["name"] + '-tab" ' \ + 'data-bs-toggle="tab" data-bs-target="#' + con + '" type="button" ' \ + 'role="tab" aria-controls="' + con + '" ' \ + 'aria-selected="true">' + t["visName"] \ + ' <span class="' + badge_classes + '">000</span></button>\n' data += ' </div>\n</nav>\n' data += '<div class="tab-content" id="nav-tabContent">\n' for t in tf: active = '' if t == tf[0]: active = ' show active' data += ' <div class="tab-pane table-responsive fade' + active + '" id="nav-' + t["name"] + '" ' \ + 'role="tabpanel" aria-labelledby="nav-' + t["name"] + '-tab">\n' tName = ("s" + str(i) + "_" + t["name"]).lower() c = dt.cur(True) got = None try: c.execute("SELECT * FROM " + tName) got = list(c) except OperationalError: pass dt.cur(False) length = str(len(got)) if got is not None else "0" data = data.replace('<span class="' + badge_classes + '">000</span>', '<span class="' + badge_classes + '">' + length + '</span>', 1) if got is not None and len(got) > 0: data += ' <table class="table table-dark">\n' # table-striped # Table Head data += ' <thead>\n' data += ' <tr>\n' arr = dt.config["viewingColumnNames"] for col in range(len(arr)): if col == 0 and not dt.config["showTimestamp"]: continue data += ' <th>' + str(arr[col]) + '</th>\n' data += ' </tr>\n' data += ' </thead>\n' # Table Body got.sort(key=lambda k: k[0]) data += ' <tbody>\n' for r in got: if not dt.config["showTimestamp"]: r = r[1:] data += ' <tr>\n' for ii in r: # DON'T USE "i"!!! data += ' <td data-bs-toggle="tooltip" data-bs-placement="top" ' \ + 'data-bs-trigger="manual">' + str(ii) + '</td>\n' data += ' </tr>\n' data += ' </tbody>\n' data += ' </table>\n' data += ' </div>\n' data += '</div>\n' data += '</center>\n' data += '<input type="hidden" id="timeSeparator" value="' + dt.config["timeSeparator"] + '">\n' data += '<input type="hidden" id="dateSeparator" value="' + dt.config["dateSeparator"] + '">\n' data += '<script type="text/javascript" src="./html/view.js"></script>\n' data += "</body>" htm = fn.template("سام: " + name, "view", data) return 200, Headers({"Content-Type": "text/html"}), htm
def branch(i: str, found: str = None): if classifier is not None and classifier.active: return "installing... please wait..." c = dt.cur(True) c.execute("SELECT name FROM branch WHERE id = '" + str(i) + "' LIMIT 1") name = c.fetchone() dt.cur(False) if len(name) == 0: raise dt.SaamError("گروه موردنظر در پایگاه داده یافت نشد!") name = name[0] data = "<body>\n" data += fn.header(name) data += '<center id="main" data-branch="' + i + '">\n' c = dt.cur(True) c.execute("SELECT id, name, info, auto FROM symbol WHERE branch = '" + i + "'") got = list(c) dt.cur(False) load = list() for s in got: tfs = dict() for t in dt.config["timeframes"]: tfs[t["name"]] = Analyzer.since_until(str(s[0]), t["name"], t["value"]) load.append({"i": s[0], "n": s[1], "f": s[2], "z": tfs, "a": fn.auto_to_binary(s[3])}) load.sort(key=lambda k: k["n"]) tf = dt.config["timeframes"] for s in load: tid = 'sym_' + str(s["i"]) sym_inf = str(s["f"]) if sym_inf == "None": sym_inf = "-" sym_checked = " checked" if "0" not in s["a"] else "" sym_indete = " indeterminate" if "0" in s["a"] and "1" in s["a"] else "" sym_found = ' id="found"' if str(s["i"]) == found else "" data += '<div class="symbol dropdown"' + sym_found + ' style="opacity: 0;" ' \ + 'onclick="symbol_toggle($(this).next());" id="div_' + str(s["i"]) + '">\n' \ + ' <input class="form-check-input chk_sym' + sym_indete + '" type="checkbox" ' \ + 'data-symbol="' + str(s["i"]) + '"' + sym_checked + '>\n' \ + ' <label>' + str(load.index(s) + 1) + ". " + str(s["n"]) + "</label>\n" \ + ' <br><span>' + sym_inf + '</span>\n' \ + ' <img src="./html/img/three_dotts_1.png" class="more" id="' + tid + '" ' \ + 'data-bs-toggle="dropdown" aria-expanded="false">\n' data += ' <ul class="dropdown-menu dropdown-menu-dark" aria-labelledby="' + tid + '">\n' \ + ' <li><a class="dropdown-item" href="/view?i=' + str(s["i"]) + '">' \ + 'نمایش تمام کندل ها' + '</a></li>\n' \ + ' <li><a class="dropdown-item" href="#" onclick="resumeSymbol(' \ + str(s["i"]) + ');">' + 'ازسرگیری تمام تایم فریم ها' + '</a></li>\n' \ + ' </ul>\n' data += '</div>\n' data += '<div class="overflow" style="display: none;" id="ovf_' + str(s["i"]) + '">\n' for t in tf: tf_checked = " checked" if s["a"][tf.index(t)] == "1" else "" data += ' <p onclick="tfClick(' + str(t["value"]) + ', \'' + str(s["i"]) + '\', this);" ' \ + 'class="' + t["name"] + '">' \ + '<input class="form-check-input chk_sym" type="checkbox" ' \ + 'data-symbol="' + str(s["i"]) + '" data-frame="' + str(tf.index(t)) + '"' \ + tf_checked + '>\n' + '<label>' + str(t["visName"]) \ + '</label><span>' + s["z"][t["name"]] + '</span></p>\n' data += '</div>\n' data += '</center>\n' data += '<input type="hidden" id="timeSeparator" value="' + dt.config["timeSeparator"] + '">\n' data += '<input type="hidden" id="dateSeparator" value="' + dt.config["dateSeparator"] + '">\n' data += '<script type="text/javascript" src="./html/symbol.js"></script>\n' data += "</body>" htm = fn.template("سام: " + name, "symbol", data) return 200, Headers({"Content-Type": "text/html"}), htm
def tuple_results(): return 200, Headers({"MyHeader": "my header"}), "hello tuple result!"