diff --git a/.gitignore b/.gitignore index a248d74..dca588e 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ /shelf/ /workspace.xml .env +.pyc diff --git a/main.py b/main.py index a0713f9..8be3a81 100644 --- a/main.py +++ b/main.py @@ -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) diff --git a/routes.py b/routes.py index 83923e2..da97d60 100644 --- a/routes.py +++ b/routes.py @@ -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) \ No newline at end of file + return jsonify(results_list) \ No newline at end of file