backing up
[vsorcdistro/.git] / ryu / build / lib.linux-armv7l-2.7 / ryu / app / sdnhub_apps / fileserver.py
1 # Copyright (C) 2014 SDN Hub
2 #
3 # Licensed under the GNU GENERAL PUBLIC LICENSE, Version 3.
4 # You may not use this file except in compliance with this License.
5 # You may obtain a copy of the License at
6 #
7 #    http://www.gnu.org/licenses/gpl-3.0.txt
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12 # implied.
13
14 import json
15 from webob import Response
16 import os
17 import mimetypes
18
19 from ryu.base import app_manager
20 from ryu.app.wsgi import ControllerBase, WSGIApplication
21
22
23 # REST API
24 #
25 ############# Configure tap
26 #
27 # get root
28 # GET /
29 #
30 # get file
31 # GET /web/{file}
32 #
33
34 class WebController(ControllerBase):
35     def __init__(self, req, link, data, **config):
36         super(WebController, self).__init__(req, link, data, **config)
37         self.directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'web')
38
39     def make_response(self, filename):
40         filetype, encoding = mimetypes.guess_type(filename)
41         if filetype == None:
42             filetype = 'application/octet-stream'
43         res = Response(content_type=filetype)
44         res.body = open(filename, 'rb').read()
45         return res
46
47     def get_root(self, req, **_kwargs):
48         return self.get_file(req, None)
49
50     def get_file(self, req, filename, **_kwargs):
51         if (filename == "" or filename == None):
52             filename = "index.html"
53         try:
54             filename = os.path.join(self.directory, filename)
55             return self.make_response(filename)
56         except IOError:
57             return Response(status=400)
58
59
60 class WebRestApi(app_manager.RyuApp):
61     _CONTEXTS = {
62         'wsgi': WSGIApplication,
63     }
64
65     def __init__(self, *args, **kwargs):
66         super(WebRestApi, self).__init__(*args, **kwargs)
67         wsgi = kwargs['wsgi']
68         mapper = wsgi.mapper
69
70         mapper.connect('web', '/web/{filename:.*}',
71                        controller=WebController, action='get_file',
72                        conditions=dict(method=['GET']))
73
74         mapper.connect('web', '/',
75                        controller=WebController, action='get_root',
76                        conditions=dict(method=['GET']))
77
78