zele-backend/routes.py
2024-10-23 09:21:48 -04:00

47 lines
1.8 KiB
Python

import os
from flask import jsonify, request, make_response
from sqlalchemy import inspect, func, text
from sqlalchemy.orm import sessionmaker
from geoalchemy2 import Geometry
from shapely import wkb
def register_route(app,db):
@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"
@app.route('/table')
def list_table():
inspector = inspect(db.engine)
tables = inspector.get_table_names()
return jsonify(tables)
@app.route('/find_agents', methods=['POST','OPTIONS'])
def find_points():
if request.method == 'OPTIONS':
response = make_response()
response.headers.add("Access-Control-Allow-Origin", "http://localhost:4000")
response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
response.headers.add('Access-Control-Allow-Methods', 'POST, OPTIONS')
return response
elif request.method == 'POST':
data = request.json
coordinates = data.get('coordinates', [])
polygon_wkt = 'POLYGON(({}))'.format(', '.join(f'{lng} {lat}' for lat, lng in coordinates))
# Construct the query string
query = f"""
SELECT id, geom FROM agents
WHERE ST_Contains(
ST_Transform(ST_GeomFromText('{polygon_wkt}', 4326), 4326),
geom
)
"""
with db.engine.connect() as connection:
results = connection.execute(text(query)).fetchall()
# Convert results to a list of dictionaries for JSON serialization
results_list = [{"id": result.id, "geom": [wkb.loads(bytes.fromhex(result.geom)).x, wkb.loads(bytes.fromhex(result.geom)).y]} for result in results]
return jsonify(results_list)