|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | +r''' |
| 5 | +learning.py |
| 6 | +
|
| 7 | +A Python 3 tutorial from http://www.liaoxuefeng.com |
| 8 | +
|
| 9 | +Usage: |
| 10 | +
|
| 11 | +python3 learning.py |
| 12 | +''' |
| 13 | + |
| 14 | +import sys |
| 15 | + |
| 16 | +def check_version(): |
| 17 | + v = sys.version_info |
| 18 | + if v.major == 3 and v.minor >= 4: |
| 19 | + return True |
| 20 | + print('Your current python is %d.%d. Please use Python 3.4.' % (v.major, v.minor)) |
| 21 | + return False |
| 22 | + |
| 23 | +if not check_version(): |
| 24 | + exit(1) |
| 25 | + |
| 26 | +import os, io, json, subprocess, tempfile |
| 27 | +from urllib import parse |
| 28 | +from wsgiref.simple_server import make_server |
| 29 | + |
| 30 | +EXEC = sys.executable |
| 31 | +PORT = 39093 |
| 32 | +HOST = 'local.liaoxuefeng.com:%d' % PORT |
| 33 | +TEMP = tempfile.mkdtemp(suffix='_py', prefix='learn_python_') |
| 34 | +INDEX = 0 |
| 35 | + |
| 36 | +def main(): |
| 37 | + httpd = make_server('127.0.0.1', PORT, application) |
| 38 | + print('Ready for Python code on port %d...' % PORT) |
| 39 | + httpd.serve_forever() |
| 40 | + |
| 41 | +def get_name(): |
| 42 | + global INDEX |
| 43 | + INDEX = INDEX + 1 |
| 44 | + return 'test_%d' % INDEX |
| 45 | + |
| 46 | +def write_py(name, code): |
| 47 | + fpath = os.path.join(TEMP, '%s.py' % name) |
| 48 | + with open(fpath, 'w', encoding='utf-8') as f: |
| 49 | + f.write(code) |
| 50 | + print('Code wrote to: %s' % fpath) |
| 51 | + return fpath |
| 52 | + |
| 53 | +def application(environ, start_response): |
| 54 | + host = environ.get('HTTP_HOST') |
| 55 | + method = environ.get('REQUEST_METHOD') |
| 56 | + path = environ.get('PATH_INFO') |
| 57 | + if method == 'GET' and path == '/': |
| 58 | + start_response('200 OK', [('Content-Type', 'text/html')]) |
| 59 | + return [b'<html><head><title>Learning Python</title></head><body><form method="post" action="/run"><textarea name="code" style="width:90%;height: 600px"></textarea><p><button type="submit">Run</button></p></form></body></html>'] |
| 60 | + if method == 'GET' and path == '/env': |
| 61 | + start_response('200 OK', [('Content-Type', 'text/html')]) |
| 62 | + L = [b'<html><head><title>ENV</title></head><body>'] |
| 63 | + for k, v in environ.items(): |
| 64 | + p = '<p>%s = %s' % (k, str(v)) |
| 65 | + L.append(p.encode('utf-8')) |
| 66 | + L.append(b'</html>') |
| 67 | + return L |
| 68 | + if host != HOST or method != 'POST' or path != '/run' or not environ.get('CONTENT_TYPE', '').lower().startswith('application/x-www-form-urlencoded'): |
| 69 | + start_response('400 Bad Request', [('Content-Type', 'application/json')]) |
| 70 | + return [b'{"error":"bad_request"}'] |
| 71 | + s = environ['wsgi.input'].read(int(environ['CONTENT_LENGTH'])) |
| 72 | + qs = parse.parse_qs(s.decode('utf-8')) |
| 73 | + if not 'code' in qs: |
| 74 | + start_response('400 Bad Request', [('Content-Type', 'application/json')]) |
| 75 | + return [b'{"error":"invalid_params"}'] |
| 76 | + name = qs['name'][0] if 'name' in qs else get_name() |
| 77 | + code = qs['code'][0] |
| 78 | + headers = [('Content-Type', 'application/json')] |
| 79 | + origin = environ.get('HTTP_ORIGIN', '') |
| 80 | + if origin: |
| 81 | + headers.append(('Access-Control-Allow-Origin', origin)) |
| 82 | + start_response('200 OK', headers) |
| 83 | + r = dict() |
| 84 | + try: |
| 85 | + fpath = write_py(name, code) |
| 86 | + print('Execute: %s %s' % (EXEC, fpath)) |
| 87 | + r['output'] = subprocess.check_output([EXEC, fpath], stderr=subprocess.STDOUT, timeout=5).decode('utf-8') |
| 88 | + except subprocess.CalledProcessError as e: |
| 89 | + r = dict(error='Exception', output=e.output.decode('utf-8')) |
| 90 | + except subprocess.TimeoutExpired as e: |
| 91 | + r = dict(error='Timeout', output='执行超时') |
| 92 | + except subprocess.CalledProcessError as e: |
| 93 | + r = dict(error='Error', output='执行错误') |
| 94 | + print('Execute done.') |
| 95 | + return [json.dumps(r).encode('utf-8')] |
| 96 | + |
| 97 | +if __name__ == '__main__': |
| 98 | + main() |
0 commit comments