|
from flask import Flask, request, jsonify |
|
import random |
|
import string |
|
import threading |
|
|
|
app = Flask(__name__) |
|
connections = {} |
|
lock = threading.Lock() |
|
|
|
def generate_id(): |
|
return ''.join(random.choices(string.ascii_letters + string.digits, k=8)) |
|
|
|
@app.route('/create_offer', methods=['POST']) |
|
def create_offer(): |
|
offer = request.json |
|
conn_id = generate_id() |
|
|
|
with lock: |
|
connections[conn_id] = { |
|
'offer': offer, |
|
'answer': None |
|
} |
|
|
|
return jsonify({'connection_id': conn_id}) |
|
|
|
@app.route('/get_offer/<conn_id>', methods=['GET']) |
|
def get_offer(conn_id): |
|
with lock: |
|
conn = connections.get(conn_id) |
|
if not conn: |
|
return jsonify({'error': 'Invalid ID'}), 404 |
|
return jsonify(conn['offer']) |
|
|
|
@app.route('/send_answer/<conn_id>', methods=['POST']) |
|
def send_answer(conn_id): |
|
with lock: |
|
if conn_id not in connections: |
|
return jsonify({'error': 'Invalid ID'}), 404 |
|
|
|
connections[conn_id]['answer'] = request.json |
|
return jsonify({'status': 'success'}) |
|
|
|
@app.route('/get_answer/<conn_id>', methods=['GET']) |
|
def get_answer(conn_id): |
|
with lock: |
|
conn = connections.get(conn_id) |
|
if not conn or not conn['answer']: |
|
return jsonify({'error': 'Not ready'}), 404 |
|
return jsonify(conn['answer']) |
|
|
|
if __name__ == '__main__': |
|
app.run(host='0.0.0.0', port=5000, threaded=True) |