Skip to content

Instantly share code, notes, and snippets.

@erm3nda
Created August 6, 2020 04:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erm3nda/7ba07ecd6b4ae577718f8e8899fcb7a4 to your computer and use it in GitHub Desktop.
Save erm3nda/7ba07ecd6b4ae577718f8e8899fcb7a4 to your computer and use it in GitHub Desktop.
This code shows how to create an https bridge with flask that sends json commands from network to json ipc server running locally #python #mpv
#!/usr/local/env python
# coding: utf8
from flask import Flask, jsonify, request, abort
import os, subprocess, json
ASSETS_DIR = os.path.dirname(os.path.abspath(__file__))
app = Flask(__name__)
def compose_command_json(json_data):
command = "echo "
command += "\'" + json_data + "\'" # this should be a valid json
command += " | socat - /tmp/mpvsocket" # hardcoded named pipe for now
return command
# ROUTES
@app.route('/', methods = ['POST'])
def index():
return 'Flask is running!'
@app.route('/json/', methods = ['POST'])
def json_parse():
#print(request.json)
#print(json.loads(request.data)["command"])
#print(request.json["command"])
if request.json:
command = compose_command_json(request.data.decode("utf8")) # compose command with json if is valid json
process_return = subprocess.check_output(command, shell=True)
return str(process_return), 200
else:
abort(400) #abort() works without return. Otherwise use `return "Page not found", 404` or even `return "Bad request", 400` manually
# START SERVER
if __name__ == '__main__':
#context = ('public.pem', 'private.pem') #certificate and key files
#app.run(debug=True, ssl_context=context)
app.run(debug=False, ssl_context="adhoc") # we will use adhoc mode, easier for develop and not a problem unless you try it with browser or browser-based extension.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment