Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96181
License: OTHER
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_path = os.path.join(os.environ['HOME'], ".smc", "info.json")
16
info = json.load(open(info_path, '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
<li><a href="%(route)s/header">%(route)s/header - header information</a></li>
47
</ul>""" % {
48
'route': base_url
49
}
50
return html_template % {'title': 'Info', 'content': content}
51
52
53
@app.route(base_url + '/get', methods=['GET'])
54
def get_something():
55
content = """<p>Try something like <a href="%(base_url)s/get?something=foo">%(base_url)s/get?something=foo</a></p>""" % {
56
'base_url': base_url
57
}
58
if request.method == 'GET':
59
something = request.args.get("something", "")
60
if len(something) > 0:
61
content = "Got " + something
62
return html_template % {'title': 'Info', 'content': content}
63
64
65
@app.route(base_url + '/header', methods=['GET'])
66
def get_header():
67
68
header = ''
69
70
for k, v in request.headers.iteritems():
71
header += '{} = {}\n'.format(k, v)
72
73
content = '''
74
<div>The header information I got about you ...</div>
75
<pre>
76
{header}
77
</pre>
78
'''.format(header=header)
79
80
return content
81
82
83
if __name__ == "__main__":
84
try:
85
info = json.load(
86
open(os.path.join(os.environ['HOME'], ".smc", "info.json"), 'r'))
87
print("Try to open https://cocalc.com" + base_url + '/')
88
app.run(host='0.0.0.0', port=port)
89
import sys
90
sys.exit(0)
91
except Exception as e:
92
print "... failed, try another port (change the port= line in the script) \n%s" % e
93
94