Beispiel #1
0
def root(env):
    try:
        docroot = env["DOCUMENT_ROOT"]
    except KeyError:
        server.error(500, "Document root not specified")

    return docroot
Beispiel #2
0
def execute(sql):
	from server import error
	ret=None
	try:
		for r in parse(sql):
			if len(r)==2: ret=r[0](*r[1])
			else:
				print r
				return error("parser error") 
		else:
			if ret: return ret
			else: return error("backend error")
	except peglet.Unparsable:
		return error("syntax error")
Beispiel #3
0
def delete_user(user_id):
    try:
        with Cursor() as cur:
            cur.execute('DELETE FROM users WHERE id = %s', (user_id, ))
            return server.ok(message='successfully deleted user')
    except:
        return server.error('unable to delete user')
Beispiel #4
0
def analyze_image(leaf, alexnet):
    try:
        # predicting images
        img = image.load_img(leaf, target_size=(227, 227))

        x = image.img_to_array(img)
        x = np.expand_dims(x, axis=0)

        images = np.vstack([x])
        classes = alexnet.predict(images)

        return server.ok(data=classes[0].tolist())
    except:
        return server.error('unable to analyze image')
Beispiel #5
0
def create_user(first_name, last_name, email, password, created_by):
    password_hash = bcrypt.hashpw(password.encode('utf8'),
                                  bcrypt.gensalt()).decode('utf8')

    try:
        with Cursor() as cur:
            cur.execute(
                'INSERT INTO users '
                '(first_name, last_name, email, password, created_by) '
                'VALUES '
                '(%s, %s, %s, %s, %s) '
                'RETURNING *',
                (first_name, last_name, email, password_hash, created_by))

            emails.new_user(email, password)

            return server.ok(data=cur.fetchone())
    except:
        return server.error('unable to create user')
Beispiel #6
0
def get_users(page_size, page_index, name):
    query = "SELECT * FROM users WHERE type = 'regular' "

    if name:
        query += "AND levenshtein(first_name, '{0}') <= 2 or levenshtein(last_name, '{0}') <= 2 " \
          .format(name)

    query += "ORDER BY created_on DESC LIMIT {} OFFSET {}".format(
        page_size, page_size * page_index)

    try:
        with Cursor() as cur:
            cur.execute(query)

            if cur.rowcount:
                return server.ok(data=cur.fetchall())
            else:
                return server.not_found('no users found')
    except:
        return server.error('unable to get users')
Beispiel #7
0
def name(env):
    try:
        name = env["REQUEST_URI"]
    except KeyError:
        server.error(400, "Request URI not specified")

    if name.startswith("/"):
        name = name[1:]

    allowed = set("abcdefghijklmnopqrstuvwxyz0123456789-")
    if set(name) - allowed:
        server.error(403, "This page name is not allowed")

    name = normalise(name)

    # redundant
    if "_" in name:
        server.error(403, "Underscores in page names are not allowed")

    # redundant
    if "/" in name:
        server.error(403, "Nested directory editing is not allowed")

    return name
Beispiel #8
0
def writeable_directory(path):
    writeable = os.access(path, os.W_OK)
    directory = os.path.isdir(path)

    if (not writeable) or (not directory):
        server.error(500, "Cannot write to %s" % path)
Beispiel #9
0
def internal_server_error(err):
  return server.error()
Beispiel #10
0
def handle(user):
    start = time.time()
    unixtime = int(time.time())


    # 1. get paths and check permissions

    docroot = request.root(os.environ)
    check.writeable_directory(docroot)

    name = request.name(os.environ)
    page_path = os.path.join(docroot, name)

    versions = os.path.join(docroot, "site", "versions")
    check.writeable_directory(versions)

    version_name = "%s_%s_%s" % (unixtime, user, name)
    version_path = os.path.join(versions, version_name)

    if os.path.isfile(version_path):
        server.error(500, "You can't save more than once per second")


    # 2. write a temporary file

    try:
        temp_path = os.path.join(docroot, version_name)

        with open(temp_path, "wb") as temp:
            for line in sys.stdin.buffer:
                temp.write(line)
            if not line.endswith(b"\n"):
                temp.write(b"\n")
            temp.flush()
            os.fsync(temp.fileno())
    except Exception as err:
        server.error(500, "Could not make a temporary file: %s" % err)


    # 3. test for duplicates

    if os.path.isfile(page_path):
        old_size = os.path.getsize(page_path)
        new_size = os.path.getsize(temp_path)

        if old_size == new_size:
            import zlib

            old_check = 0
            with open(page_path, "rb") as f:
                for line in f:
                    old_check = zlib.adler32(line, old_check)

            new_check = 0
            with open(temp_path, "rb") as f:
                for line in f:
                    new_check = zlib.adler32(line, new_check)

            if old_check == new_check:
                os.remove(temp_path)
                server.error(500, "Won't save duplicate pages")


    # 4. copy temporary file to backup

    try:
        shutil.copy2(temp_path, version_path)
    except Exception as err:
        os.remove(temp_path)
        server.error(500, "Could not archive backup version: %s" % err)


    # 5. move temporary file into place

    existing = os.path.exists(page_path)

    try:
        shutil.move(temp_path, page_path)
    except Exception as err:
        os.remove(temp_path)
        server.error(500, "Could not move temporary file into place: %s" % err)

    size = os.path.getsize(page_path)
    took = time.time() - start
    message = "%s bytes, in %ss" % (size, round(took, 3))

    if existing:
        server.response(200, message)
    else:
        server.response(201, message)


    # 6. add metadata to change log

    changes_path = os.path.join(versions, "changes.log")
    entry = "%s %s %s\n" % (unixtime, user, name)

    with open(changes_path, "a") as f:
        f.write(entry)
        f.flush()
        os.fsync(f.fileno())


    # 7. scan for links and update database

    outbound_path = os.path.join(versions, "outbound.db")
    inbound_path = os.path.join(versions, "inbound.db")

    links.update(outbound_path, inbound_path, page_path, name)