Skip to content

Instantly share code, notes, and snippets.

@kaganisildak
Created April 11, 2023 22:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaganisildak/ced4e81f71ff058ac688008b92a4eec3 to your computer and use it in GitHub Desktop.
Save kaganisildak/ced4e81f71ff058ac688008b92a4eec3 to your computer and use it in GitHub Desktop.
from flask import Flask, request, jsonify, Response
import os, glob, sys
from threading import Thread, Event
from multiprocessing import Process, cpu_count
from io import BytesIO as BytesIO
class RepeatingTimer(Thread):
def __init__(self, interval_seconds, callback):
super().__init__()
self.stop_event = Event()
self.interval_seconds = interval_seconds
self.callback = callback
def run(self):
while not self.stop_event.wait(self.interval_seconds):
self.callback()
def stop(self):
self.stop_event.set()
app = Flask(__name__)
workers = (cpu_count() * 2) + 1
from flask_cors import CORS
cors = CORS(app, resources={r"/*": {"origins": "*", "allow_headers": "*"}})
app.config['JSON_SORT_KEYS'] = False
from dotenv import load_dotenv
load_dotenv(os.path.expanduser('~/.env'))
API_KEY = os.environ.get("API_KEY")
@app.before_request
def apikey_decorator():
if request.method.lower() == 'options':
return Response()
if "api-key" in request.headers:
if request.headers["api-key"] != API_KEY:
resp = jsonify({'message' : 'API key is invalid. Please enter valid key.'})
resp.status_code = 400
return resp
else:
resp = jsonify({'message' : 'API key is missing.'})
resp.status_code = 400
return resp
@app.route('/filestatus/<uid>', methods=['GET'])
def filestatus(uid):
if uid:
return jsonify({"status" : "There is no file with this uid : " + uid})
else:
return "Bad Request", 400
@app.route('/upload', methods=['POST'])
def upload_file():
# check if the post request has the file part
success = False
if 'file' not in request.files:
resp = jsonify({'message' : 'No file part in the request.'})
resp.status_code = 400
return resp
else:
resp = jsonify({'message' : 'File successfully uploaded '})
resp.status_code = 200
return resp
import gunicorn.app.base
class StandaloneApplication(gunicorn.app.base.BaseApplication):
def __init__(self, app, options=None):
self.options = options or {}
self.application = app
super().__init__()
def load_config(self):
config = {key: value for key, value in self.options.items()
if key in self.cfg.settings and value is not None}
for key, value in config.items():
self.cfg.set(key.lower(), value)
def load(self):
return self.application
if __name__ == '__main__':
options = {
'bind': '127.0.0.1:8000',
'workers': workers,
'umask' : 0o000,
}
StandaloneApplication(app, options).run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment