blueprints.py 3.88 KB
Newer Older
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
1
2
#!/usr/bin/python
# -*- coding: utf-8 -*-
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
3
4
# Copyright 2014 J. Fernando Sánchez Rada - Grupo de Sistemas Inteligentes
# DIT, UPM
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
5
#
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
6
7
8
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
9
#
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
10
# http://www.apache.org/licenses/LICENSE-2.0
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
11
#
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
12
# Unless required by applicable law or agreed to in writing, software
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
13
14
15
16
#    distributed under the License is distributed on an "AS IS" BASIS,
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    See the License for the specific language governing permissions and
#    limitations under the License.
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
17
18
19
"""
Blueprints for Senpy
"""
20
21
from flask import Blueprint, request, current_app, render_template, url_for, jsonify
from .models import Error, Response, Plugins, read_schema
22
from .api import NIF_PARAMS, WEB_PARAMS, parse_params
23
from functools import wraps
24

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
25
import json
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
26
import logging
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
27

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
28
29
logger = logging.getLogger(__name__)

30
31
api_blueprint = Blueprint("api", __name__)
demo_blueprint = Blueprint("demo", __name__)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
32

J. Fernando Sánchez's avatar
YAPFed    
J. Fernando Sánchez committed
33

34
def get_params(req):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
35
    if req.method == 'POST':
36
        indict = req.form.to_dict(flat=True)
J. Fernando Sánchez's avatar
Oups    
J. Fernando Sánchez committed
37
    elif req.method == 'GET':
38
        indict = req.args.to_dict(flat=True)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
39
    else:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
40
        raise Error(message="Invalid data")
41
    return indict
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
42

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
43

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
44
@demo_blueprint.route('/')
Ignacio Corcuera's avatar
Ignacio Corcuera committed
45
46
47
def index():
    return render_template("index.html")

J. Fernando Sánchez's avatar
YAPFed    
J. Fernando Sánchez committed
48

49
50
51
@api_blueprint.route('/contexts/<entity>.jsonld')
def context(entity="context"):
    return jsonify({"@context": Response.context})
Ignacio Corcuera's avatar
Ignacio Corcuera committed
52

J. Fernando Sánchez's avatar
YAPFed    
J. Fernando Sánchez committed
53

54
55
@api_blueprint.route('/schemas/<schema>')
def schema(schema="definitions"):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
56
    try:
57
        return jsonify(read_schema(schema))
J. Fernando Sánchez's avatar
YAPFed    
J. Fernando Sánchez committed
58
    except Exception:  # Should be FileNotFoundError, but it's missing from py2
59
60
        return Error(message="Schema not found", status=404).flask()

J. Fernando Sánchez's avatar
YAPFed    
J. Fernando Sánchez committed
61

62
63
64
65
66
def basic_api(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        print('Getting request:')
        print(request)
67
68
69
70
71
72
73
        raw_params = get_params(request)
        web_params = parse_params(raw_params, spec=WEB_PARAMS)

        if hasattr(request, 'params'):
            request.params.update(raw_params)
        else:
            request.params = raw_params
74
75
76
77
        try:
            response = f(*args, **kwargs)
        except Error as ex:
            response = ex
78
79
        in_headers = web_params["inHeaders"] != "0"
        headers = {'X-ORIGINAL-PARAMS': raw_params}
J. Fernando Sánchez's avatar
YAPFed    
J. Fernando Sánchez committed
80
81
82
83
84
85
        return response.flask(
            in_headers=in_headers,
            headers=headers,
            context_uri=url_for(
                'api.context', entity=type(response).__name__, _external=True))

86
    return decorated_function
J. Fernando Sánchez's avatar
YAPFed    
J. Fernando Sánchez committed
87
88


89
90
91
92
93
94
95
96
97
@api_blueprint.route('/', methods=['POST', 'GET'])
@basic_api
def api():
    response = current_app.senpy.analyse(**request.params)
    return response


@api_blueprint.route('/plugins/', methods=['POST', 'GET'])
@basic_api
98
99
100
def plugins():
    sp = current_app.senpy
    dic = Plugins(plugins=list(sp.plugins.values()))
101
    return dic
J. Fernando Sánchez's avatar
YAPFed    
J. Fernando Sánchez committed
102
103


104
105
106
@api_blueprint.route('/plugins/<plugin>/', methods=['POST', 'GET'])
@api_blueprint.route('/plugins/<plugin>/<action>', methods=['POST', 'GET'])
@basic_api
107
def plugin(plugin=None, action="list"):
108
    filt = {}
109
    sp = current_app.senpy
110
111
112
113
114
115
116
    plugs = sp.filter_plugins(name=plugin)
    if plugin == 'default' and sp.default_plugin:
        response = sp.default_plugin
        plugin = response.name
    elif plugin in sp.plugins:
        response = sp.plugins[plugin]
    else:
117
        return Error(message="Plugin not found", status=404)
118
    if action == "list":
119
        return response
120
    method = "{}_plugin".format(action)
J. Fernando Sánchez's avatar
YAPFed    
J. Fernando Sánchez committed
121
    if (hasattr(sp, method)):
122
        getattr(sp, method)(plugin)
123
        return Response(message="Ok")
124
    else:
125
        return Error(message="action '{}' not allowed".format(action))
126

J. Fernando Sánchez's avatar
YAPFed    
J. Fernando Sánchez committed
127

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
128
if __name__ == '__main__':
129
    import config
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
130

131
    app.register_blueprint(api_blueprint)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
132
    app.debug = config.DEBUG
Ignacio Corcuera's avatar
Ignacio Corcuera committed
133
    app.run(host='0.0.0.0', port=5000)