Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download

Github repo cloud-examples: https://github.com/sagemath/cloud-examples

Views: 7963
License: MIT
1
#!/usr/bin/env python
2
# -*- coding: utf-8 -*-
3
# This runs a demo-webservice inside SMC.
4
# Run by typing
5
# sage -python main.py
6
7
import json
8
import os
9
10
from flask import Flask, request
11
app = Flask(__name__)
12
#app.debug = True # Uncomment this if you wish to debug
13
14
port = 8765
15
info = json.load(
16
open(os.path.join(os.environ['HOME'], ".smc", "info.json"), 'r'))
17
base_url = "/%s/port/%s" % (info['project_id'], port)
18
19
html_template = """
20
<!DOCTYPE html
21
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
22
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
23
<html>
24
25
<head>
26
<title>%(title)s</title>
27
</head>
28
29
<body>
30
31
<p>%(content)s</p>
32
33
</body>
34
</html>
35
"""
36
37
38
@app.route(base_url + '/', strict_slashes=False)
39
def info():
40
content = """<p>SMC Webservice running</p>
41
<p><b>Routes:</b></p>
42
43
<ul>
44
<li><a href="%(route)s/">%(route)s/ - list of routes</a></li>
45
<li><a href="%(route)s/get">%(route)s/get - simple get request</a></li>
46
</ul>""" % {'route': base_url}
47
return html_template % {'title': 'Info', 'content': content}
48
49
50
@app.route(base_url + '/get', methods=['GET'])
51
def get_something():
52
content = """<p>Try something like <a href="%(base_url)s/get?something=foo">%(base_url)s/get?something=foo</a></p>""" % {
53
'base_url': base_url}
54
if request.method == 'GET':
55
something = request.args.get("something", "")
56
if len(something) > 0:
57
content = "Got " + something
58
return html_template % {'title': 'Info', 'content': content}
59
60
if __name__ == "__main__":
61
try:
62
info = json.load(
63
open(os.path.join(os.environ['HOME'], ".smc", "info.json"), 'r'))
64
print("Try to open https://cloud.sagemath.com" + base_url + '/')
65
app.run(host='0.0.0.0', port=port)
66
import sys
67
sys.exit(0)
68
except Exception as e:
69
print "... failed, try another port (change the port= line in the script) \n%s" % e
70
71