-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.py
93 lines (70 loc) · 2.45 KB
/
server.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import os
from os.path import join, dirname
from dotenv import load_dotenv
from flask import Flask, jsonify
from flask_cors import CORS
from flask_jwt_extended import JWTManager
from flasgger import Swagger
from app.routes import api
from app.models import db
from app.helpers.cache_helper import cache
# Load env variabes
dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)
def create_app(config_name):
""" app factory """
# import config options
from config.config import app_config
app = Flask(__name__)
# allow cross-domain requests
CORS(app)
# use running config settings on app
app.config.from_object(app_config[config_name])
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# register app with the db
db.init_app(app)
# initialize api resources
api.init_app(app)
# initialize jwt with app
jwt = JWTManager(app)
# initialize cache with app
cache.init_app(app)
# swagger
app.config['SWAGGER'] = {
'title': 'flask-app backend API',
'uiversion': 3
}
Swagger(app, template_file='api_docs.json')
# handle default 404 exceptions with a custom response
@app.errorhandler(404)
def resource_not_found(exception):
response = jsonify(dict(status='fail', data={
'error': 'Not found', 'message': 'The requested URL was'
' not found on the server. If you entered the URL '
'manually please check and try again'
}))
response.status_code = 404
return response
# both error handlers below handle default 500 exceptions with a custom
# response
@app.errorhandler(500)
def internal_server_error(error):
response = jsonify(dict(status=error, error='Internal Server Error',
message='The server encountered an internal error and was'
' unable to complete your request. Either the server is'
' overloaded or there is an error in the application'))
response.status_code = 500
return response
@jwt.additional_claims_loader
def add_claims_to_access_token(user):
return {
# Add claims here
}
@jwt.user_identity_loader
def user_identity_lookup(user):
return user.get('id', None)
return app
# create app instance using running config
app = create_app(os.getenv('FLASK_ENV'))
if __name__ == '__main__':
app.run()