major cleanup. Sir, yes, sir!
This commit is contained in:
parent
efc8f565bf
commit
6ebf34c4a9
85
app.py
Executable file → Normal file
85
app.py
Executable file → Normal file
@ -1,43 +1,58 @@
|
||||
#!/usr/bin/env python3
|
||||
from flask import Flask, render_template, url_for, request, redirect, Response, abort, session
|
||||
from flask_sock import Sock
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from werkzeug.middleware.proxy_fix import ProxyFix
|
||||
from datetime import datetime
|
||||
import magic
|
||||
import random
|
||||
import string
|
||||
import asyncio
|
||||
import websockets
|
||||
import json
|
||||
|
||||
app = Flask(__name__)
|
||||
app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)
|
||||
app.secret_key = '029c0gji3jfo3o8h938vhwtfmh3t39th'
|
||||
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///cloudvars.db'
|
||||
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
|
||||
db = SQLAlchemy(app)
|
||||
sock = Sock(app)
|
||||
clients = {}
|
||||
vars = {}
|
||||
|
||||
class variables(db.Model):
|
||||
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
|
||||
namespace = db.Column(db.String(64), nullable=False)
|
||||
project = db.Column(db.String(64), nullable=False)
|
||||
name = db.Column(db.String(64), nullable=False)
|
||||
value = db.Column(db.String(64), nullable=True)
|
||||
async def handshake(ws,data):
|
||||
project_id = data.get('project_id','')
|
||||
user = data.get('user')
|
||||
print(f"{project_id} new user connected from {ws.host}:{ws.port}")
|
||||
|
||||
if not clients.get(project_id):
|
||||
clients[project_id] = []
|
||||
clients[project_id].append(ws)
|
||||
await get_variables(ws,project_id,user)
|
||||
return (project_id,user)
|
||||
|
||||
@app.context_processor
|
||||
def get_date():
|
||||
date = datetime.now()
|
||||
return { "now": date.strftime("%Y-%m-%d") }
|
||||
async def get_variables(ws,project_id,user):
|
||||
for name,value in vars.get(project_id,{}).items():
|
||||
if not name:
|
||||
continue
|
||||
await ws.send(json.dumps({"method":"set","name":name,"value":value}))
|
||||
|
||||
@sock.route('/')
|
||||
def echo(sock):
|
||||
while True:
|
||||
data = json.loads(sock.receive())
|
||||
sock.send(json.dumps({"method":"set","name":"test","value":"abcd"}))
|
||||
async def set_variable(project_id,var):
|
||||
if not vars.get(project_id,''):
|
||||
vars[project_id] = {}
|
||||
vars[project_id][var.get('name','')] = var.get('value','')
|
||||
await websockets.broadcast(clients.get(project_id,[]),json.dumps(var))
|
||||
|
||||
@app.route('/', methods = ['GET'])
|
||||
def index():
|
||||
return render_template('index.html')
|
||||
async def disconnect(project_id,user):
|
||||
print("disconnecting",user)
|
||||
clients.get(project_id,[]).pop(user)
|
||||
|
||||
|
||||
async def process(ws, path):
|
||||
project_id = ""
|
||||
user = ""
|
||||
async for msg in ws:
|
||||
print(f"< {user} - {msg}")
|
||||
try:
|
||||
data = json.loads(msg)
|
||||
method = data.get('method','')
|
||||
if method == 'handshake':
|
||||
project_id,user = await handshake(ws,data)
|
||||
if method in ['set','create']:
|
||||
await set_variable(project_id,data)
|
||||
finally:
|
||||
pass
|
||||
await disconnect(project_id,ws)
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=True)
|
||||
try:
|
||||
start_server = websockets.serve(process, 'localhost', 5000, compression=None)
|
||||
finally:
|
||||
pass
|
||||
asyncio.get_event_loop().run_until_complete(start_server)
|
||||
asyncio.get_event_loop().run_forever()
|
2
app.sh
2
app.sh
@ -5,4 +5,4 @@ cd $BASE
|
||||
git pull
|
||||
source env/bin/activate
|
||||
pip3 install -r requirements.txt
|
||||
gunicorn -D --bind 0.0.0.0:80 --pid /var/run/webapp.pid wsgi:app
|
||||
python3 app.py
|
@ -1,56 +0,0 @@
|
||||
<html>
|
||||
<body>
|
||||
<div id="data"></div>
|
||||
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
|
||||
<script>
|
||||
let socket = new WebSocket("ws://localhost:5000");
|
||||
let projectID = "einTollesProjekt"; // hier project ID eintragen
|
||||
|
||||
function setVariable(name, value) {
|
||||
console.log(`Setting variable: ${name} = ${value}`);
|
||||
socket.send(JSON.stringify({
|
||||
method: "set",
|
||||
project_id: projectID,
|
||||
name,
|
||||
value
|
||||
}));
|
||||
};
|
||||
|
||||
|
||||
socket.onopen = function(e) {
|
||||
console.log("connection established");
|
||||
socket.send(JSON.stringify({
|
||||
method: "handshake",
|
||||
project_id: projectID,
|
||||
user: "testClient"+Math.random()
|
||||
}));
|
||||
|
||||
setInterval(function() { setVariable('test','einTollerText'+Math.random()) }, 5000);
|
||||
};
|
||||
|
||||
socket.onmessage = function(event) {
|
||||
console.log(event.data);
|
||||
for (const message of event.data.split("\n")) {
|
||||
console.log(`${message}`);
|
||||
const obj = JSON.parse(message);
|
||||
if (obj.method === "set") {
|
||||
// variable name in obj.name, Wert der Variablen steht in obj.value
|
||||
$('#data').html(`<b/>${obj.name}:</b> <pre>${obj.value}</pre>`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
socket.onclose = function(event) {
|
||||
if (event.wasClean) {
|
||||
console.log(`connection closed cleanly, code=${event.code} reason=${event.reason}`);
|
||||
} else {
|
||||
console.log('connection died');
|
||||
}
|
||||
};
|
||||
|
||||
socket.onerror = function(error) {
|
||||
console.log(`[error] ${error.data}`);
|
||||
};
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
396
docs/cloud.html
Normal file
396
docs/cloud.html
Normal file
File diff suppressed because one or more lines are too long
@ -1,35 +0,0 @@
|
||||
<html>
|
||||
<body>
|
||||
<div id="data"></div>
|
||||
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
|
||||
<script>
|
||||
let socket = new WebSocket("ws://localhost:5000/");
|
||||
socket.onopen = function(e) {
|
||||
console.log("connection established");
|
||||
socket.send("Hello World");
|
||||
setInterval(function () {socket.send("hello " + Math.random())}, 1000);
|
||||
};
|
||||
|
||||
socket.onmessage = function(event) {
|
||||
for (const message of event.data.split("\n")) {
|
||||
console.log(`${message}`);
|
||||
// variable name in obj.name, Wert der Variablen steht in obj.value
|
||||
$('#data').html(`<b/>${message}</b>`);
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
socket.onclose = function(event) {
|
||||
if (event.wasClean) {
|
||||
console.log(`connection closed cleanly, code=${event.code} reason=${event.reason}`);
|
||||
} else {
|
||||
console.log('connection died');
|
||||
}
|
||||
};
|
||||
|
||||
socket.onerror = function(error) {
|
||||
console.log(`[error] ${error.data}`);
|
||||
};
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
@ -1,56 +0,0 @@
|
||||
<html>
|
||||
<body>
|
||||
<div id="data"></div>
|
||||
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
|
||||
<script>
|
||||
let socket = new WebSocket("ws://localhost:5000");
|
||||
let projectID = "5678"; // hier project ID eintragen
|
||||
|
||||
function setVariable(name, value) {
|
||||
console.log(`Setting variable: ${name} = ${value}`);
|
||||
socket.send(JSON.stringify({
|
||||
method: "set",
|
||||
project_id: projectID,
|
||||
name,
|
||||
value
|
||||
}));
|
||||
};
|
||||
|
||||
|
||||
socket.onopen = function(e) {
|
||||
console.log("connection established");
|
||||
socket.send(JSON.stringify({
|
||||
method: "handshake",
|
||||
project_id: projectID,
|
||||
user: "testClient"+Math.random()
|
||||
}));
|
||||
|
||||
setInterval(function() { setVariable('test',666) }, 100);
|
||||
};
|
||||
|
||||
socket.onmessage = function(event) {
|
||||
console.log(event.data);
|
||||
for (const message of event.data.split("\n")) {
|
||||
console.log(`${message}`);
|
||||
const obj = JSON.parse(message);
|
||||
if (obj.method === "set") {
|
||||
// variable name in obj.name, Wert der Variablen steht in obj.value
|
||||
$('#data').html(`<b/>${obj.name}:</b> <pre>${obj.value}</pre>`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
socket.onclose = function(event) {
|
||||
if (event.wasClean) {
|
||||
console.log(`connection closed cleanly, code=${event.code} reason=${event.reason}`);
|
||||
} else {
|
||||
console.log('connection died');
|
||||
}
|
||||
};
|
||||
|
||||
socket.onerror = function(error) {
|
||||
console.log(`[error] ${error.data}`);
|
||||
};
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
@ -1,43 +0,0 @@
|
||||
<html>
|
||||
<body>
|
||||
<div id="data"></div>
|
||||
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
|
||||
<script>
|
||||
let socket = new WebSocket("ws://localhost:5000");
|
||||
let projectID = "einTollesProjekt"; // hier project ID eintragen
|
||||
|
||||
socket.onopen = function(e) {
|
||||
console.log("connection established");
|
||||
socket.send(JSON.stringify({
|
||||
method: "handshake",
|
||||
project_id: projectID,
|
||||
user: "testClient"+Math.random()
|
||||
}));
|
||||
};
|
||||
|
||||
socket.onmessage = function(event) {
|
||||
console.log(event.data);
|
||||
for (const message of event.data.split("\n")) {
|
||||
console.log(`${message}`);
|
||||
const obj = JSON.parse(message);
|
||||
if (obj.method === "set") {
|
||||
// variable name in obj.name, Wert der Variablen steht in obj.value
|
||||
$('#data').html(`<b/>${obj.name}:</b> <pre>${obj.value}</pre>`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
socket.onclose = function(event) {
|
||||
if (event.wasClean) {
|
||||
console.log(`connection closed cleanly, code=${event.code} reason=${event.reason}`);
|
||||
} else {
|
||||
console.log('connection died');
|
||||
}
|
||||
};
|
||||
|
||||
socket.onerror = function(error) {
|
||||
console.log(`[error] ${error.data}`);
|
||||
};
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
@ -1,11 +1 @@
|
||||
python-magic
|
||||
Click
|
||||
Flask
|
||||
Flask-SQLAlchemy
|
||||
gunicorn
|
||||
itsdangerous
|
||||
Jinja2
|
||||
MarkupSafe
|
||||
SQLAlchemy
|
||||
Werkzeug
|
||||
flask-sock
|
||||
websockets
|
@ -1,22 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta http-equiv="X-UA-Compatible" content="ie=edge">
|
||||
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
|
||||
{% block head %}<title>Scratch Cloudvars Server</title>{% endblock %}
|
||||
</head>
|
||||
<body>
|
||||
<header class="w3-container w3-border-bottom w3-border-blue-grey w3-light-grey w3-margin-bottom" style="position: fixed; top: 0; width: 100vw; height: 3em">
|
||||
{% block header %}<span><a class="w3-button" href="/"><i class="material-icons w3-xlarge">home</i></a>Scratch Cloudvars Server</span>{% endblock %}
|
||||
</header>
|
||||
<div class="w3-container" style="margin-top: 4em; margin-bottom:3em">
|
||||
{% block content %}{% endblock %}
|
||||
</div>
|
||||
<footer class="w3-container w3-border-top w3-light-grey w3-border-blue-grey w3-center" style="position: fixed; bottom: 0; width: 100vw; height: auto">
|
||||
{% block footer %}<div class="w3-small">{{ now }} - {{ request.base_url }}</div>{% endblock %}
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
@ -1,20 +0,0 @@
|
||||
{% extends 'base.html' %}
|
||||
|
||||
{% block content %}
|
||||
<div class="w3-display-container" style="height: 200px">
|
||||
<div class="w3-row w3-half w3-display-middle">
|
||||
<div class="w3-blue-grey w3-col w3-mobile s6">
|
||||
<a class="w3-block w3-button" href="/train">
|
||||
<i class="material-icons w3-jumbo">school</i>
|
||||
<p>train</p>
|
||||
</a>
|
||||
</div>
|
||||
<div class="w3-blue-grey w3-col w3-mobile s6">
|
||||
<a class="w3-block w3-button" href="/manage">
|
||||
<i class="material-icons w3-jumbo">settings_applications</i>
|
||||
<p>manage vocabulary</p>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
57
test.py
57
test.py
@ -1,57 +0,0 @@
|
||||
import asyncio
|
||||
import websockets
|
||||
import json
|
||||
|
||||
clients = {}
|
||||
vars = {}
|
||||
|
||||
async def handshake(ws,j):
|
||||
if not clients.get(j.get('project_id')):
|
||||
clients[j.get('project_id')] = {}
|
||||
clients[j.get('project_id')][j.get('user')] = ws
|
||||
print(f"{j.get('user')} connected from {ws.host}:{ws.port}")
|
||||
return(j.get('project_id'),j.get('user'))
|
||||
|
||||
async def get_variables(websocket,project_id,user):
|
||||
for name,value in vars.get(project_id,{}).items():
|
||||
if not name:
|
||||
continue
|
||||
await websocket.send(json.dumps({"method":"set","name":name,"value":value}))
|
||||
|
||||
async def set_variable(project_id,user,var):
|
||||
if not vars.get(project_id,''):
|
||||
vars[project_id] = {}
|
||||
vars[project_id][var.get('name','')] = var.get('value','')
|
||||
|
||||
data = json.dumps(var)
|
||||
for name,ws in clients.get(project_id,{}).items():
|
||||
if name == user:
|
||||
continue
|
||||
print(f"> {name} - {data}")
|
||||
await ws.send(data)
|
||||
|
||||
async def disconnect(project_id,user):
|
||||
print("disconnecting",user)
|
||||
clients.get(project_id,[]).pop(user)
|
||||
|
||||
|
||||
async def process(websocket, path):
|
||||
project_id = ""
|
||||
user = ""
|
||||
async for msg in websocket:
|
||||
print(f"< {user} - {msg}")
|
||||
try:
|
||||
data = json.loads(msg)
|
||||
method = data.get('method','')
|
||||
if method == 'handshake':
|
||||
project_id,user = await handshake(websocket,data)
|
||||
await get_variables(websocket,project_id,user)
|
||||
if method in ['set','create']:
|
||||
await set_variable(project_id,user,data)
|
||||
finally:
|
||||
pass
|
||||
await disconnect(project_id,user)
|
||||
|
||||
start_server = websockets.serve(process, 'localhost', 5000, compression=None)
|
||||
asyncio.get_event_loop().run_until_complete(start_server)
|
||||
asyncio.get_event_loop().run_forever()
|
Loading…
x
Reference in New Issue
Block a user