• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python textutils.json_encode函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: executeProcess

def executeProcess(manifest, role, extension_id, user_id, argv, timeout, stdin=None, rlimit_cpu=5, rlimit_rss=256):
    flavor = manifest.flavor

    if manifest.flavor not in configuration.extensions.FLAVORS:
        flavor = configuration.extensions.DEFAULT_FLAVOR

    executable = configuration.extensions.FLAVORS[flavor]["executable"]
    library = configuration.extensions.FLAVORS[flavor]["library"]

    process_argv = [executable,
                    "--rlimit-cpu=%ds" % rlimit_cpu,
                    "--rlimit-rss=%dm" % rlimit_rss,
                    os.path.join(library, "critic-launcher.js")]

    stdin_data = "%s\n" % json_encode({ "criticjs_path": os.path.join(library, "critic2.js"),
                                        "rlimit": { "cpu": rlimit_cpu,
                                                    "rss": rlimit_rss },
                                        "hostname": configuration.base.HOSTNAME,
                                        "dbname": configuration.database.PARAMETERS["database"],
                                        "dbuser": configuration.database.PARAMETERS["user"],
                                        "git": configuration.executables.GIT,
                                        "python": configuration.executables.PYTHON,
                                        "python_path": "%s:%s" % (configuration.paths.CONFIG_DIR,
                                                                  configuration.paths.INSTALL_DIR),
                                        "repository_work_copy_path": os.path.join(configuration.paths.DATA_DIR, "temporary", "EXTENSIONS"),
                                        "changeset_address": configuration.services.CHANGESET["address"],
                                        "maildelivery_pid_path": configuration.services.MAILDELIVERY["pidfile_path"],
                                        "is_development": configuration.debug.IS_DEVELOPMENT,
                                        "extension_path": manifest.path,
                                        "extension_id": extension_id,
                                        "user_id": user_id,
                                        "role": role.name(),
                                        "script_path": role.script,
                                        "fn": role.function,
                                        "argv": argv })

    if stdin is not None:
        stdin_data += stdin

    process = subprocess.Popen(process_argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=manifest.path)

    communicate = Communicate(process)
    communicate.setInput(stdin_data)
    communicate.setTimout(timeout)

    return communicate.run()[0]
开发者ID:ahockersten,项目名称:critic,代码行数:46,代码来源:execute.py


示例17: suggestreview

def suggestreview(req, db, _user):
    repository_id = req.getParameter("repository", filter=int)
    sha1 = req.getParameter("sha1")

    repository = gitutils.Repository.fromId(db, repository_id)
    commit = gitutils.Commit.fromSHA1(db, repository, sha1)

    cursor = db.cursor()
    suggestions = {}

    def addSuggestions():
        for review_id, summary in cursor:
            review = dbutils.Review.fromId(db, review_id, load_commits=False)
            if review.state != "dropped":
                suggestions[str(review_id)] = "(%s) %s" % (review.getReviewState(db), summary)

    summary = commit.summary()
    while True:
        match = re.search("[A-Z][A-Z0-9]*-[0-9]+", summary)
        if match:
            pattern = "r/%" + match.group(0) + "%"
            cursor.execute(
                """SELECT reviews.id, reviews.summary
                                FROM reviews
                                JOIN branches ON (reviews.branch=branches.id)
                               WHERE branches.name LIKE %s""",
                (pattern,),
            )
            addSuggestions()

            summary = summary[match.end() :]
        else:
            break

    cursor.execute(
        """SELECT reviews.id, reviews.summary
                        FROM reviews
                       WHERE reviews.summary=%s""",
        (commit.summary(),),
    )
    addSuggestions()

    return json_encode(suggestions)
开发者ID:suquant,项目名称:critic,代码行数:43,代码来源:critic.py


示例18: 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 as error:
        raise ChangesetBackgroundServiceError(error[1])

    try:
        results = json_decode(data)
    except ValueError:
        raise ChangesetBackgroundServiceError(
            "returned an invalid response: %r" % data)

    if type(results) != list:
        # If not a list, the result is probably an error message.
        raise ChangesetBackgroundServiceError(str(results))

    if len(results) != len(requests):
        raise ChangesetBackgroundServiceError("didn't process all requests")

    errors = []

    for result in results:
        if "error" in result:
            errors.append(result["error"])

    if errors:
        raise ChangesetBackgroundServiceError(
            "one or more requests failed:\n%s" % "\n".join(map(indent, errors)))
开发者ID:Aessy,项目名称:critic,代码行数:40,代码来源:client.py


示例19: requestHighlights

def requestHighlights(repository, sha1s):
    requests = [{ "repository_path": repository.path, "sha1": sha1, "path": path, "language": language }
                for sha1, (path, language) in sha1s.items()
                if not syntaxhighlight.isHighlighted(sha1, language)]

    if not requests: return

    try:
        connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        connection.connect(configuration.services.HIGHLIGHT["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 HighlightBackgroundServiceError(error[1])
开发者ID:ryfow,项目名称:critic,代码行数:23,代码来源:request.py


示例20: requestHighlights

def requestHighlights(repository, sha1s):
    requests = [{ "repository_path": repository.path, "sha1": sha1, "path": path, "language": language }
                for sha1, (path, language) in sha1s.items()
                if not syntaxhighlight.isHighlighted(sha1, language)]

    if not requests: return

    try:
        connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        connection.connect(configuration.services.HIGHLIGHT["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 as error:
        raise HighlightBackgroundServiceError(error[1])

    try:
        results = json_decode(data)
    except ValueError:
        raise HighlightBackgroundServiceError(
            "returned an invalid response (%r)" % data)

    if type(results) != list:
        # If not a list, the result is probably an error message.
        raise HighlightBackgroundServiceError(str(results))

    if len(results) != len(requests):
        raise HighlightBackgroundServiceError("didn't process all requests")
开发者ID:Aessy,项目名称:critic,代码行数:36,代码来源:request.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python textutils.reflow函数代码示例发布时间:2022-05-27
下一篇:
Python textutils.json_decode函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap