1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| """Server. """ from __future__ import print_function
import os import json import time import base64 import argparse from wsgiref.simple_server import make_server
def get_args(): """Get arguments.
Returns: Namespace, arguments. """ parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--server_host', type=str, default='0.0.0.0', help='Server host.') parser.add_argument('--server_port', type=int, default=8000, help='Server port.') parser.add_argument('--images_dir', type=str, default='upload_images/', help='Images directory.') args = parser.parse_args() return args
ARGS = get_args()
def application(environ, start_response): """Application
Args: environ: dict, environment values. start_response: func, start_response function.
Returns: str, response. """ method = environ['REQUEST_METHOD'] path = environ['PATH_INFO'] status = '200 OK' if method == 'POST' and path == '/upload': headers = [('Content-type', 'application/json')] content_length = int(environ.get('CONTENT_LENGTH', 0)) request_body = environ['wsgi.input'].read(content_length) request_body = json.loads(request_body) image_data = request_body['image'] image_path = os.path.join(ARGS.images_dir, '{}.jpg'.format(time.time())) image_data = base64.b64decode(image_data) open(image_path, 'wb').write(image_data) response = {'info': 'Get text: {}'.format(request_body['text'])} start_response(status, headers) return [json.dumps(response)] headers = [('Content-type', 'text/plain')] start_response(status, headers) return 'Hello World'
def main(): """main. """ print('----------- Configuration Arguments -----------') for arg, value in sorted(vars(ARGS).items()): print('{}: {}'.format(arg, value)) print('------------------------------------------------') if not os.path.exists(ARGS.images_dir): os.makedirs(ARGS.images_dir) httpd = make_server(ARGS.server_host, ARGS.server_port, application) print('[INFO] Serving on port {}...'.format(ARGS.server_port)) httpd.serve_forever()
if __name__ == '__main__': main()
|