-
Notifications
You must be signed in to change notification settings - Fork 4
/
hello.py
60 lines (43 loc) · 1.6 KB
/
hello.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import os
import json
import StringIO
import shapely
from shapely.geometry import shape, mapping
from flask import Flask, request, send_file, jsonify, render_template
from werkzeug.utils import secure_filename
ALLOWED_EXTENSIONS = set(['js', 'json', 'geojson'])
app = Flask(__name__)
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
def get_centroids(polygons_json):
feature_collection = {
'type': 'FeatureCollection',
'features': []
}
for feature in json.loads(polygons_json)['features']:
feature_geom = shape(feature['geometry'])
feature_centroid = feature_geom.centroid
centroid = mapping(feature_centroid)
feature['geometry'] = centroid
feature_collection['features'].append(feature)
return feature_collection
@app.route('/', methods=['GET', 'POST'])
def operation():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file_type = filename.rsplit('.', 1)[1]
file_title = filename.rsplit('.', 1)[0]
polygons_json = file.read()
strIO = StringIO.StringIO()
strIO.write(json.dumps(get_centroids(polygons_json)))
strIO.seek(0)
centroids_filename = file_title + "_centroids.geojson"
return send_file(strIO, attachment_filename=centroids_filename, as_attachment=True)
return render_template('index.html')
@app.route('/centroids', methods=['POST'])
def api_centroids():
return jsonify(get_centroids(request.data))
if __name__ == '__main__':
app.run(debug=True)