minor improvements

This commit is contained in:
Kian 2024-10-23 09:21:48 -04:00
parent 0c07d7ea93
commit 2538e54764
3 changed files with 31 additions and 19 deletions

1
.gitignore vendored
View File

@ -2,3 +2,4 @@
/shelf/
/workspace.xml
.env
.pyc

View File

@ -1,6 +1,7 @@
import os
from dotenv import load_dotenv
from flask import Flask
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from routes import register_route
@ -13,5 +14,8 @@ db.init_app(app)
register_route(app, db)
CORS(app, resources={r"/find_agents": {"origins": os.getenv("ORIGINS")}})
if __name__ == '__main__':
app.run(debug=True)

View File

@ -1,5 +1,5 @@
import os
from flask import jsonify, request
from flask import jsonify, request, make_response
from sqlalchemy import inspect, func, text
from sqlalchemy.orm import sessionmaker
from geoalchemy2 import Geometry
@ -16,25 +16,32 @@ def register_route(app,db):
tables = inspector.get_table_names()
return jsonify(tables)
@app.route('/find_points/', methods=['POST'])
@app.route('/find_agents', methods=['POST','OPTIONS'])
def find_points():
data = request.json
coordinates = data.get('coordinates', [])
polygon_wkt = 'POLYGON(({}))'.format(', '.join(f'{lat} {lng}' for lat, lng in coordinates))
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
)
"""
# 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()
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]
# 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)
return jsonify(results_list)