blueprints.py 3.93 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

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

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

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

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

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

def basic_api(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        print('Getting request:')
        print(request)
63
64
65
66
67
68
69
        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
70
71
72
73
        try:
            response = f(*args, **kwargs)
        except Error as ex:
            response = ex
74
75
        in_headers = web_params["inHeaders"] != "0"
        headers = {'X-ORIGINAL-PARAMS': raw_params}
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
        return response.flask(in_headers=in_headers,
                              headers=headers,
                              context_uri=url_for('api.context', entity=type(response).__name__,
                                                  _external=True))
    return decorated_function
    
@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
91
92
93
def plugins():
    sp = current_app.senpy
    dic = Plugins(plugins=list(sp.plugins.values()))
94
    return dic
95
    
96
97
98
@api_blueprint.route('/plugins/<plugin>/', methods=['POST', 'GET'])
@api_blueprint.route('/plugins/<plugin>/<action>', methods=['POST', 'GET'])
@basic_api
99
def plugin(plugin=None, action="list"):
100
    filt = {}
101
    sp = current_app.senpy
102
103
104
105
106
107
108
    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:
109
        return Error(message="Plugin not found", status=404)
110
    if action == "list":
111
        return response
112
113
114
    method = "{}_plugin".format(action)
    if(hasattr(sp, method)):
        getattr(sp, method)(plugin)
115
        return Response(message="Ok")
116
    else:
117
        return Error(message="action '{}' not allowed".format(action))
118

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
119
if __name__ == '__main__':
120
    import config
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
121

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