def render(self, name, value=None, attrs=None): initial = [] if value: for v in value: v = v.strip() if v: initial += [{"id": v, "name": v}] initial = json_encode(initial) html = super(AutoCompleteTags, self).render(name, value, attrs) js = """<script type="text/javascript"> $(document).ready(function() { $("#%s").tokenInput("%s",{ prePopulate: %s, allowNewValues: true, canCreate: true, classes: { tokenList: "token-input-list-noc", token: "token-input-token-noc", tokenDelete: "token-input-delete-token-noc", selectedToken: "token-input-selected-token-noc", highlightedToken: "token-input-highlighted-token-noc", dropdown: "token-input-dropdown-noc", dropdownItem: "token-input-dropdown-item-noc", dropdownItem2: "token-input-dropdown-item2-noc", selectedDropdownItem: "token-input-selected-dropdown-item-noc", inputToken: "token-input-input-token-noc" } }); }); </script> """ % (attrs["id"], "/main/tag/ac_lookup/", initial) return mark_safe("\n".join([html, js]))
def error_report(reverse=TRACEBACK_REVERSE, logger=logger): fp = error_fingerprint() r = get_traceback(reverse=reverse, fp=fp) logger.error(r) if ENABLE_CP: fp = error_fingerprint() path = os.path.join(CP_NEW, fp + ".json") if not os.path.exists(path): # @todo: TZ # @todo: Installation ID c = { "ts": datetime.datetime.now().isoformat(), "uuid": fp, # "installation": None, "process": os.path.relpath(sys.argv[0]), "branch": get_branch(), "tip": get_tip(), "traceback": r } try: safe_rewrite(path, json_encode(c)) if CP_SET_UID: os.chown(path, CP_SET_UID, -1) logger.error("Writing CP report to %s", path) except OSError, why: logger.error("Unable to write CP report: %s", why)
def save_beef(self, path, **kwargs): def q(s): ts = type(s) if ts == datetime.datetime: return s.isoformat() elif ts == dict: return dict((k, q(s[k])) for k in s) elif ts == list: return [q(x) for x in s] elif ts == tuple: return tuple([q(x) for x in s]) elif isinstance(s, basestring): return str(s).encode("string_escape") else: return s beef = dict((k, getattr(self, k, None)) for k in self.beef_args) beef.update(kwargs) if not beef.get("date"): beef["date"] = datetime.datetime.now() if not beef.get("guid"): beef["guid"] = str(uuid.uuid4()) beef = q(beef) if os.path.isdir(path): path = os.path.join(path, beef["guid"] + ".json") safe_rewrite(path, json_encode(beef), mode=0644) return path
def render_json(self, obj, status=200): """ Create serialized JSON-encoded response """ return HttpResponse(json_encode(obj), mimetype="text/json", status=status)
def response(self, content="", status=200): if not isinstance(content, basestring): return HttpResponse(json_encode(content), mimetype="text/json; charset=utf-8", status=status) else: return HttpResponse(content, mimetype="text/plain; charset=utf-8", status=status)
def handle_create(self, *args, **options): if options.get("platform"): vendor, platform, version = options["platform"].split(",", 2) else: vendor, platform, version = None, None, None beef = { "type": "script::beef", "date": datetime.datetime.now().isoformat(), "script": options.get("script"), "guid": str(uuid.uuid4()), "vendor": vendor, "platform": platform, "version": version, "cli": {}, "result": None } for cmd, result in zip(options["cli"], options["result"]): with open(result) as f: beef["cli"][cmd] = f.read() print json_encode(beef)
def compile_mib(self, mib, out_path, bump=False): sys.stderr.write("%s -> %s\n" % (mib.name, out_path)) if out_path: d = os.path.dirname(out_path) if not os.path.isdir(d): os.makedirs(d) if os.path.splitext(out_path)[-1] == ".gz": out = gzip.GzipFile(out_path, "w") else: out = open(out_path, "w") else: out = sys.stdout # Prepare MIB data mib_data = sorted([{ "oid": d.oid, "name": d.name, "description": d.description, "syntax": d.syntax } for d in MIBData.objects.filter(mib=mib.id)] + [{ "oid": d.oid, "name": (a for a in d.aliases if a.startswith(mib.name + "::")).next(), "description": d.description, "syntax": d.syntax } for d in MIBData.objects.filter(aliases__startswith="%s::" % mib.name)], key=lambda x: x["oid"]) # Prepare MIB if mib.last_updated: last_updated = mib.last_updated.strftime("%Y-%m-%d") else: last_updated = "1970-01-01" version = mib.version if bump: # Bump to next version version += 1 data = { "name": mib.name, "description": mib.description, "last_updated": last_updated, "version": version, "depends_on": mib.depends_on, "typedefs": mib.typedefs, "data": mib_data } # Serialize out.write(json_encode(data)) if out_path: out.close()
def get_json_response(self, data, opts): r = [] for series in data: r += [{"target": series.name, "datapoints": list(series)}] c = json_encode(r) if opts.get("jsonp"): return HttpResponse( mimetype="text/javascript", content="%s(%s)" % (opts["jsonp"], c) ) else: return HttpResponse( mimetype="application/json", content=c )
def request(self, method, path, user=None, **kwargs): if user is None: kwargs["credentials"] = {} else: kwargs["credentials"] = {"user": user, "password": user} # Convert input to JSON if "data" in kwargs: kwargs["data"] = json_encode(kwargs["data"]) if method in ("post", "put"): kwargs["content_type"] = "text/json" r = getattr(self.client, method)(path, **kwargs) if r.has_header("Content-Type") and r["Content-Type"].startswith( "text/json"): return (r.status_code, json_decode(r.content)) else: return r.status_code, r.content
def stomp_build_frame(cmd, headers=None, body=""): headers = headers or {} # Set content-type if "content-type" not in headers: if isinstance(body, basestring): headers["content-type"] = "text/plain" else: headers["content-type"] = "text/json" # Serialize body if not isinstance(body, basestring): body = json_encode(body) # Set content-length if "content-length" not in headers: headers["content-length"] = len(body) # Escape headers h = "\n".join("%s:%s" % (k, stomp_escape_value(headers[k])) for k in headers) return "%s\n%s\n\n%s\x00" % (cmd, h, body)
def send_data(self, data): logger.debug("Sending data") conf = self._daemon.configuration_thread with conf.conf_lock: url = conf.url[:-8] + "/feed/" auth = conf.auth timeout = 60 req = urllib2.Request(url) if auth: req.add_header("Authorization", auth) req.add_header("Content-Type", "text/json") req.add_data(json_encode(data)) try: urllib2.urlopen(req, timeout=timeout) except urllib2.URLError, why: logger.error("Cannot feed data to %s: %s", url, why) return False
def call(self, service, method, *args): """ JSON-RPC client """ self.t_id += 1 r = {"id": self.t_id, "method": method, "params": args} auth = None if self.account_name and self.account_password: auth = (self.account_name, self.account_password) r = json_encode(r) logger.debug("JSON-RPC REQUEST: %s", r) try: req = requests.post(self.cp_url + service, data=r, auth=auth, verify=True) except Exception, why: logger.error("JSON-RPC Error: %s", why) raise self.Error(str(why))