コード例 #1
0
def write_file() :
	'''
		Write content to a file (overwrites original; creates new file)
		Request
			pathname: Linux-style path and name of file
			content: base64 encoded content
		Response
			length: Length written to file
			pathname: same as in request
	'''
	pathname = get_pathname()
	b64content = request.args.get('content')
	if b64content is None :
		return json_error('Please supply content using HTTP GET')
	try :
		content = base64.decodebytes(b64content.encode())
	except binascii.Error :
		return json_error('Content cannot be base64 decoded')
	directory = os.path.dirname(pathname)
	if not os.path.exists(directory) :
		return json_error('Directory %s does not exist' % repr(directory))
	try :
		f = open(pathname, 'wb')
		nbytes = f.write(content)
		f.close()
	except PermissionError :
		return json_error('Permission Denied')
	except Exception :
		return json_error('Exception: %s' % repr(traceback.format_exc()))
	return json_success('Written %d bytes to %s' % (nbytes, repr(pathname)),
						length=nbytes, pathname=pathname)
コード例 #2
0
def copy_tree() :
	'''
		Copy a tree using shutil.copytree
		Call convention: (src, dst, ignore=shutil.ignore_patterns(*ignore))
		Request
			src: A Linux-style path of file or directory
			dst: A Linux-style path of file or directory
			ignore: list of json strings, passed to ignore_patterns(); optional
		Response
			(none)
	'''
	src = get_pathname('src')
	dst = get_pathname('dst')
	ignore = request.args.get('ignore', None)
	try :
		print(repr(ignore))
		if ignore is not None :
			ignore = shutil.ignore_patterns(*json.loads(ignore))
		shutil.copytree(src, dst, ignore=ignore)
	except PermissionError :
		return json_error('Permission Denied')
	except FileExistsError :
		return json_error('File exists')
	except FileNotFoundError :
		return json_error('No such file or directory')
	except Exception :
		return json_error('Exception: %s' % repr(traceback.format_exc()))
	return json_success()
コード例 #3
0
def status() :
	'''
		Display file status (permission, user, etc), wrapper for os.stat
		Request
			pathname: Linux-style path of file or directory
		Response
			mode: file mode in integer
			uid: user id in integer
			gid: group id in integer
			size: size in integer
			atime: access time in float
			mtime: modify time in float
			ctime: change time in float
	'''
	pathname = get_pathname()
	parent = request.args.get('parent', '0') == '1'
	if not os.path.exists(pathname) :
		return json_error('pathname does not exist')
	try :
		stat = os.stat(pathname)
	except Exception as e :
		return json_error(e.strerror)
	return json_success(mode=stat.st_mode,
						uid=stat.st_uid,
						gid=stat.st_gid,
						size=stat.st_size,
						atime=stat.st_atime,
						mtime=stat.st_mtime,
						ctime=stat.st_ctime)
コード例 #4
0
def list_directory() :
	'''
		List a directory
		Request
			pathname: Linux-style path of directory
		Response
			content: json list of direcotry content
	'''
	pathname = get_pathname()
	if not os.path.exists(pathname) :
		return json_error('pathname does not exist')
	if not os.path.isdir(pathname) :
		return json_error('pathname is not directory')
	return json_success(content=os.listdir(pathname))
コード例 #5
0
ファイル: app.py プロジェクト: salman-codes/nlpweb
def add_book():
    try:
        params = request.get_json()
        if not params:
            params = request.form

        if not params.get("title") or not params.get("author"):
            return validation_errors(errors="title and author is required")

        groups = classify_book(params["title"])
        temp_params = {
            "title": request.form["title"],
            "author": request.form["author"],
            "groups": groups
        }
        books_list = Books().create(temp_params)
        suggested_books = Books().list_books_in_group(groups.split(", ")[0])
        return render_template("index.html",
                               results={
                                   "data": books_list,
                                   "suggestion_flag": True,
                                   "suggested_books": suggested_books
                               })
    except Exception as e:
        return json_error(message=str(e))
コード例 #6
0
def copy_file() :
	'''
		Copy a file
		Request
			src: A Linux-style path of file or directory
			dst: A Linux-style path of file or directory
		Response
			(none)
	'''
	src = get_pathname('src')
	dst = get_pathname('dst')
	try :
		shutil.copy(src, dst)
	except PermissionError :
		return json_error('Permission Denied')
	except Exception :
		return json_error('Exception: %s' % repr(traceback.format_exc()))
	return json_success()
コード例 #7
0
ファイル: models.py プロジェクト: salman-codes/nlpweb
 def create(self, params):
     try:
         query = """ INSERT INTO {0} (title, author, groups)
                     VALUES ("{1}","{2}", "{3}")
                 """.format(self.__table_name__, params.get("title"),
                            params.get("author"), params.get("groups"))
         self.conn.execute(query)
         return self.list_items()
     except Exception as e:
         return json_error(message=str(e))
コード例 #8
0
def remove_tree() :
	'''
		Copy a tree using shutil.copytree
		Call convention: (src, dst, ignore=shutil.ignore_patterns(*ignore))
		Request
			pathname: A Linux-style path of file or directory
		Response
			(none)
	'''
	pathname = get_pathname('pathname')
	try :
		shutil.rmtree(pathname)
	except PermissionError :
		return json_error('Permission Denied')
	except FileNotFoundError :
		return json_error('No such file or directory')
	except Exception :
		return json_error('Exception: %s' % repr(traceback.format_exc()))
	return json_success()
コード例 #9
0
ファイル: app.py プロジェクト: salman-codes/nlpweb
def delete_book(item_id):
    try:
        books_list = Books().delete(item_id)
        return render_template("index.html",
                               results={
                                   "data": books_list,
                                   "suggestion_flag": False,
                                   "suggested_books": []
                               })
    except Exception as e:
        return json_error(message=str(e))
コード例 #10
0
def read_file() :
	'''
		Read the content of a file
		Request
			pathname: Linux-style path and name of file
		Response
			content: base64 encoded content of file
	'''
	pathname = get_pathname()
	if not os.path.exists(pathname) :
		return json_error('File %s does not exist' % repr(pathname))
	try :
		f = open(pathname, 'rb')
		content = f.read()
		f.close()
	except PermissionError :
		return json_error('Permission Denied')
	except Exception :
		return json_error('Exception: %s' % repr(traceback.format_exc()))
	return json_success(content=base64.encodebytes(content).decode())
コード例 #11
0
ファイル: models.py プロジェクト: salman-codes/nlpweb
 def delete(self, item_id):
     try:
         query = """ UPDATE {0} 
                     SET is_deleted =  {1} 
                     WHERE id = {2}
                 """.format(self.__table_name__, 1, item_id)
         if self.conn.execute(query):
             return self.list_items()
         else:
             return False
     except Exception as e:
         return json_error(message=str(e))
コード例 #12
0
ファイル: app.py プロジェクト: salman-codes/nlpweb
def list_books():
    try:
        books_list = Books().list()
        # books_list = get_paginated_list(books_list, start=1, limit=10)
        return render_template("index.html",
                               results={
                                   "data": books_list,
                                   "suggestion_flag": False,
                                   "suggested_books": []
                               })
    except Exception as e:
        return json_error(message=str(e))
コード例 #13
0
def make_directory() :
	'''
		Make a directory
		Request
			pathname: Linux-style path of directory
			parent: (optional) 0 or 1, whether mkdir parent directories
		Response
			(none)
	'''
	pathname = get_pathname()
	parent = request.args.get('parent', '0') == '1'
	if os.path.exists(pathname) :
		return json_error('File exists')
	try :
		if parent :
			os.makedirs(pathname)
		else :
			os.mkdir(pathname)
	except Exception as e :
		return json_error(e.strerror)
	return json_success()
コード例 #14
0
def change_mode() :
	'''
		Change mode of file or directory
		Request
			pathname: Linux-style path of file or directory
			mode: file mode in integer
		Response
			(none)
	'''
	pathname = get_pathname()
	parent = request.args.get('parent', '0') == '1'
	if not os.path.exists(pathname) :
		return json_error('pathname does not exist')
	try :
		mode = int(request.args.get('mode'))
	except ValueError :
		return json_error('Please supply mode in integer using HTTP GET')
	try :
		os.chmod(pathname, mode)
	except Exception as e :
		return json_error(e.strerror)
	return json_success()
コード例 #15
0
ファイル: app.py プロジェクト: salman-codes/nlpweb
def get_group_wise_books():
    try:
        books_list = Books().list()
        data = grouping_books(books_list)
        records = []
        groups = data.keys()
        for grp in groups:
            temp = {"groups": int(grp), "books_count": data[grp]}
            records.append(temp)
        if records:
            records = sorted(records,
                             key=lambda i: i['books_count'],
                             reverse=True)
        return render_template("groups.html", results=records)
    except Exception as e:
        return json_error(message=str(e))
コード例 #16
0
def page_not_found(error):
	return json_error('404 (Not Found)')