added definitions of flask app
This commit is contained in:
+38
@@ -0,0 +1,38 @@
|
|||||||
|
from flask import Flask, request, jsonify
|
||||||
|
import os
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
from ipaddress import ip_address, ip_network
|
||||||
|
import logging
|
||||||
|
|
||||||
|
load_dotenv()
|
||||||
|
app = Flask(__name__)
|
||||||
|
|
||||||
|
@app.before_request
|
||||||
|
def check_authorized():
|
||||||
|
"""
|
||||||
|
Ensure request from allowed ip.
|
||||||
|
"""
|
||||||
|
# prepare variables
|
||||||
|
assert 'ALLOWED_IP_RANGE' in os.environ
|
||||||
|
allowed_ip_range = ip_network(os.getenv['ALLOWED_IP_RANGE'])
|
||||||
|
requesting_ip = ip_address(request.remote_addr)
|
||||||
|
# check that requesting ip is allowed
|
||||||
|
if requesting_ip not in allowed_ip_range:
|
||||||
|
logging.info(f'received request from unauthorised ip: {request.remote_addr}')
|
||||||
|
return jsonify(status='forbidden'), 403
|
||||||
|
logging.info(f'received request from {request.remote_addr}')
|
||||||
|
|
||||||
|
@app.before_request
|
||||||
|
def check_media_type():
|
||||||
|
"""
|
||||||
|
Ensure correct Content-Type of request
|
||||||
|
"""
|
||||||
|
if not request.headers.get('Content-Type').lower().startswith('application/json'):
|
||||||
|
logging.error(f'received request with wrong content type')
|
||||||
|
return jsonify(status='unsupported media type'), 415
|
||||||
|
|
||||||
|
@app.route('/test', methods=['POST'])
|
||||||
|
def test():
|
||||||
|
logging.debug(request.get_json(force=True))
|
||||||
|
return jsonify(status='success', sender=request.remote_addr)
|
||||||
|
|
||||||
Reference in New Issue
Block a user