Home | History | Annotate | Download | only in server
      1 #!/usr/bin/env python
      2 #
      3 # Copyright 2017 The Chromium OS Authors. All rights reserved.
      4 #
      5 # Licensed under the Apache License, Version 2.0 (the "License");
      6 # you may not use this file except in compliance with the License.
      7 # You may obtain a copy of the License at
      8 #
      9 #      http://www.apache.org/licenses/LICENSE-2.0
     10 #
     11 # Unless required by applicable law or agreed to in writing, software
     12 # distributed under the License is distributed on an "AS IS" BASIS,
     13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     14 # See the License for the specific language governing permissions and
     15 # limitations under the License.
     16 #
     17 
     18 """
     19 Runs a server that receives log uploads from the WALT app
     20 Usage example:
     21     $ python main.py
     22 """
     23 
     24 import time
     25 import os
     26 
     27 try:
     28     from bottle import route, template, run, request, static_file
     29 except:
     30     print('Could not import bottle! Please install bottle, e.g. pip install bottle')
     31     raise
     32 
     33 @route('/')
     34 def index():
     35     if not os.path.isdir('logs/'):
     36         return 'No files uploaded yet'
     37     filenames = []
     38     for file in os.listdir('logs/'):
     39         if file.endswith('.txt'):
     40             filenames.append(file)
     41     return template('make_table', filenames=filenames)
     42 
     43 
     44 @route('/logs/<filename>')
     45 def static(filename):
     46     return static_file(filename, root='logs')
     47 
     48 
     49 @route('/upload', method='POST')
     50 def upload():
     51     body = request.body.getvalue()
     52     request.body.close()
     53     filename = 'logs/' + str(int(time.time()*1000)) + '.txt'
     54     if not os.path.exists(os.path.dirname(filename)):
     55         try:
     56             os.makedirs(os.path.dirname(filename))
     57         except OSError as e:
     58             if e.errno != errno.EEXIST:
     59                 raise
     60     with open(filename, 'w') as file:
     61         file.write(body)
     62     return 'success'
     63 
     64 
     65 run(host='localhost', port=8080)
     66 
     67