From 598da57427c7b23e9e68f01f55649b368fe3a2bf Mon Sep 17 00:00:00 2001 From: fakefeik Date: Tue, 24 Mar 2015 17:49:01 +0500 Subject: [PATCH] file loading done --- main.html | 7 +++++++ wsgi.py | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 58 insertions(+), 4 deletions(-) diff --git a/main.html b/main.html index 61423bc..4be9712 100644 --- a/main.html +++ b/main.html @@ -12,6 +12,13 @@

+ + +
+ + Choose a file to upload:
+ +
\ No newline at end of file diff --git a/wsgi.py b/wsgi.py index 6e1f6c1..c26176f 100644 --- a/wsgi.py +++ b/wsgi.py @@ -1,4 +1,7 @@ import wsgiref.validate +from tempfile import TemporaryFile +import cgi +import os from utils import parse_http_x_www_form_urlencoded_post_data, \ get_first_element, parse_http_get_data, parse_http_headers, \ @@ -12,7 +15,21 @@ b'Name: user
Message: hi!', b'Name: user
Message: hi!', ] +#import wsgiref.util +#wsgiref.util.FileWrapper().filelike() +def read(environ): + length = int(environ.get('CONTENT_LENGTH', 0)) + stream = environ['wsgi.input'] + body = TemporaryFile(mode='w+b') + while length > 0: + part = stream.read(min(length, 1024*200)) # 200KB buffer size + if not part: break + body.write(part) + length -= len(part) + body.seek(0) + environ['wsgi.input'] = body + return body @wsgiref.validate.validator def application(environ, start_response): @@ -34,10 +51,7 @@ def application(environ, start_response): status = '404 Not Found' start_response(status, headers) return [b''] - - if URI_PATH.startswith(STATIC_URL): - print('STATIC FILE DETECTED!') - + print(environ) if DEBUG: print("{REQUEST_METHOD} {URI_PATH}?{URI_QUERY} {SERVER_PROTOCOL}\n" "CONTENT_TYPE: {CONTENT_TYPE}; {CONTENT_TYPE_KWARGS}\n" @@ -46,6 +60,39 @@ def application(environ, start_response): ":HEADERS:\n{HEADERS}\n" .format(**locals())) + if URI_PATH == "/upload": + status = '303 See Other' + headers.append(('Location', '/')) + body = read(environ) + form = cgi.FieldStorage(fp=body, environ=environ, keep_blank_values=True) + try: + fileitem = form['file'] + except KeyError: + fileitem = None + if fileitem is not None and fileitem.file is not None: + fn = os.path.basename(fileitem.filename) + with open("data/" + fn, 'wb') as f: + data = fileitem.file.read(1024) + while data: + f.write(data) + data = fileitem.file.read(1024) + + start_response(status, headers) + return [b''] + + if URI_PATH.startswith(STATIC_URL): + path = URI_PATH.split(STATIC_URL)[-1] + if "../" in path: + status = '404 Not Found' + start_response(status, headers) + return [b''] + + with open(STATIC_ROOT + "/" + path, 'rb') as f: + start_response(status, [('Content-type', 'application/octet-stream; charset=utf-8')]) + return [f.read()] + + + with open('main.html', 'rb') as f: template_bytes = f.read()