我有一项要求非常特殊的大学作业。 关键是我们需要构建一个使用 2 种不同语言的 Web 应用程序。我知道的奇怪要求。
我立即想到或许可以使用 Scala 和 Play Framework 以 JSON 格式提供数据,然后使用某种 Python 客户端将 REST 服务呈现为 HTML。
问题是我对此很陌生。我以前从未做过 REST 的东西,甚至连术语都令人望而生畏。然而,我已经成功地启动并运行了几个模型,为 Json 服务。现在我需要渲染它。
您会推荐什么来满足该要求?还有其他想法吗?理想情况下,我仍然喜欢使用 Scala 和 Play,但除了这个限制之外,我不在乎还有什么。
编辑:我知道这是一个奇怪的要求。为什么我不直接使用 Play 来呈现 HTML...?唉,我不能。
最佳答案
我创建了一个非常简单的项目来展示如何做到这一点:
https://github.com/jamesward/playscalapython
没什么好说的。这是游戏!/Scala 应用程序:
package controllers
import play._
import play.mvc._
object Application extends Controller {
def index = {
val widget1: Widget = Widget(1, "The first Widget")
val widget2: Widget = Widget(2, "A really special Widget")
val widget3: Widget = Widget(3, "Just another Widget")
val widgets: Vector[Widget] = Vector(widget1, widget2, widget3)
Json(widgets.toArray)
}
}
case class Widget(val id: Int, val name: String)
这是使用 Play 中的 JSON 的 Python 应用程序!应用:
import os
import simplejson
import requests
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
jsonString = requests.get(os.environ.get("JSON_SERVICE_URL", "http://localhost:9000"))
widgets = simplejson.loads(jsonString.content)
htmlResponse = "<html><body>"
for widget in widgets:
htmlResponse += "Widget " + str(widget['id']) + " = " + widget['name'] + "</br>"
htmlResponse += "</body></html>"
return htmlResponse
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)
关于java - Scala 和 Play-Framework 公开 REST 服务。现在渲染(但需要使用 Scala 以外的东西),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7700801/