Skip to content

Commit

Permalink
Upgrade flask to 2.3.2
Browse files Browse the repository at this point in the history
  • Loading branch information
jonthornton committed Aug 9, 2023
1 parent ced2c50 commit d85e635
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 29 deletions.
50 changes: 28 additions & 22 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
"""

from mtapi.mtapi import Mtapi
from flask import Flask, request, jsonify, render_template, abort, redirect
from flask.json import JSONEncoder
from flask import Flask, request, Response, render_template, abort, redirect
import json
from datetime import datetime
from functools import wraps, reduce
import logging
Expand Down Expand Up @@ -39,8 +39,7 @@
logging.basicConfig(level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")

class CustomJSONEncoder(JSONEncoder):

class CustomJSONEncoder(json.JSONEncoder):
def default(self, obj):
try:
if isinstance(obj, datetime):
Expand All @@ -51,7 +50,6 @@ def default(self, obj):
else:
return list(iterable)
return JSONEncoder.default(self, obj)
app.json_encoder = CustomJSONEncoder

mta = Mtapi(
app.config['MTA_KEY'],
Expand All @@ -61,11 +59,19 @@ def default(self, obj):
expires_seconds=app.config['CACHE_SECONDS'],
threaded=app.config['THREADED'])

def cross_origin(f):
def response_wrapper(f):
@wraps(f)
def decorated_function(*args, **kwargs):
resp = f(*args, **kwargs)

if not isinstance(resp, Response):
# custom JSON encoder; this is important
resp = Response(
response=json.dumps(resp, cls=CustomJSONEncoder),
status=200,
mimetype="application/json"
)

if app.config['DEBUG']:
resp.headers['Access-Control-Allow-Origin'] = '*'
elif 'CROSS_ORIGIN' in app.config:
Expand All @@ -76,31 +82,31 @@ def decorated_function(*args, **kwargs):
return decorated_function

@app.route('/')
@cross_origin
@response_wrapper
def index():
return jsonify({
return {
'title': 'MTAPI',
'readme': 'Visit https://github.com/jonthornton/MTAPI for more info'
})
}

@app.route('/by-location', methods=['GET'])
@cross_origin
@response_wrapper
def by_location():
try:
location = (float(request.args['lat']), float(request.args['lon']))
except KeyError as e:
print(e)
response = jsonify({
'error': 'Missing lat/lon parameter'
})
response.status_code = 400
return response
return Response(
response=json.dumps({'error': 'Missing lat/lon parameter'}),
status=400,
mimetype="application/json"
)

data = mta.get_by_point(location, 5)
return _make_envelope(data)

@app.route('/by-route/<route>', methods=['GET'])
@cross_origin
@response_wrapper
def by_route(route):

if route.islower():
Expand All @@ -113,7 +119,7 @@ def by_route(route):
abort(404)

@app.route('/by-id/<id_string>', methods=['GET'])
@cross_origin
@response_wrapper
def by_index(id_string):
ids = id_string.split(',')
try:
Expand All @@ -123,12 +129,12 @@ def by_index(id_string):
abort(404)

@app.route('/routes', methods=['GET'])
@cross_origin
@response_wrapper
def routes():
return jsonify({
return {
'data': sorted(mta.get_routes()),
'updated': mta.last_update()
})
}

def _envelope_reduce(a, b):
if a['last_update'] and b['last_update']:
Expand All @@ -143,10 +149,10 @@ def _make_envelope(data):
if data:
time = reduce(_envelope_reduce, data)['last_update']

return jsonify({
return {
'data': data,
'updated': time
})
}

if __name__ == '__main__':
app.run(use_reloader=False)
15 changes: 8 additions & 7 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
atomicwrites==1.3.0
attrs==19.1.0
Click==7.0
blinker==1.6.2
click==8.1.6
configparser==4.0.2
contextlib2==0.5.5
Flask==1.1.1
Flask==2.3.2
funcsigs==1.0.2
importlib-metadata==0.22
itsdangerous==1.1.0
Jinja2==2.11.3
MarkupSafe==0.23
importlib-metadata==6.8.0
itsdangerous==2.1.2
Jinja2==3.1.2
MarkupSafe==2.1.3
more-itertools==5.0.0
packaging==19.1
pathlib2==2.3.4
Expand All @@ -21,5 +22,5 @@ pytz==2019.2
scandir==1.10.0
six==1.12.0
wcwidth==0.1.7
Werkzeug==0.15.6
Werkzeug==2.3.6
zipp==0.6.0

0 comments on commit d85e635

Please sign in to comment.