当前位置: 首页>>代码示例>>Python>>正文


Python textutils.json_encode函数代码示例

本文整理汇总了Python中textutils.json_encode函数的典型用法代码示例。如果您正苦于以下问题:Python json_encode函数的具体用法?Python json_encode怎么用?Python json_encode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了json_encode函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: renderLocalRepository

    def renderLocalRepository(target):
        page.utils.generateRepositorySelect(db, user, target)

        cursor.execute("""SELECT repositories.id, repositories.name, repositories.path, branches.name
                            FROM repositories
                 LEFT OUTER JOIN branches ON (branches.id=repositories.branch)
                        ORDER BY id""")

        for repository_id, name, path, branch_name in cursor.fetchall():
            local_names = ["*"]

            if branch_name:
                local_names.append(branch_name)

            cursor.execute("""SELECT remote
                                FROM trackedbranches
                               WHERE repository=%s
                                 AND local_name=ANY (%s)
                            ORDER BY local_name
                               LIMIT 1""",
                           (repository_id, local_names))

            row = cursor.fetchone()

            if row: default_remotes[name] = row[0]
            else: default_remotes[name] = None

            default_branches[name] = branch_name

        document.addInternalScript("var default_remotes = %s;" % json_encode(default_remotes))
        document.addInternalScript("var default_branches = %s;" % json_encode(default_branches))
开发者ID:ahockersten,项目名称:critic,代码行数:31,代码来源:createreview.py

示例2: renderLocalRepository

    def renderLocalRepository(target):
        repositories = target.select("repository")

        cursor.execute("""SELECT repositories.id, repositories.name, repositories.path, branches.name
                            FROM repositories
                 LEFT OUTER JOIN branches ON (branches.id=repositories.branch)
                        ORDER BY id""")

        for repository_id, name, path, branch_name in cursor.fetchall():
            option = repositories.option("repository", value=name, selected="selected" if name == default_repository else None)
            option.text("%s [%s]" % (name, gitutils.Repository.constructURL(db, user, path)))

            local_names = ["*"]

            if branch_name:
                local_names.append(branch_name)

            cursor.execute("""SELECT remote
                                FROM trackedbranches
                               WHERE repository=%s
                                 AND local_name=ANY (%s)
                            ORDER BY local_name
                               LIMIT 1""",
                           (repository_id, local_names))

            row = cursor.fetchone()

            if row: default_remotes[name] = row[0]
            else: default_remotes[name] = None

            default_branches[name] = branch_name

        document.addInternalScript("var default_remotes = %s;" % json_encode(default_remotes))
        document.addInternalScript("var default_branches = %s;" % json_encode(default_branches))
开发者ID:ryfow,项目名称:critic,代码行数:34,代码来源:createreview.py

示例3: renderLocalRepository

    def renderLocalRepository(target):
        page.utils.generateRepositorySelect(db, user, target)

        cursor.execute("""SELECT repositories.id, repositories.name, repositories.path
                            FROM repositories
                        ORDER BY repositories.id""")

        for repository_id, name, path in cursor.fetchall():
            def findRemote(local_name):
                cursor.execute("""SELECT remote
                                    FROM trackedbranches
                                   WHERE repository=%s
                                     AND local_name=%s""",
                               (repository_id, local_name))
                row = cursor.fetchone()
                if row:
                    return row[0]

            repository = gitutils.Repository.fromId(db, repository_id)
            remote = branch_name = None

            for branch in repository.getSignificantBranches(db):
                remote = findRemote(branch.name)
                if remote:
                    branch_name = branch.name
                    break

            if not remote:
                remote = findRemote("*")

            default_remotes[name] = remote
            default_branches[name] = branch_name

        document.addInternalScript("var default_remotes = %s;" % json_encode(default_remotes))
        document.addInternalScript("var default_branches = %s;" % json_encode(default_branches))
开发者ID:Aessy,项目名称:critic,代码行数:35,代码来源:createreview.py

示例4: renderLocalRepository

    def renderLocalRepository(target):
        repositories = target.select("repository")

        cursor.execute(
            """SELECT repositories.id, repositories.name, repositories.path, branches.name
                            FROM repositories
                 LEFT OUTER JOIN branches ON (branches.id=repositories.branch)
                        ORDER BY id"""
        )

        for repository_id, name, path, branch_name in cursor:
            option = repositories.option(
                "repository", value=name, selected="selected" if name == default_repository else None
            )
            option.text("%s [%s:%s]" % (name, configuration.base.HOSTNAME, path))

            local_names = ["*"]

            if branch_name:
                local_names.append(branch_name)

            cursor.execute(
                """SELECT remote
                                FROM trackedbranches
                               WHERE repository=%s
                                 AND local_name=ANY (%s)
                            ORDER BY local_name
                               LIMIT 1""",
                (repository_id, local_names),
            )

            def splitRemote(remote):
                if remote.startswith("git://"):
                    host, path = remote[6:].split("/", 1)
                    host = "git://" + host
                else:
                    host, path = remote.split(":", 1)
                return host, path

            row = cursor.fetchone()

            if row:
                default_remotes[name] = splitRemote(row[0])
            else:
                default_remotes[name] = None

            default_branches[name] = branch_name

        document.addInternalScript("var default_remotes = %s;" % json_encode(default_remotes))
        document.addInternalScript("var default_branches = %s;" % json_encode(default_branches))
开发者ID:KurSh,项目名称:critic,代码行数:50,代码来源:createreview.py

示例5: construct_query

            def construct_query(query):
                if not query:
                    return "null"

                params = urlparse.parse_qs(query, keep_blank_values=True)

                for key in params:
                    values = params[key]
                    if len(values) == 1:
                        if not values[0]:
                            params[key] = None
                        else:
                            params[key] = values[0]

                return ("Object.freeze({ raw: %s, params: Object.freeze(%s) })"
                        % (json_encode(query), json_encode(params)))
开发者ID:Aessy,项目名称:critic,代码行数:16,代码来源:inject.py

示例6: handle_input

        def handle_input(self, data):
            lines = data.splitlines()

            user_name = lines[0]

            # The second line is the value of the REMOTE_USER environment
            # variable (from the environment with which the git hook ran.)
            #
            # We use it as the actual user only if the actual user was the
            # Critic system user, meaning the push was performed by the
            # branch tracker service, the web front-end (for instance via
            # 'git http-backend') or an extension.
            if user_name == configuration.base.SYSTEM_USER_NAME and lines[1]:
                user_name = lines[1]

            self.__request = { "user_name": user_name,
                               "repository_name": lines[2],
                               "flags": lines[3],
                               "refs": [{ "name": name,
                                          "old_sha1": old_sha1,
                                          "new_sha1": new_sha1 }
                                        for old_sha1, new_sha1, name
                                        in map(str.split, lines[4:])] }

            self.server.info("session started: %s / %s"
                             % (self.__request["user_name"],
                                self.__request["repository_name"]))

            child_process = GitHookServer.ChildProcess(self.server, self)
            child_process.write(json_encode(self.__request))
            child_process.close()
            self.server.add_peer(child_process)
开发者ID:Haster2004,项目名称:critic,代码行数:32,代码来源:githook.py

示例7: finished

        def finished(self, process):
            if process.did_time_out:
                status = status_text = "timeout"
            else:
                status = "ok"
                if process.returncode == 0:
                    status_text = "success"
                else:
                    status_text = "error(%d)" % process.returncode

            self.server.debug("Process finished: %s [pid=%d]"
                              % (status_text, process.pid))

            if process.stdout:
                self.server.debug("  stdout=%r" % process.stdout)
            if process.stderr:
                self.server.debug("  stderr=%r" % process.stderr)

            self.write(textutils.json_encode({
                "status": status,
                "stdout": process.stdout,
                "stderr": process.stderr,
                "returncode": process.returncode
            }))
            self.close()
开发者ID:jensl,项目名称:critic,代码行数:25,代码来源:extensionrunner.py

示例8: process

    def process(self, db, user, service_name):
        if not user.hasRole(db, "administrator"):
            raise OperationFailure(
                code="notallowed", title="Not allowed!", message="Only a system administrator can restart services."
            )

        if service_name == "wsgi":
            for pid in os.listdir(configuration.paths.WSGI_PIDFILE_DIR):
                try:
                    os.kill(int(pid), signal.SIGINT)
                except:
                    pass
            return OperationResult()
        else:
            connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            connection.connect(configuration.services.SERVICEMANAGER["address"])
            connection.send(textutils.json_encode({"command": "restart", "service": service_name}))
            connection.shutdown(socket.SHUT_WR)

            data = ""
            while True:
                received = connection.recv(4096)
                if not received:
                    break
                data += received

            result = textutils.json_decode(data)

            if result["status"] == "ok":
                return OperationResult()
            else:
                raise OperationError, result["error"]
开发者ID:kolorowestudio,项目名称:critic,代码行数:32,代码来源:servicemanager.py

示例9: perform_job

    def perform_job():
        import syntaxhighlight.generate

        request = json_decode(sys.stdin.read())
        request["highlighted"] = syntaxhighlight.generate.generateHighlight(
            repository_path=request["repository_path"],
            sha1=request["sha1"],
            language=request["language"])
        sys.stdout.write(json_encode(request))
开发者ID:ahockersten,项目名称:critic,代码行数:9,代码来源:highlight.py

示例10: execute_command

        def execute_command(self, client, command):
            if command["command"] == "purge":
                purged_count = self.__purge()

                client.write(json_encode({ "status": "ok",
                                           "purged": purged_count }))
                client.close()
            else:
                super(ChangesetServer, self).execute_command(client, command)
开发者ID:Aessy,项目名称:critic,代码行数:9,代码来源:changeset.py

示例11: __call__

    def __call__(self, req, db, user):
        from operation.typechecker import TypeCheckerContext

        if user.isAnonymous() and not self.__accept_anonymous_user:
            return OperationFailureMustLogin()

        if req.method == "POST": data = req.read()
        else: data = req.getParameter("data")

        if not data: raise OperationError("no input")

        try: value = json_decode(data)
        except ValueError as error: raise OperationError("invalid input: %s" % str(error))

        try:
            self.__checker(value, TypeCheckerContext(req, db, user))
            return self.process(db, user, **value)
        except OperationError as error:
            return error
        except OperationFailure as failure:
            return failure
        except dbutils.NoSuchUser as error:
            return OperationFailure(code="nosuchuser",
                                    title="Who is '%s'?" % error.name,
                                    message="There is no user in Critic's database named that.")
        except dbutils.NoSuchReview as error:
            return OperationFailure(code="nosuchreview",
                                    title="Invalid review ID",
                                    message="The review ID r/%d is not valid." % error.id)
        except dbutils.TransactionRollbackError:
            return OperationFailure(code="transactionrollback",
                                    title="Transaction rolled back",
                                    message="Your database transaction rolled back, probably due to a deadlock.  Please try again.")
        except:
            # Decode value again since the type checkers might have modified it.
            value = json_decode(data)

            error_message = ("User: %s\nReferrer: %s\nData: %s\n\n%s"
                             % (user.name,
                                req.getReferrer(),
                                json_encode(self.sanitize(value), indent=2),
                                traceback.format_exc()))

            db.rollback()

            import mailutils
            import configuration

            if not user.hasRole(db, "developer"):
                mailutils.sendExceptionMessage(db, "wsgi[%s]" % req.path, error_message)

            if configuration.debug.IS_DEVELOPMENT or user.hasRole(db, "developer"):
                return OperationError(error_message)
            else:
                return OperationError("An unexpected error occurred.  " +
                                      "A message has been sent to the system administrator(s) " +
                                      "with details about the problem.")
开发者ID:andreastt,项目名称:critic,代码行数:57,代码来源:__init__.py

示例12: execute_command

        def execute_command(self, client, command):
            if command["command"] == "compact":
                uncompressed_count, compressed_count, purged_files_count, purged_contexts_count = self.__compact()

                client.write(json_encode({ "status": "ok",
                                           "uncompressed": uncompressed_count,
                                           "compressed": compressed_count,
                                           "purged_files": purged_files_count,
                                           "purged_contexts": purged_contexts_count }))
                client.close()
            else:
                super(HighlightServer, self).execute_command(client, command)
开发者ID:jensl,项目名称:critic,代码行数:12,代码来源:highlight.py

示例13: handle_input

            def handle_input(self, data):
                lines = data.splitlines()

                self.__request = { "user_name": lines[0],
                                   "repository_name": lines[1],
                                   "refs": [{ "name": name, "old_sha1": old_sha1, "new_sha1": new_sha1 }
                                            for old_sha1, new_sha1, name in map(str.split, lines[2:])] }

                self.server.info("session started: %s / %s" % (self.__request["user_name"], self.__request["repository_name"]))

                child_process = GitHookServer.ChildProcess(self.server, self)
                child_process.write(json_encode(self.__request))
                child_process.close()
                self.server.add_peer(child_process)
开发者ID:KurSh,项目名称:critic,代码行数:14,代码来源:githook.py

示例14: perform_job

    def perform_job():
        soft_limit, hard_limit = getrlimit(RLIMIT_RSS)
        rss_limit = configuration.services.CHANGESET["rss_limit"]
        if soft_limit < rss_limit:
            setrlimit(RLIMIT_RSS, (rss_limit, hard_limit))

        from changeset.create import createChangeset

        request = json_decode(sys.stdin.read())

        try:
            db = dbutils.Database()

            createChangeset(db, request)

            db.close()

            sys.stdout.write(json_encode(request))
        except:
            print "Request:"
            print json_encode(request, indent=2)
            print

            print_exc(file=sys.stdout)
开发者ID:Aessy,项目名称:critic,代码行数:24,代码来源:changeset.py

示例15: requestChangesets

def requestChangesets(requests):
    try:
        connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        connection.connect(configuration.services.CHANGESET["address"])
        connection.send(json_encode(requests))
        connection.shutdown(socket.SHUT_WR)

        data = ""

        while True:
            received = connection.recv(4096)
            if not received: break
            data += received

        connection.close()
    except socket.error, error:
        raise Exception, "Changeset background service failed: %s" % error[1]
开发者ID:KurSh,项目名称:critic,代码行数:17,代码来源:client.py


注:本文中的textutils.json_encode函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。