Example #1
0
def processFile(id, filename):
	from store import ImSto
	imsto = ImSto()
	file = imsto.get(id)
	if file is None:
		imsto.close()
		return False
	save_file(file, filename)
	imsto.close()
	return True
Example #2
0
def stored_process(environ, start_response):
	from cgi import FieldStorage
	import cgitb; cgitb.enable(display=0, logdir="/tmp")
	form = FieldStorage(fp=environ['wsgi.input'], environ=environ)
	print(form.keys())

	start_response('200 Ok', [('Content-type', 'text/javascript')])

	if "oper" not in form:
		#print("Bad Request")
		return [json.dumps([False, 'Bad Request'])]

	method = environ['REQUEST_METHOD'].upper()
	if method == 'GET' or method == 'HEAD':
		return [json.dumps([False, 'bad request'])]
	oper = form['oper']
	print(oper)
	from store import ImSto
	imsto = ImSto()
	if oper.value == 'delete':
		id = form['id']
		return [json.dumps(imsto.delete(id.value))]
	if oper.value == 'add':

		if "new_file" not in form:
			return [json.dumps([False, 'please select a file'])]

		new_file = form['new_file']
		if new_file is None:
			return [json.dumps([False, 'invalid upload field'])]
		print(type(new_file))
		result = []
		if type(new_file) == type([]):
			for f in new_file:
				print('%r %r %r %r %r %r' % (f.name, f.filename, f.type, f.disposition, f.file, f.length))
				id = imsto.store(f.file, ctype=f.type, name=f.filename)
				print('new_id: %r' % id)
				result.append(id)
		else:
			f = new_file
			print('single file %r %r' % (f.name, f.filename))
			id = imsto.store(f.file, ctype=f.type, name=f.filename)
			print('new_id: %r' % id)
			result = id
		if hasattr(imsto, 'close'):
			imsto.close()
		
		return [json.dumps(result)]
	else:
		return [json.dumps([False, 'invalid operation'])]
Example #3
0
def image_handle(environ, start_response):
    """main url process"""
    path = environ.get('PATH_INFO', '')
    image_url_regex = r'/([a-z0-9]{2})/([a-z0-9]{2})/([a-z0-9]{19,36})(-[sc]\d{2,4})?\.(gif|jpg|jpeg|png)$'
    match = re.search(image_url_regex, path)
    #print(image_url_regex, path, match)
    if match is not None:
        ids = match.groups()
        #print(ids)
        id = '{0}{1}{2}'.format(*ids)
        from store import ImSto
        imsto = ImSto()
        file = imsto.get(id)
        if file is None:
            imsto.close()
            return not_found(environ, start_response)

        org_path = '{0}/{1}/{2}.{4}'.format(*ids)
        org_file = '{0}/{1}'.format(THUMB_ROOT, org_path)
        if not os.path.exists(org_file):
            save_file(file, org_file)
        if ids[3] is None:
            dst_path = org_path
            dst_file = org_file
        else:
            dst_path = '{0}/{1}/{2}{3}.{4}'.format(*ids)
            dst_file = '{0}/{1}'.format(THUMB_ROOT, dst_path)
            #print(ids[3][1:])
            size = int(ids[3][2:])
            if size not in SUPPORTED_SIZE:
                print('unsupported size: {0}'.format(size))
                imsto.close()
                return not_found(environ, start_response)
            thumb_image(org_file, size, dst_file)
        #print(dst_file)
        server_soft = environ.get('SERVER_SOFTWARE', '')
        if server_soft[:5] == 'nginx' and os.name != 'nt':
            imsto.close()
            start_response(
                '200 OK',
                [('X-Accel-Redirect', '{0}/{1}'.format(THUMB_PATH, dst_path))])
            return []
        #print(file.type)
        headers = [('Content-Type', str(file.type)),
                   ('Content-Length', '{0.length}'.format(file)),
                   ('Via', 'imsto')]
        #print(headers)
        start_response('200 OK', headers)
        # TODO: response file content
        #data = file.read()
        imsto.close()
        #return [data]
        fd = open(dst_file, 'r')
        return environ['wsgi.file_wrapper'](fd, 4096)

    return not_found(environ, start_response)
Example #4
0
def image_handle(environ, start_response):
	"""main url process"""
	path = environ.get('PATH_INFO', '')
	image_url_regex = r'/([a-z0-9]{2})/([a-z0-9]{2})/([a-z0-9]{19,36})(-[sc]\d{2,4})?\.(gif|jpg|jpeg|png)$'
	match = re.search(image_url_regex, path)
	#print(image_url_regex, path, match)
	if match is not None:
		ids = match.groups()
		#print(ids)
		id = '{0}{1}{2}'.format(*ids)
		from store import ImSto
		imsto = ImSto()
		file = imsto.get(id)
		if file is None:
			imsto.close()
			return not_found(environ, start_response)

		org_path = '{0}/{1}/{2}.{4}'.format(*ids)
		org_file = '{0}/{1}'.format(THUMB_ROOT, org_path)
		if not os.path.exists(org_file):
			save_file(file, org_file)
		if ids[3] is None:
			dst_path = org_path
			dst_file = org_file
		else:
			dst_path = '{0}/{1}/{2}{3}.{4}'.format(*ids)
			dst_file = '{0}/{1}'.format(THUMB_ROOT, dst_path)
			#print(ids[3][1:])
			size = int(ids[3][2:])
			if size not in SUPPORTED_SIZE:
				print('unsupported size: {0}'.format(size))
				imsto.close()
				return not_found(environ, start_response)
			thumb_image(org_file, size, dst_file)
		#print(dst_file)
		server_soft = environ.get('SERVER_SOFTWARE','')
		if server_soft[:5] == 'nginx' and os.name != 'nt':
			imsto.close()
			start_response('200 OK', [('X-Accel-Redirect', '{0}/{1}'.format(THUMB_PATH, dst_path))])
			return []
		#print(file.type) 
		headers = [('Content-Type', str(file.type)), ('Content-Length', '{0.length}'.format(file)), ('Via','imsto')]
		#print(headers)
		start_response('200 OK', headers)
		# TODO: response file content
		#data = file.read()
		imsto.close()
		#return [data]
		fd = open(dst_file,'r')
		return environ['wsgi.file_wrapper'](fd, 4096)
		
	return not_found(environ, start_response)
Example #5
0
def manage(environ, start_response):
    path_info = environ.get('PATH_INFO', '')

    man_regex = r'^/([A-Za-z]+)/(env|Gallery|Stored)'
    match = re.search(man_regex, path_info)
    #print('match: {0}'.format(match))
    if match is None:
        return not_found(environ, start_response)

    action = match.groups()[1]
    if (action == 'Gallery'):
        from cgi import FieldStorage
        form = FieldStorage(environ=environ)
        limit = 20
        start = 0
        if form.has_key("page") and form["page"].value != "":
            page = int(form["page"].value)
            if page < 1:
                page = 1
            start = limit * (page - 1)

        start_response('200 OK', [('Content-type', 'text/plain')])

        imsto = ImSto()
        gallery = imsto.browse(limit, start)
        import datetime
        dthandler = lambda obj: obj.isoformat() if isinstance(
            obj, datetime.datetime) else None
        if hasattr(imsto, 'close'):
            imsto.close()
        return [json.dumps(gallery, default=dthandler)]
    elif (action == 'Stored'):
        return stored_process(environ, start_response)
        #start_response('200 OK', [('Content-type', 'text/plain')])
        #return ['Stored']
    elif (action == 'env'):
        from _respond import print_env
        return print_env(environ, start_response)

    start_response('200 OK', [('Content-type', 'text/plain')])
    return [path_info]
Example #6
0
def manage(environ, start_response):
	path_info = environ.get('PATH_INFO', '')
	
	man_regex = r'^/([A-Za-z]+)/(env|Gallery|Stored)'
	match = re.search(man_regex, path_info)
	#print('match: {0}'.format(match))
	if match is None:
		return not_found(environ, start_response)
	
	action = match.groups()[1]
	if (action == 'Gallery'):
		from cgi import FieldStorage
		form = FieldStorage(environ=environ)
		limit = 20
		start = 0
		if form.has_key("page") and form["page"].value != "":
			page = int(form["page"].value)
			if page < 1:
				page = 1
			start = limit * (page - 1)
		
		start_response('200 OK', [('Content-type', 'text/plain')])
		
		imsto = ImSto()
		gallery = imsto.browse(limit, start)
		import datetime
		dthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime.datetime) else None
		if hasattr(imsto, 'close'):
			imsto.close()
		return [json.dumps(gallery, default=dthandler)]
	elif (action == 'Stored'):
		return stored_process(environ, start_response)
		#start_response('200 OK', [('Content-type', 'text/plain')])
		#return ['Stored']
	elif  (action == 'env'):
		from _respond import print_env
		return print_env(environ, start_response)
	
	start_response('200 OK', [('Content-type', 'text/plain')])
	return [path_info]
Example #7
0
def stored_process(environ, start_response):
    from cgi import FieldStorage
    form = FieldStorage(environ=environ)
    #print(form.keys())
    start_response('200 Ok', [('Content-type', 'text/javascript')])
    method = environ['REQUEST_METHOD'].upper()
    if method == 'GET' or method == 'HEAD':
        return [json.dumps([False, 'bad request'])]
    oper = form['oper']
    print(oper)
    from store import ImSto
    imsto = ImSto()
    if oper.value == 'delete':
        id = form['id']
        return [json.dumps(imsto.delete(id.value))]
    if oper.value == 'add':
        new_file = form['new_file']
        if new_file is None:
            return [json.dumps([False, 'invalid upload field'])]
        print(type(new_file))
        result = []
        if type(new_file) == type([]):
            for f in new_file:
                print('%r %r %r %r %r %r' % (f.name, f.filename, f.type,
                                             f.disposition, f.file, f.length))
                id = imsto.store(f.file, ctype=f.type, name=f.filename)
                print('new_id: %r' % id)
                result.append(id)
        else:
            f = new_file
            print('single file %r %r' % (f.name, f.filename))
            id = imsto.store(f.file, ctype=f.type, name=f.filename)
            print('new_id: %r' % id)
            result.append(id)
        if hasattr(imsto, 'close'):
            imsto.close()

        return [json.dumps(result)]
    else:
        return [json.dumps([False, 'invalid operation'])]