Example #1
1
    def handleSendChatMessage(self, connection, package):
        """
        发送聊天消息
        """
        user = self.onlineUsers.getUserByConnection(connection)

        retPackage = SendToClientPackage("sendchatmsg")
        # 自己的id
        if user.DBUser.uid == int(package.uid) and user.DBUser.uid != int(package.fid):

            # 寻找好友ID
            for friend in user.getAllFriends():
                if friend.DBUser.uid == int(package.fid):
                    # 发送消息给好友
                    retPackage.status = 1

                    user.connection.send_message(json.dumps(retPackage, cls=ComplexEncoder))

                    chat = SendToClientPackageChatMessage(user.DBUser.uid, package.fid, package.chatmsg)
                    retPackage.obj = chat
                    if friend.connection:
                        friend.connection.send_message(json.dumps(retPackage, cls=ComplexEncoder))
                    else:
                        # 当前不在线,数据库插入离线消息
                        self.dbEngine.addOfflineChatMessageWithUserId(
                            user.DBUser.uid, package.fid, package.chatmsg, datetime.datetime.now()
                        )

                    return

        else:
            retPackage.errcode = PACKAGE_ERRCODE_USERID
            user.connection.send_message(json.dumps(retPackage, cls=ComplexEncoder))
Example #2
1
    def test_07_01_create_stat(self):
        # create the base version
        reg = {
            "register": {
                "metadata": [
                    {
                        "lang": "en",
                        "default": True,
                        "record": {"name": "My Repo 3", "url": "http://myrepo", "repository_type": ["Institutional"]},
                    }
                ]
            }
        }
        resp = requests.post(BASE_URL + "record?api_key=" + AUTH_TOKEN_4, json.dumps(reg))
        loc = resp.headers["Location"]

        # create the statistic
        stat = {"value": "27", "type": "record_count"}
        resp = requests.post(loc + "/stats?api_key=" + AUTH_TOKEN_4, json.dumps(stat))
        assert resp.status_code == 201
        sl = resp.headers["Location"]
        j = resp.json()
        assert j["success"] == "true"
        assert sl.endswith(j["id"])
        assert sl.endswith(j["location"])
Example #3
1
 def update_queue(self, queue_name, options=None):
     body = json.dumps({})
     if options is not None:
         body = json.dumps({"queue": options})
     url = "queues/%s" % queue_name
     response = self.client.patch(url, body=body, headers={"Content-Type": "application/json"})
     return response["body"]["queue"]
 def _prepare_group(self, project_id, kwargs):
     """
     Create and store OperationGroup entity, or return None
     """
     # Standard ranges as accepted from UI
     range1_values = self.get_range_values(kwargs, self._range_name(1))
     range2_values = self.get_range_values(kwargs, self._range_name(2))
     available_args = self.__expand_arguments([(kwargs, None)], range1_values, self._range_name(1))
     available_args = self.__expand_arguments(available_args, range2_values, self._range_name(2))
     is_group = False
     ranges = []
     if self._range_name(1) in kwargs and range1_values is not None:
         is_group = True
         ranges.append(json.dumps((kwargs[self._range_name(1)], range1_values)))
     if self._range_name(2) in kwargs and range2_values is not None:
         is_group = True
         ranges.append(json.dumps((kwargs[self._range_name(2)], range2_values)))
     # Now for additional ranges which might be the case for the 'model exploration'
     last_range_idx = 3
     ranger_name = self._range_name(last_range_idx)
     while ranger_name in kwargs:
         values_for_range = self.get_range_values(kwargs, ranger_name)
         available_args = self.__expand_arguments(available_args, values_for_range, ranger_name)
         last_range_idx += 1
         ranger_name = self._range_name(last_range_idx)
     if last_range_idx > 3:
         ranges = []  # Since we only have 3 fields in db for this just hide it
     if not is_group:
         group = None
     else:
         group = model.OperationGroup(project_id=project_id, ranges=ranges)
         group = dao.store_entity(group)
     return available_args, group
Example #5
1
    def test_07_03_delete_stat(self):
        # create the base version
        reg = {
            "register": {
                "metadata": [
                    {
                        "lang": "en",
                        "default": True,
                        "record": {"name": "My Repo 3", "url": "http://myrepo", "repository_type": ["Institutional"]},
                    }
                ]
            }
        }
        resp = requests.post(BASE_URL + "record?api_key=" + AUTH_TOKEN_4, json.dumps(reg))
        loc = resp.headers["Location"]

        # create the statistic
        stat = {"value": "27", "type": "record_count"}
        resp = requests.post(loc + "/stats?api_key=" + AUTH_TOKEN_4, json.dumps(stat))
        sl = resp.headers["Location"]

        # let the index catch up
        time.sleep(2)

        # issue a delete request
        resp3 = requests.delete(sl + "?api_key=" + AUTH_TOKEN_4)
        assert resp3.status_code == 200
        j = resp3.json()
        assert j.get("success") == "true"
Example #6
1
def poll_for_download(request):
    task_id = request.GET.get("task_id")
    filename = request.GET.get("filename")
    print ("Polling task id  %s" % task_id)

    if request.is_ajax():
        task = Getbigcutout()
        result = task.AsyncResult(task_id)
        print ("Ajax requested..checking result")

        if result.ready():
            print ("Result is ready")
            return HttpResponse(json.dumps({"filename": result.get()}))
        print ("Result isn't ready:", result)
        # import pdb; pdb.set_trace();
        print (result.result)

        return HttpResponse(json.dumps({"filename": None, "result": result.result}))  # result.PROGRESS

    try:
        print ("Opening file")
        f = open("/var/www/cutoutcache/" + filename)
    except:
        return HttpResponseForbidden()
    else:
        response = HttpResponse(file, mimetype="text/csv")
        response["Content-Disposition"] = "attachment; filename=%s" % filename
    return response
Example #7
1
    def post(self):
        # array of time strings: "08:00 AM"
        bannedTimes = json.loads(self.request.get("bannedTimes"))
        # array of all bannedDays checkboxes (booleans)
        bannedDays = json.loads(self.request.get("bannedDays"))

        badIvals = []
        # each 2 time strings corresponds to 5 bannedDays checkboxes
        for dayBools, times in zip(misc.iterGroups(bannedDays, 5), misc.iterGroups(bannedTimes, 2)):
            badIvals += parseJSInterval(times, dayBools)

        subCodes = json.loads(self.request.get("subCodes"))
        nums = json.loads(self.request.get("nums"))
        curCRNs = json.loads(self.request.get("curCRNs"))

        classes = [t + (year, season) for t in zip(subCodes, nums)]

        try:
            clsToSections = courses.planSchedule(classes, badIvals, curCRNs)
        except:
            self.response.out.write(json.dumps({}))
        else:
            for cls, sections in clsToSections.items():
                clsToSections[cls[0] + " " + str(cls[1])] = sections
                del clsToSections[cls]

                for sec in sections:
                    sec["Intervals"] = [courses.reprInterval(i) for i in sec["Intervals"]]

            self.response.out.write(json.dumps(clsToSections))
Example #8
0
def graphics_devices(request):
    context = {}
    form = forms.GraphicsDeviceForm()
    upload_form = forms.GraphicsDeviceUploadForm()

    if request.method == "POST" and "file" in request.FILES:
        upload_form = forms.GraphicsDeviceUploadForm(request.POST, request.FILES)
        if upload_form.is_valid():
            payload = list(parse_graphics_devices_iterable(upload_form.cleaned_data["file"]))
            api = GraphicsDevices()
            result = api.post(json.dumps(payload))
            messages.success(request, "Graphics device CSV upload successfully saved.")
            return redirect("manage:graphics_devices")

    elif request.method == "POST":
        form = forms.GraphicsDeviceForm(request.POST)
        if form.is_valid():
            payload = [
                {
                    "vendor_hex": form.cleaned_data["vendor_hex"],
                    "adapter_hex": form.cleaned_data["adapter_hex"],
                    "vendor_name": form.cleaned_data["vendor_name"],
                    "adapter_name": form.cleaned_data["adapter_name"],
                }
            ]
            api = GraphicsDevices()
            result = api.post(json.dumps(payload))
            if result:
                messages.success(request, "Graphics device saved.")
            return redirect("manage:graphics_devices")

    context["page_title"] = "Graphics Devices"
    context["form"] = form
    context["upload_form"] = upload_form
    return render(request, "manage/graphics_devices.html", context)
Example #9
0
    def _internal_call(self, method, url, payload, params):
        args = dict(params=params)
        if not url.startswith("http"):
            url = self.prefix + url
        headers = self._auth_headers()
        headers["Content-Type"] = "application/json"

        if payload:
            r = requests.request(method, url, headers=headers, data=json.dumps(payload), **args)
        else:
            r = requests.request(method, url, headers=headers, **args)

        if self.trace:
            print()
            print(method, r.url)
            if payload:
                print("DATA", json.dumps(payload))

        try:
            r.raise_for_status()
        except:
            raise SpotifyException(r.status_code, -1, u"%s:\n %s" % (r.url, r.json()["error"]["message"]))
        if len(r.text) > 0:
            results = r.json()
            if self.trace:
                print("RESP", results)
                print()
            return results
        else:
            return None
Example #10
0
    def also_prune_variant(self, also_prune, tippees=1):

        self.make_participant("test_tippee1")
        self.make_participant("test_tippee2")
        test_tipper = self.make_participant("test_tipper")

        data = [{"username": "test_tippee1", "amount": "1.00"}, {"username": "test_tippee2", "amount": "2.00"}]

        response = self.client.POST(
            "/test_tipper/tips.json", body=json.dumps(data), content_type="application/json", auth_as=test_tipper
        )

        assert response.code == 200
        assert len(json.loads(response.body)) == 2

        response = self.client.POST(
            "/test_tipper/tips.json?also_prune=" + also_prune,
            body=json.dumps([{"username": "test_tippee2", "amount": "1.00"}]),
            content_type="application/json",
            auth_as=test_tipper,
        )

        assert response.code == 200

        response = self.client.GET("/test_tipper/tips.json", auth_as=test_tipper)
        assert response.code == 200
        assert len(json.loads(response.body)) == tippees
Example #11
0
def invokeMasterChaincode(context, devopsFunc, chaincodeName, functionName, containerName):
    args = []
    if "table" in context:
        args = context.table[0].cells
    typeGolang = 1
    chaincodeSpec = {
        "type": typeGolang,
        "chaincodeID": {"name": chaincodeName},
        "ctorMsg": {"function": functionName, "args": args},
    }
    if "userName" in context:
        chaincodeSpec["secureContext"] = context.userName

    chaincodeOpPayload = createChaincodeOpPayload(devopsFunc, chaincodeSpec)

    ipAddress = bdd_test_util.ipFromContainerNamePart(containerName, context.compose_containers)
    request_url = buildUrl(context, ipAddress, "/chaincode")
    print("{0} POSTing path = {1}".format(currentTime(), request_url))

    resp = requests.post(
        request_url, headers={"Content-type": "application/json"}, data=json.dumps(chaincodeOpPayload), verify=False
    )
    assert resp.status_code == 200, "Failed to POST to %s:  %s" % (request_url, resp.text)
    context.response = resp
    print("RESULT from {0} of chaincode from peer {1}".format(functionName, containerName))
    print(json.dumps(context.response.json(), indent=4))
    if "result" in resp.json():
        result = resp.json()["result"]
        if "message" in result:
            transactionID = result["message"]
            context.transactionID = transactionID
Example #12
0
def step_impl(context, chaincodePath, ctor, containerName):
    ipAddress = bdd_test_util.ipFromContainerNamePart(containerName, context.compose_containers)
    request_url = buildUrl(context, ipAddress, "/chaincode")
    print("Requesting path = {0}".format(request_url))
    args = []
    if "table" in context:
        # There is ctor arguments
        args = context.table[0].cells
    typeGolang = 1

    # Create a ChaincodeSpec structure
    chaincodeSpec = {
        "type": typeGolang,
        "chaincodeID": {"path": chaincodePath, "name": ""},
        "ctorMsg": {"function": ctor, "args": args},
        # "secureContext" : "binhn"
    }
    if "userName" in context:
        chaincodeSpec["secureContext"] = context.userName
    if "metadata" in context:
        chaincodeSpec["metadata"] = context.metadata

    chaincodeOpPayload = createChaincodeOpPayload("deploy", chaincodeSpec)

    resp = requests.post(
        request_url, headers={"Content-type": "application/json"}, data=json.dumps(chaincodeOpPayload), verify=False
    )
    assert resp.status_code == 200, "Failed to POST to %s:  %s" % (request_url, resp.text)
    context.response = resp
    chaincodeName = resp.json()["result"]["message"]
    chaincodeSpec["chaincodeID"]["name"] = chaincodeName
    context.chaincodeSpec = chaincodeSpec
    print(json.dumps(chaincodeSpec, indent=4))
    print("")
Example #13
0
    def __call__(self, *args):
        AuthServiceProxy.__id_count += 1

        log.debug(
            "-%s-> %s %s" % (AuthServiceProxy.__id_count, self.__service_name, json.dumps(args, default=EncodeDecimal))
        )
        postdata = json.dumps(
            {"version": "1.1", "method": self.__service_name, "params": args, "id": AuthServiceProxy.__id_count},
            default=EncodeDecimal,
        )
        self.__conn.request(
            "POST",
            self.__url.path,
            postdata,
            {
                "Host": self.__url.hostname,
                "User-Agent": USER_AGENT,
                "Authorization": self.__auth_header,
                "Content-type": "application/json",
            },
        )

        response = self._get_response()
        if response["error"] is not None:
            raise JSONRPCException(response["error"])
        elif "result" not in response:
            raise JSONRPCException({"code": -343, "message": "missing JSON-RPC result"})
        else:
            return response["result"]
Example #14
0
def main():
    parser = argparse.ArgumentParser(__file__, __doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    modes = parser.add_mutually_exclusive_group(required=True)
    modes.add_argument("--list", action="store_true", help="list all variables")
    modes.add_argument("--host", help="list variables for a single host")
    modes.add_argument("--version", action="store_true", help="print version and exit")
    modes.add_argument("--hostfile", action="store_true", help="print hosts as a /etc/hosts snippet")
    parser.add_argument("--pretty", action="store_true", help="pretty-print output JSON")
    parser.add_argument("--nometa", action="store_true", help="with --list, exclude hostvars")
    default_root = os.environ.get(
        "TERRAFORM_STATE_ROOT", os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
    )
    parser.add_argument("--root", default=default_root, help="custom root to search for `.tfstate`s in")

    args = parser.parse_args()

    if args.version:
        print("%s %s" % (__file__, VERSION))
        parser.exit()

    hosts = iterhosts(iterresources(tfstates(args.root)))
    if args.list:
        output = query_list(hosts)
        if args.nometa:
            del output["_meta"]
        print(json.dumps(output, indent=4 if args.pretty else None))
    elif args.host:
        output = query_host(hosts, args.host)
        print(json.dumps(output, indent=4 if args.pretty else None))
    elif args.hostfile:
        output = query_hostfile(hosts)
        print(output)

    parser.exit()
Example #15
0
    def test_trim_field(self):
        uc = UpdateCount(addon_id=3615, count=1, date="2015-01-11")
        self.command.trim_field(uc.versions)  # Empty field.
        assert not uc.versions

        uc.versions = {"3.6": 123, "3.7": 321}
        self.command.trim_field(uc.versions)  # Small enough to fit in the db.
        assert uc.versions == {"3.6": 123, "3.7": 321}  # Unchanged.

        very_long_key = "x" * (2 ** 16)
        uc.versions[very_long_key] = 1
        self.command.trim_field(uc.versions)  # Too big, must be trimmed.
        assert uc.versions == {"3.6": 123, "3.7": 321}  # Keep the most used.

        uc.versions[very_long_key] = 1000  # Most used.
        self.command.trim_field(uc.versions)  # Too big, must be trimmed.
        # Nothing left: least used removed, but still too big, so all the keys
        # were removed.
        assert uc.versions == {}

        # Make sure we can store a very large field in the database.
        long_key = "x" * 65528  # This makes the dict barely fit in the db.
        uc.versions[long_key] = 1
        assert len(json.dumps(uc.versions)) == (2 ** 16) - 1
        uc.save()
        uc = UpdateCount.objects.get(pk=uc.pk)  # Reload
        # Fits in the database, so no truncation.
        assert len(json.dumps(uc.versions)) == (2 ** 16) - 1
Example #16
0
def getcontacts(id=None):
    """
    Retrieves all the contacts currently stored in the database
    @return: unicode
    """
    if id is None:
        contacts = [
            {
                "id": c.id,
                "firstName": c.firstName,
                "lastName": c.lastName or "",
                "phoneNumbers": [pn.number for pn in c.phonenumber],
            }
            for c in models.Contact.query.all()
        ]
        return json.dumps({"contacts": contacts})
    else:
        c = models.Contact.query.filter_by(id=id).one()
        r = {
            "id": c.id,
            "firstName": c.firstName,
            "lastName": c.lastName or "",
            "phoneNumbers": [pn.number for pn in c.phonenumber],
        }
        return json.dumps(r)
Example #17
0
def inc_desc(sign, request, pk):
    """
    Need doc
    """
    ple = get_object_or_404(PlaylistEntry, pk=pk)
    key = "ple_{}_{}".format(request.user.id, ple.pk)
    song_key = "song_{}".format(ple.song.pk)

    if cache.get(key):
        return HttpResponse(json.dumps({"message": "Do not try this with me"}), mimetype="application/json")
    else:
        cache.set(key, True)
        cache.set(song_key, True)

    song = get_object_or_404(Song, pk=ple.song.id)

    if sign == "plus":
        ple.score += 1
        song.global_score += 1
        vte = +1
    else:
        ple.score -= 1
        song.global_score -= 1
        vte = -1
    ple.save()
    song.save()
    # create a vote for this song
    Vote.objects.create(song=song, user=request.user, vote=vte)

    resp = {"score": ple.score, "id": ple.pk}
    return HttpResponse(json.dumps({"entry": resp}), mimetype="application/json")
Example #18
0
def gdisconnect():
    access_token = login_session["access_token"]
    print "In gdisconnect access token is %s", access_token
    print "User name is: "
    print login_session["username"]
    if access_token is None:
        print "Access Token is None"
        response = make_response(json.dumps("Current user not connected."), 401)
        response.headers["Content-Type"] = "application/json"
        return response
    url = (
        "https://accounts.google.com/o/oauth2/revoke? \
    token=%s"
        % login_session["access_token"]
    )
    h = httplib2.Http()
    result = h.request(url, "GET")[0]
    print "result is "
    print result
    if result["status"] == "200":
        # del login_session['access_token']
        # del login_session['gplus_id']
        # del login_session['username']
        # del login_session['email']
        # del login_session['picture']
        login_session.clear()
        response = make_response(json.dumps("Successfully disconnected."), 200)
        response.headers["Content-Type"] = "application/json"
        return response
    else:

        response = make_response(json.dumps("Failed to revoke token for given user.", 400))
        response.headers["Content-Type"] = "application/json"
        return response
Example #19
0
    def test_put_raises_if_missing_fields(self):
        path = "/v1/shards/" + str(uuid.uuid1())
        self.simulate_put(path, body=json.dumps({"weight": 100}))
        self.assertEqual(self.srmock.status, falcon.HTTP_400)

        self.simulate_put(path, body=json.dumps({"uri": "localhost"}))
        self.assertEqual(self.srmock.status, falcon.HTTP_400)
Example #20
0
 def PUT(self, request, tenantId):
     try:
         info = InfoManager.InfoManager().get_information(tenantId)
         self.set_info(info)
         info2 = self.info.parse(request.body)
         if info2 != None:
             t = InfoManager.InfoManager().updateWindowSize(tenantId, info2.windowsize)
             logger.debug("Window size updated for tenant: %s", tenantId)
             return HttpResponse(json.dumps({"windowsize": info2.windowsize}, indent=4))
         else:
             return HttpResponseBadRequest(
                 json.dumps({"badRequest": {"code": 400, "message": "windowsize could not be parsed"}}, indent=4)
             )
     except ObjectDoesNotExist as err:
         t = TenantInfo(tenantId=tenantId, windowsize=5)
         t.save()
         info = InfoManager.InfoManager().get_information(tenantId)
         self.set_info(info)
         info2 = self.info.parse(request.body)
         t = InfoManager.InfoManager().updateWindowSize(tenantId, info2.windowsize)
         return HttpResponse(json.dumps({"windowsize": info2.windowsize}, indent=4))
     except ValidationError as ex:
         return HttpResponse(
             json.dumps({"badRequest": {"code": 400, "message": ex.messages[0]}}, indent=4), status=400
         )
Example #21
0
    def test_update(self):

        resp = yield from aiohttp.post(
            self.full_url(self.app.reverse("fruit_index")), data=json.dumps(dict(name="pear", colors=["green"]))
        )

        self.assertEqual(resp.status, 200)
        resp.close()

        resp = yield from aiohttp.get(self.full_url(self.app.reverse("fruit_item", id="pear")))

        self.assertEqual(resp.status, 200)
        jr = yield from resp.json()
        self.assertEqual(jr["body"], dict(colors=["green"]))
        resp.close()

        resp = yield from aiohttp.put(
            self.full_url(self.app.reverse("fruit_item", id="pear")), data=json.dumps(dict(colors=["green", "yellow"]))
        )

        self.assertEqual(resp.status, 200)
        resp.close()

        resp = yield from aiohttp.get(self.full_url(self.app.reverse("fruit_item", id="pear")))

        self.assertEqual(resp.status, 200)
        jr = yield from resp.json()
        self.assertEqual(jr["body"], dict(colors=["green", "yellow"]))
        resp.close()
Example #22
0
 def GET(self, request, tenantId):
     # Should return a list of servers with their rules
     try:
         entities = RuleManager.RuleManager().get_all_entities(tenantId)
         return HttpResponse(json.dumps(vars(entities), cls=DateEncoder, indent=4))
     except Exception as err:
         return HttpResponseServerError(json.dumps({"serverFault": {"code": 500, "message": str(err)}}, indent=4))
def getProfile():
    accessToken = request.args.get("a", "", type=unicode)
    url = (
        "https://graph.facebook.com/me?fields=id, name, gender, relationship_status, picture.height(200).width(200), link, statuses.limit(1).fields(message,updated_time) &access_token="
        + accessToken
    )
    profile = json.loads(urllib.urlopen(url).read())
    print "PROFILE: ", profile, type(profile)
    print profile["id"]
    me = dict()
    for key in profile.keys():
        print "key: ", key
        if key == "picture":
            print profile[key]["data"]
            me[key] = profile[key]["data"]
        elif key == "statuses":
            recent_status = {}
            recent_status["updated_time"] = profile["statuses"]["data"][0]["updated_time"]
            recent_status["message"] = profile["statuses"]["data"][0]["message"]
            me["status"] = recent_status
            print me["status"]
        else:
            print profile[key]
            me[key] = profile[key]
    print json.dumps(me)
    return json.dumps(me)
Example #24
0
def make_metadata(uid0, uid1, n_bytes, rservice):
    def make_data(uid, rid, direction):
        assert direction in [1, -1]
        data = {}
        data["uid"] = uid
        data["rid"] = rid
        data["store_filename"] = get_storefile_name(uid, rid)
        data["metadata_filename"] = get_metadatafile_name(uid, rid)
        data["n_bytes"] = n_bytes
        data["rservice"] = rservice
        data["split_index"] = n_bytes / 2
        data["direction"] = direction
        data["encrypt_index"] = 0 if direction == 1 else n_bytes - 1
        data["decrypt_log"] = ""
        data["decrypt_max"] = n_bytes - 1 if direction == 1 else 0
        # These two must always go last, in this order
        data["n_eles"] = len(data.items()) + 2
        data["checksum"] = hash(frozenset(data.items()))
        return data

    data = [make_data(uid0, uid1, 1), make_data(uid1, uid0, -1)]

    mfile = [data[0]["metadata_filename"], data[1]["metadata_filename"]]
    sfile = [data[0]["store_filename"], data[1]["store_filename"]]

    with open(mfile[0], "w") as metadata0, open(mfile[1], "w") as metadata1:
        metadata0.write(json.dumps(data[0]))
        metadata1.write(json.dumps(data[1]))
    log(
        "metadata for {} and {} have been written to {} and {}, respectively".format(
            sfile[0], sfile[1], mfile[0], mfile[1]
        )
    )
Example #25
0
    def test_08_01_create_admin(self):
        # create the base version
        reg = {
            "register": {
                "metadata": [
                    {
                        "lang": "en",
                        "default": True,
                        "record": {"name": "My Repo 3", "url": "http://myrepo", "repository_type": ["Institutional"]},
                    }
                ]
            }
        }
        resp = requests.post(BASE_URL + "record?api_key=" + AUTH_TOKEN_5, json.dumps(reg))
        loc = resp.headers["Location"]

        admin = {"akey": "a value"}
        resp2 = requests.put(loc + "/admin?api_key=" + AUTH_TOKEN_5, json.dumps(admin))

        assert resp2.status_code == 200
        j = resp2.json()
        assert j.get("success") == "true"

        # give the index time to catch up
        time.sleep(2)

        resp3 = requests.get(loc)
        j = resp3.json()
        assert "admin" in j
        assert "test5" in j["admin"]
        assert j["admin"]["test5"]["akey"] == "a value"
Example #26
0
def multipath_status_json(request):

    multipaths = notifier().multipath_all()
    _id = 1
    items = []
    for mp in multipaths:
        children = []
        for cn in mp.consumers:
            actions = {}
            items.append(
                {
                    "id": str(_id),
                    "name": cn.devname,
                    "status": cn.status,
                    "lunid": cn.lunid,
                    "type": "consumer",
                    "actions": json.dumps(actions),
                }
            )
            children.append({"_reference": str(_id)})
            _id += 1
        data = {"id": str(_id), "name": mp.devname, "status": mp.status, "type": "root", "children": children}
        items.append(data)
        _id += 1
    return HttpResponse(
        json.dumps({"identifier": "id", "label": "name", "items": items}, indent=2), content_type="application/json"
    )
Example #27
0
    def msg(self, text=None, from_obj=None, session=None, **kwargs):
        """
        Emits something to a session attached to the object.

        Args:
            text (str, optional): The message to send
            from_obj (obj, optional): object that is sending. If
                given, at_msg_send will be called
            session (Session or list, optional): Session or list of
                Sessions to relay data to, if any. If set, will
                force send to these sessions. If unset, who receives the
                message depends on the MULTISESSION_MODE.

        Notes:
            `at_msg_receive` will be called on this Object.
            All extra kwargs will be passed on to the protocol.

        """
        # Send messages to the client. Messages are in format of JSON.
        raw = kwargs.get("raw", False)
        if not raw:
            try:
                text = json.dumps(text)
            except Exception, e:
                text = json.dumps({"err": "There is an error occurred while outputing messages."})
                logger.log_errmsg("json.dumps failed: %s" % e)
Example #28
0
def validate_user(request):
    """ not sure what we want to do here, since we will use email as username"""
    response_doc = {"status": True, "msg": "success", "errors": []}
    status, msg, errors = True, "", []
    try:
        if request.method == "POST":
            print "post"
            in_data = request.body
            json_data = json.loads(in_data)
            print "loaded_body"
            if json_data:
                email = json_data.get("email")
                password = json_data.get("password")
                print " trying result"
                result = test_login(email, password)
                if result:
                    if "401" in result:
                        status, msg = False, "Incorrect Credentials"
                    else:
                        status, msg = True, "success"
                    print result
                    print "end"
                else:
                    status, msg = False, "Incorrect Credentials"
            else:
                status, msg = False, "No JSON Data received in POST"
            return HttpResponse(
                json.dumps({"status": status, "msg": msg, "errors": errors}), content_type="application/json"
            )
    except Exception as e:
        print e
        return HttpResponse(json.dumps({"err": str(e)}), content_type="application/json")
def zip_lookup(request):

    zipcode = request.GET.get("zip")

    if len(zipcode) > 5:
        if "-" in zipcode:
            zip5, plus4 = zipcode.split("-")
        else:
            zip5 = zipcode[:5]
    else:
        zip5 = zipcode

    if zip5:
        try:
            place = ZipCode.objects.get(zipcode=zip5)
            cleaned = {}
            cleaned["city"] = place.city.lower().title()
            cleaned["state"] = place.state
            cleaned["zip"] = place.zipcode
            # print cleaned
        except ZipCode.DoesNotExist:
            # print e
            return HttpResponseServerError(json.dumps({"error": "unknown zipcode"}), mimetype="application/json")
    else:
        return HttpResponseServerError("requires zip get parameter")
    return HttpResponse(json.dumps(cleaned), mimetype="application/json")
Example #30
0
    def handleDeleteFriend(self, connection, package):
        """
        删除好友
        """
        user = self.onlineUsers.getUserByConnection(connection)

        retPackage = SendToClientPackage("delfriend")
        # 自己的id
        if user.DBUser.uid == int(package.uid) and user.DBUser.uid != int(package.fid):

            retPackage.status = 1
            # 从数据库中删除
            self.dbEngine.deleteFriendshipByUserAndFriendId(package.uid, package.fid)

            user.connection.send_message(json.dumps(retPackage, cls=ComplexEncoder))

            # 给在线好友发送通知,删除
            online_friend = self.onlineUsers.getUserExistByUserid(package.fid)
            if online_friend:
                sendObj = SendToClientPackageUser(
                    user.DBUser.uid, user.DBUser.username, user.DBUser.sex, user.DBUser.description
                )
                retPackage.obj = sendObj
                online_friend.connection.send_message(json.dumps(retPackage, cls=ComplexEncoder))

                # 从维护的好友列表中删除
                user.deleteFriend(online_friend)

        else:
            retPackage.errcode = PACKAGE_ERRCODE_USERID
            user.connection.send_message(json.dumps(retPackage, cls=ComplexEncoder))