· 5 years ago · Mar 11, 2021, 11:06 AM
1import os
2from flask import Flask, send_from_directory
3from flask_restful import Api
4from resources import *
5
6# ============================================================================================
7# =================================================================== INITIALIZATION =========
8# ============================================================================================
9
10# Create a new Flask application
11app = Flask(__name__)
12# Add a secret key. Important for hashing (e.g. with login handling)
13app.secret_key = os.getenv('SECRET')
14# Create a new API
15api = Api(app, prefix=os.getenv('API_PREFIX'))
16
17# ============================================================================================
18# =============================================================== FRONTEND REDIRECTS =========
19# ============================================================================================
20
21@app.route('/')
22def index():
23 """Redirects the base url '/' to the webshop/index.html file
24
25 Returns:
26 string: file content
27 """
28 return send_from_directory('../webshop', 'index.html')
29
30@app.route('/<path:path>')
31def shop(path):
32 """Redirects all requests to the front end (webshop)
33
34 Args:
35 path (path): path to requested file
36
37 Returns:
38 string: file content
39 """
40 return send_from_directory('../webshop', path)
41
42# ============================================================================================
43# =================================================================== ERROR HANDLING =========
44# ============================================================================================
45
46@app.errorhandler(404)
47def page_not_found(e):
48 """Returns a JSON on 404
49
50 Returns:
51 object: error message
52 """
53 return {'message': 'resource not found'}, 404
54
55# =================================================================== =========================
56# ======================================================================== ENDPOINTS =========
57# ============================================================================================
58
59api.add_resource(Categories, '/categories')
60api.add_resource(Products, '/products')
61api.add_resource(Product, '/products/<int:id>')
62api.add_resource(Category, '/categories/<int:id>/products')
63
64# ============================================================================================
65# ================================================================ START APPLICATION =========
66# ============================================================================================
67
68if __name__ == '__main__':
69 app.run(debug=True)
70