{"componentChunkName":"component---src-templates-blog-detail-tsx","path":"/blog/2019-09-16-online-Judge","result":{"data":{"currentBlog":{"id":"ae4fd2f8-515c-5aec-b584-38427ef33f7e","frontmatter":{"thumbnail":"https://img.serverlesscloud.cn/2020114/1578989800047-part-00492-780.jpg","authors":["Anycodes"],"categories":["guides-and-tutorials","user-stories"],"date":"2019-09-16T00:00:00.000Z","title":"突破传统 OJ 瓶颈，「判题姬」接入云函数","description":"通过 Serverless 实现在线编程","authorslink":["https://www.zhihu.com/people/liuyu-43-97"],"translators":null,"translatorslink":null,"tags":["在线编程","云函数"],"keywords":"Serverless 在线编程,Serverless OJ","outdated":null},"wordCount":{"words":169,"sentences":30,"paragraphs":30},"fileAbsolutePath":"/opt/build/repo/content/blog/2019-09-16-online-Judge.md","fields":{"slug":"/blog/2019-09-16-online-Judge/","keywords":["python","serverless","云函数","代码","函数","serverless"]},"html":"<blockquote>\n<p>Online Judge 系统（简称 OJ）是一个在线的判题系统。用户可以在线提交多种程序（如C、C++、Pascal）源代码，系统对源代码进行编译和执行，并通过预先设计的测试数据来检验程序源代码的正确性。</p>\n</blockquote>\n<p>随着时代的发展，OJ 已经真正地成为了测评工具，其作用不再局限为 ACM 备战，还有老师检测学生能力、学生入学考试、能力评测（例如 ZJU 的 PAT）、找工作刷题和面试（例如牛客）等，而目前 OJ 的开源框架也越来越多，但是很多 OJ 都是基于 HUSTOJ 进行定制或者二次开发。</p>\n<p><strong>无论是什么方法，在关于 OJ 的众多问题中，有一个就是：性能问题。</strong></p>\n<p>说实话，一些 OJ 群里，总会有人问：1 核 1G 的机器，可以同时判多少题目？可以有多少人同时用？如果比赛，大约有多少人需要多高性能的机器？那么『判题姬』是否只能存在传统的宿主机中，能否通过其他方式焕发新的生命力？</p>\n<p><strong>其中一种方法，就是和现有的云函数进行结合。</strong></p>\n<h2 id=\"▎简单思路\"><a href=\"#%E2%96%8E%E7%AE%80%E5%8D%95%E6%80%9D%E8%B7%AF\" aria-label=\"▎简单思路 permalink\" class=\"anchor\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>▎简单思路</h2>\n<p>通过云函数实现在线编程的思路基本有两个：</p>\n<ol>\n<li>每个用户的代码建立一个函数，用后删除；</li>\n<li>每个语言建立一个函数，用户传递代码，每次执行；</li>\n</ol>\n<p>这两种方法，第一种相对简单的，但是目前对于很多云函数服务商来说，函数数量有一定限制，而且每次执行这个操作相对比较繁琐。</p>\n<p>所以，本文采用第二种策略，建立一个函数，每次执行，用户传入代码，系统执行，返回结果。</p>\n<p>代码写入系统：</p>\n<div class=\"gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\">def WriteCode(code):\n    try:\n        with open(&quot;/tmp/mytest.py&quot;, &quot;w&quot;) as f:\n            f.write(code)\n        return True\n    except Exception as e:\n        print(e)\n        return False</code></pre></div>\n<p>执行代码：</p>\n<div class=\"gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\">def RunCode(input_data=None):\n    child = subprocess.Popen(&quot;python /tmp/mytest.py&quot;, stdin=input_data, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, shell=True)\n    error = child.stderr.read()\n    output = child.stdout.read()\n    return error, output</code></pre></div>\n<p>代码和用例处理逻辑：</p>\n<div class=\"gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\">def main_handler(event, context):\n    if WriteCode(event[&quot;code&quot;]):\n        try:\n            temp_list = []\n            for eve in event[&quot;input&quot;]:\n                result = RunCode()\n                temp_list.append({&quot;error&quot;:result[0].decode(&quot;utf-8&quot;),&quot;result&quot;: result[1].decode(&quot;utf-8&quot;), &quot;exception&quot;:&quot;&quot;})\n            return json.dumps(temp_list)\n        except Exception as e:\n            return json.dumps({&quot;error&quot;:&quot;&quot;,&quot;result&quot;: &quot;&quot;, &quot;exception&quot;:str(e)})</code></pre></div>\n<p>用户在传入数据的时候，需要注意事件为：</p>\n<div class=\"gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\">{\n  &quot;code&quot;: &quot;print(&#39;hello&#39;)&quot;,\n  &quot;input&quot;: [&quot;111&quot;,&quot;22222&quot;]\n}</code></pre></div>\n<p>这样就可以每次请求的时候把代码传入（code），每个测试用例的 input 就是 input 内容。</p>\n<p><strong>以本题输出结果：</strong></p>\n<p><img src=\"https://img.serverlesscloud.cn/2020114/1578989799994-part-00492-780.jpg\" alt=\"输出结果\"></p>\n<p>这样就实现了 Python 判题机的基本功能，此时通过 <a href=\"https://cloud.tencent.com/document/api/583/17243?from=9253\">腾讯云云 API </a>实现参数传入，通过 <a href=\"https://console.cloud.tencent.com/api/explorer?Product=scf&#x26;Version=2018-04-16&#x26;Action=Invoke&#x26;SignVersion=\">Explorer</a> 进行代码撰写，直接接入自己的 OJ 就可以了。</p>\n<h2 id=\"▎额外的话\"><a href=\"#%E2%96%8E%E9%A2%9D%E5%A4%96%E7%9A%84%E8%AF%9D\" aria-label=\"▎额外的话 permalink\" class=\"anchor\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>▎额外的话</h2>\n<p>虽然这是一个简单的代码执行工具，但是这个小工具还可以应用在很多其他地方。本文只是抛砖引玉，例如我们做了一个 OJ，如果在本地跑代码可能性能和安全性都会受到挑战，那么此时，放入腾讯云云函数中，就会简单、安全、便捷得多，最主要的是腾讯云的函数调用免费额度很高。</p>\n<p>此外，如果临时举办比赛，也不用费心费力扩容缩容，只要有云函数，后端的主要压力，都传给 Serverless 搞定，这也算是发挥了云函数的一个优势和特性。</p>\n<p>那么，除了在 OJ 中使用的用途，它还有啥用？简单举两个例子：</p>\n<ol>\n<li><a href=\"https://www.anycodes.cn\">Anycodes</a>、<a href=\"http://codepad.org\">Codepad</a> 这些在线编程网站，之前很多人就问是如何实现的。试想一下，通过这个策略，是不是很好实现了在线编程？确切说，只需要一个前端，就可以实现在线写代码的一个网页。</li>\n<li>菜鸟教程这些网站，可以看代码然后点击运行，很炫酷的功能，很多小伙伴也想往自己博客增加一个类似的功能，也可以基于这个方法来实现。</li>\n</ol>\n<p>除此之外，还有好多的用途，各位小伙伴们，快来自己挖掘吧！</p>\n<blockquote>\n<p><strong>传送门：</strong></p>\n<ul>\n<li>GitHub: <a href=\"https://github.com/serverless/serverless/blob/master/README_CN.md\">github.com/serverless</a> </li>\n<li>官网：<a href=\"https://serverless.com/\">serverless.com</a></li>\n</ul>\n</blockquote>\n<p>欢迎访问：<a href=\"https://serverlesscloud.cn/\">Serverless 中文网</a>，您可以在 <a href=\"https://serverlesscloud.cn/best-practice\">最佳实践</a> 里体验更多关于 Serverless 应用的开发！</p>","tableOfContents":"<ul>\n<li><a href=\"/blog/2019-09-16-online-Judge/#%E2%96%8E%E7%AE%80%E5%8D%95%E6%80%9D%E8%B7%AF\">▎简单思路</a></li>\n<li><a href=\"/blog/2019-09-16-online-Judge/#%E2%96%8E%E9%A2%9D%E5%A4%96%E7%9A%84%E8%AF%9D\">▎额外的话</a></li>\n</ul>"},"previousBlog":{"id":"56b79d5f-8104-59ba-b8c8-c6d1b5518ded","frontmatter":{"thumbnail":"https://img.serverlesscloud.cn/qianyi/images/YHl6UWa9s63gXEueAufpULb25PiblSh96vULKgk2padpta42yxwdVnqEQPYNn5WVnM3D7FibEvUqWr7LyF5tsCNA.png","authors":["Anycodes"],"categories":["news"],"date":"2019-09-18T00:00:00.000Z","title":"Serverless 实践：全新命令行工具帮你快速部署云函数","description":"SCF CLI 是腾讯云云函数（Serverless Cloud Function，SCF）产品的命令行工具，想必很多小伙伴已经有所了解，或者试用过了。作为一个可以提高开发者效率的工具，腾讯云 Serverless 团队一直在对 SCF CLI 进行优化工作，本文将给大家介绍新版 SCF CLI 增加的有趣功能！","authorslink":["https://github.com/jiangliu5267"],"translators":null,"translatorslink":null,"tags":["SCF CLI","云函数"],"keywords":"Serverless, SCF CLI, Serverless云函数","outdated":true},"wordCount":{"words":358,"sentences":90,"paragraphs":90},"fileAbsolutePath":"/opt/build/repo/content/blog/2019-09-18-serverless-scf-cli.md","fields":{"slug":"/blog/2019-09-18-serverless-scf-cli/","keywords":["python","serverless","spa","云函数","Serverless","serverlesscloud","网关","cos"]}},"nextBlog":{"id":"97450b07-658b-5207-8216-1c7b9b51b115","frontmatter":{"thumbnail":"https://img.serverlesscloud.cn/2020114/1578988490344-v2-8b2cd2c5275aa2c5a3c5083a148a7a9f_1200x500.jpg","authors":["Anycodes"],"categories":["user-stories"],"date":"2019-09-01T00:00:00.000Z","title":"如何通过 Serverless 与自然语言处理，让搜索引擎「看」到你的博客","description":"Serverless 与自然语言处理结合的一个小应用","authorslink":["https://www.zhihu.com/people/liuyu-43-97"],"translators":null,"translatorslink":null,"tags":["个人博客","serverless"],"keywords":"Serverless 自然语言处理","outdated":null},"wordCount":{"words":106,"sentences":34,"paragraphs":34},"fileAbsolutePath":"/opt/build/repo/content/blog/2019-09-01-search-engine-blog.md","fields":{"slug":"/blog/2019-09-01-search-engine-blog/","keywords":["serverless","云函数","keywords","serverlesscloud","summary"]}},"recommendBlogs":{"edges":[{"node":{"id":"4300b21c-7209-5256-86ff-0d38e3daec9b","frontmatter":{"thumbnail":"https://main.qcloudimg.com/raw/14f1c8eed372e76c1b139703b2f6d0fa.jpg","authors":["KieranMcCarthy"],"categories":["user-stories","engineering-culture"],"date":"2018-01-09T00:00:00.000Z","title":"我是如何在四年时间里，从厨师转行为 Serverless 应用开发者","description":"我是厨师出身，现在成为了一名 Serverless 应用开发者。","authorslink":["https://serverless.com/author/kieranmccarthy/"],"translators":["Aceyclee"],"translatorslink":["https://www.zhihu.com/people/Aceyclee"],"tags":["应用开发","Serverless"],"keywords":"Serverless 应用开发,Serverless 管理,厨师转行为 Serverless 应用开发者","outdated":null},"wordCount":{"words":285,"sentences":38,"paragraphs":36},"fileAbsolutePath":"/opt/build/repo/content/blog/2018-01-09-from-chef-to-serverless-developer-in-4-years.md","fields":{"slug":"/blog/2018-01-09-from-chef-to-serverless-developer-in-4-years/","keywords":["无服务器","无服务器开发","云函数","学习","Serverless","构建","Framework","开发者","服务器","应用","学位","简历"]}}},{"node":{"id":"665f9ce2-4451-59fd-bf98-1861789d3b3b","frontmatter":{"thumbnail":"https://s3-us-west-2.amazonaws.com/assets.blog.serverless.com/Serverless_logo.png","authors":["AndreaPasswater"],"categories":["guides-and-tutorials","engineering-culture"],"date":"2018-03-19T00:00:00.000Z","title":"如何为无服务器开放源代码项目做贡献","description":"想要为无服务器开放源代码项目做贡献？您可以遵循下面的指南。","authorslink":null,"translators":null,"translatorslink":null,"tags":null,"keywords":null,"outdated":null},"wordCount":{"words":96,"sentences":36,"paragraphs":36},"fileAbsolutePath":"/opt/build/repo/content/blog/2018-03-19-how-contribute-to-serverless-open-source.md","fields":{"slug":"/blog/2018-03-19-how-contribute-to-serverless-open-source/","keywords":["serverless","无服务器","serverless","github","插件","服务器","贡献","示例","blog","contribute"]}}},{"node":{"id":"a3e92579-65c3-5159-937c-32d18c5df7d7","frontmatter":{"thumbnail":"https://s3-us-west-2.amazonaws.com/assets.blog.serverless.com/why-not/why-not-header.png","authors":["AndreaPasswater"],"categories":["guides-and-tutorials","operations-and-observability","engineering-culture"],"date":"2018-03-21T00:00:00.000Z","title":"不适合选择无服务器的情境及原因","description":"无服务器既有优点也有缺点。那么，哪些情境下不适合选择无服务器？原因又是什么呢？","authorslink":null,"translators":null,"translatorslink":null,"tags":null,"keywords":null,"outdated":null},"wordCount":{"words":163,"sentences":43,"paragraphs":43},"fileAbsolutePath":"/opt/build/repo/content/blog/2018-03-21-when-why-not-use-serverless.md","fields":{"slug":"/blog/2018-03-21-when-why-not-use-serverless/","keywords":["faas","react","serverless","spa","无服务器","无服务器函数","无服务器架构","无服务器开发","服务器","twitter","serverless","blockquote","lang","script","en"]}}},{"node":{"id":"6a16520b-7886-582e-9182-64e50712d486","frontmatter":{"thumbnail":"https://s3-us-west-2.amazonaws.com/assets.blog.serverless.com/vendor+choice/serverless-data-portability.jpg","authors":["NickGottlieb"],"categories":["engineering-culture","guides-and-tutorials"],"date":"2018-06-20T00:00:00.000Z","title":"浅谈无服务器、数据锁定和供应商选择","description":"供应商选择是如今 IT 领导者需要考虑的最重要事项，而这一点可利用数据可移植性来实现。","authorslink":null,"translators":null,"translatorslink":null,"tags":null,"keywords":null,"outdated":null},"wordCount":{"words":205,"sentences":33,"paragraphs":33},"fileAbsolutePath":"/opt/build/repo/content/blog/2018-06-20-data-lockin-vendor-choice-portability.md","fields":{"slug":"/blog/2018-06-20-data-lockin-vendor-choice-portability/","keywords":["go","serverless","无服务器","无服务器架构","供应商","serverless","开发人员","数据","锁定","选择","服务"]}}},{"node":{"id":"94741abb-10ba-5db1-9756-cd1d573473fa","frontmatter":{"thumbnail":"https://s3-us-west-2.amazonaws.com/assets.blog.serverless.com/webstorm-ide/streamline-webstorm-serverless2.jpg","authors":["EslamHefnawy"],"categories":["guides-and-tutorials","engineering-culture"],"date":"2018-08-15T00:00:00.000Z","title":"如何使用 WebStorm 简化无服务器工作流程","description":"在本文中，我将和您分享如何使用 WebStorm 进行无服务器特定的 IDE 设置以及如何利用它来极大地加快无服务器工作流程。","authorslink":null,"translators":null,"translatorslink":null,"tags":null,"keywords":null,"outdated":null},"wordCount":{"words":234,"sentences":54,"paragraphs":54},"fileAbsolutePath":"/opt/build/repo/content/blog/2018-08-15-streamline-serverless-workflow-webstorm.md","fields":{"slug":"/blog/2018-08-15-streamline-serverless-workflow-webstorm/","keywords":["nodejs","serverless","无服务器","无服务器开发","serverless","WebStorm","webstorm","服务器","blog","assets"]}}},{"node":{"id":"713a0563-4bf9-5721-bacb-3b4ef609fe4a","frontmatter":{"thumbnail":"https://s3-us-west-2.amazonaws.com/assets.blog.serverless.com/camp-fire/camp-fire-housing-thumb.jpg","authors":["EricWyne"],"categories":["guides-and-tutorials","user-stories"],"date":"2018-12-05T00:00:00.000Z","title":"Serverless Twitter 机器人帮助为坎普山火受灾者安置住房","description":"加利福尼亚州的坎普山火致使数千人流离失所，为此，我构建了一个简单的 Serverless Twitter 机器人来帮助将受灾者安置在临时住房！","authorslink":["https://serverless.com/author/ericwyne/"],"translators":["Aceyclee"],"translatorslink":["zhihu.com/people/Aceyclee"],"tags":null,"keywords":null,"outdated":null},"wordCount":{"words":157,"sentences":26,"paragraphs":26},"fileAbsolutePath":"/opt/build/repo/content/blog/2018-12-05-serverless-twitter-camp-fire.md","fields":{"slug":"/blog/2018-12-05-serverless-twitter-camp-fire/","keywords":["serverless","无服务器","云函数","Serverless","org","住房","Twitter","函数","受灾","机器人","山火"]}}},{"node":{"id":"98602143-b837-5f50-a24f-3b1ec76044d7","frontmatter":{"thumbnail":"https://s3-us-west-2.amazonaws.com/assets.blog.serverless.com/sqquid/sqquid-serverless-thumb.jpg","authors":["RonPeled"],"categories":["user-stories"],"date":"2018-12-17T00:00:00.000Z","title":"SQQUID：100% 无服务器初创公司","description":"SQQUID 将 AWS Lambda 和无服务器框架用于其核心产品和营销网站。我们来看看一个完全无服务器的初创公司是怎样的。","authorslink":null,"translators":null,"translatorslink":null,"tags":null,"keywords":null,"outdated":null},"wordCount":{"words":266,"sentences":42,"paragraphs":42},"fileAbsolutePath":"/opt/build/repo/content/blog/2018-12-17-sqquid-one-hundred-percent-serverless.md","fields":{"slug":"/blog/2018-12-17-sqquid-one-hundred-percent-serverless/","keywords":["go","serverless","无服务器","无服务器架构","服务器","架构","Lambda","集成","FaaS","串行","系统"]}}},{"node":{"id":"29dc2e58-d2ba-56f9-aee1-d21b0bc62e0e","frontmatter":{"thumbnail":"https://s3-us-west-2.amazonaws.com/assets.blog.serverless.com/ao-com-story/ao-serverless-thumbnail.png","authors":["NickGottlieb"],"categories":["user-stories"],"date":"2019-04-24T00:00:00.000Z","title":"AO.com：逐渐转向无服务器优先","description":"AO.com 的 SCV 团队率先尝试无服务器服务。折服于无服务器框架的快速周转时间和低维护成本，整个团队逐渐转向无服务器优先。","authorslink":null,"translators":null,"translatorslink":null,"tags":null,"keywords":null,"outdated":null},"wordCount":{"words":236,"sentences":42,"paragraphs":35},"fileAbsolutePath":"/opt/build/repo/content/blog/2019-04-24-ao-serverless-first.md","fields":{"slug":"/blog/2019-04-24-ao-serverless-first/","keywords":["serverless","无服务器","服务器","团队","Lambda","功能","构建"]}}}],"totalCount":89}},"pageContext":{"isCreatedByStatefulCreatePages":false,"blogId":"ae4fd2f8-515c-5aec-b584-38427ef33f7e","previousBlogId":"56b79d5f-8104-59ba-b8c8-c6d1b5518ded","nextBlogId":"97450b07-658b-5207-8216-1c7b9b51b115","categories":["guides-and-tutorials","user-stories"]}}}