Skip to content

Instantly share code, notes, and snippets.

@burrussmp
Created July 11, 2020 21:37
Show Gist options
  • Save burrussmp/13aa571219be6c8dd2fd1e2538fd1f9d to your computer and use it in GitHub Desktop.
Save burrussmp/13aa571219be6c8dd2fd1e2538fd1f9d to your computer and use it in GitHub Desktop.
A python flask server that runs in the background and can be used in a Google Colab environment
## imports
import flask
from flask import Flask
from flask_cors import CORS
from flask_ngrok import run_with_ngrok
import threading
import trace
import sys
import time
## create Flask app
app = Flask(__name__)
run_with_ngrok(app)
CORS(app)
## a global variable your application can update which the server can provide
## This can easily be replaced by an alternative request to an actual DB to avoid a global variable
YOURDATA = []
@app.route('/data', methods=['GET'])
def get_signals():
# this is returned to the client - note, it will take data_obj, and convert it to a Javascript object
data_obj = {
'data': YOURDATA
return response
class server_thread_wrapper(threading.Thread):
def __init__(self, *args, **keywords):
threading.Thread.__init__(self, *args, **keywords)
self.killed = False
def start(self):
self.__run_backup = self.run
self.run = self.__run
threading.Thread.start(self)
def __run(self):
sys.settrace(self.globaltrace)
self.__run_backup()
self.run = self.__run_backup
def globaltrace(self, frame, event, arg):
if event == 'call':
return self.localtrace
else:
return None
def localtrace(self, frame, event, arg):
if self.killed:
if event == 'line':
raise SystemExit()
return self.localtrace
def kill(self):
self.killed = True
def start_server():
server = server_thread_wrapper(target=app.run)
server.start()
return server
def kill_server():
server.kill()
server.join()
## start the server
server = start_server()
## temp wait
time.sleep(4)
## show the url to copy to access the server
print("\n\nCopy this address to the Observable notebook!")
! curl -s http://localhost:4040/api/tunnels | jq -r '.tunnels[0].public_url'
## kill the server
# kill_server()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment