Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala and Play-Framework exposing REST services. Now to render (but need to use something other then Scala)

I have a university assignment with a very peculiar requirement. The crux of it is that we need to build a web application that utilizes 2 different languages. Weird requirement I know.

I immediately thought to perhaps have Scala and the Play Framework serving data in JSON, and then have some sort of Python client, render the REST services as HTML.

The issue is I am very new to this. I've never done REST stuff before, and even the terminology is daunting. I have however managed to get several models up and running with Play, serving the Json. Now I need to render it.

What would you recommend to satisfy that requirement? Any other ideas?. Ideally I would still like to use Scala and Play, but apart from that constraint I don't care what else.

Edit: I know it's a weird requirement. Why wouldn't I just use Play to render the HTML...? Alas I can't.

like image 638
Dominic Bou-Samra Avatar asked Oct 09 '11 01:10

Dominic Bou-Samra


1 Answers

I created a very simple project that shows how to do this:
https://github.com/jamesward/playscalapython

There isn't much to it. Here is the Play! / Scala app:

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)

Here is the Python app that consumes the JSON from the Play! app:

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)
like image 98
James Ward Avatar answered Sep 21 '22 19:09

James Ward