REST test script

from bottle import route, run, template,get,post,put,delete,request,response
import json
import os


def secure_response_headers(response):
    response.set_header('Content-Type', 'application/json')
    response.set_header('X-XSS-Protection', '1; mode=block')
    response.set_header('X-Frame-Options', 'deny')
    response.set_header('Content-Security-Policy', "default-src 'none'")
    response.set_header('Strict-Transport-Security', 'max-age=31536000')
    response.set_header('X-Content-Type-Options', 'nosniff')
    return response

def debug_request():

  print('--- QUERY ---')
  for k,v in request.query.items():
    print( k+"="+v )

  print('--- COKKIE ---')
  for k,v in request.cookies.items():
    print( k+"="+v )

  print('--- HEADER ---')
  for k,v in request.headers.items():
    print( k+"="+v )

  print('--- FORM ---')
  for k,v in request.forms.allitems():
    print( k+"="+v )


@get('/gettest')
def gettest():

  debug_request()

  _a = request.query['a']  # same as request.query.get('a')
  _b = request.query['b']  # same as request.query.get('b')

  secure_response_headers(response)
  return json.dumps({'staus':'ok'})

@post('/posttest')
def posttest():

  debug_request()
  secure_response_headers(response)
  return json.dumps({'staus':'ok'})

@put('/puttest')
def puttest():

  debug_request()

  secure_response_headers(response)
  return json.dumps({'staus':'ok'})

@delete('/deletetest')
def deletetest():

  debug_request()

  secure_response_headers(response)
  return json.dumps({'staus':'ok'})


@post('/post_multipart_test')
def post_multipart_test():

  debug_request()

  # make image folder
  _dir = 'user/image/123/'
  os.makedirs(_dir, exist_ok=True)

  # save file.
  _file = request.files.get('image')

  upload_file = _dir + _file.filename
  _file.save(upload_file)


  print('file uploaded :' + str(os.path.isfile(upload_file)))

  secure_response_headers(response)
  return json.dumps({'staus':'ok', 'filename':_file.filename})


@route('/hello')
def hello():
  _msg = "World!"
  return template('Hello {{a}}!', a=_msg)


if __name__ == '__main__':
  run(host='192.168.111.102', port=8888, debug=True, reloader=True)


 

Leave a Comment.