Last active
April 17, 2023 05:27
-
-
Save Rahmanism/77e46767d6359b2d3ccc03cc0aaaffcc to your computer and use it in GitHub Desktop.
File listing using Python for web
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import os, sys | |
print('Content-Type: text/html; charset=utf-8') | |
print('') | |
print('<!DOCTYPE html>') | |
print('<html>') | |
print('<head>') | |
print('<meta charset="utf-8" />') | |
print('<meta name="viewport" content="width=device-width, initial-scale=1.0">') | |
print(''' | |
<style> | |
body { | |
font-size: 1.5rem; | |
line-height: 1.5; | |
font-family: math; | |
margin: 2cqw; | |
} | |
a { | |
text-decoration: none; | |
} | |
li { | |
padding: .5cqw; | |
} | |
li:nth-of-type(even) { | |
background: #e7e7e7; | |
} | |
.small { | |
color: gray; | |
font-size: 1rem; | |
} | |
</style> | |
''') | |
print('</head>') | |
print('<body>') | |
try: | |
query_string = os.environ.get('QUERY_STRING') | |
folder_path = './' # Replace with your folder path | |
if query_string: | |
queries = query_string.split('&') | |
if len(queries) > 0: | |
dir_value = [n for i, n in enumerate(queries) if n.startswith('dir=')] | |
if len(dir_value) > 0: | |
folder_path = dir_value[0].split('=')[1] | |
if folder_path.startswith('.//'): | |
folder_path = folder_path[0] + folder_path[2:] | |
sys.stdout.buffer.write('testestsetset'.encode('utf-8')) | |
print(f'<h1>{folder_path}</h1>') | |
file_list = os.listdir(folder_path) | |
print('<ol>') | |
for i in file_list: | |
print('<li>') | |
if os.path.isdir(folder_path + '/' + i): | |
print(f'<a href="/r/in.py?dir={folder_path}/{i}">[{i}]</a>') | |
else: | |
file_size = os.path.getsize(folder_path + '/' + i) | |
size_unit = 'Bytes' | |
if file_size > 999999: | |
file_size = file_size / 1000000 | |
size_unit = 'MB' | |
elif file_size > 999: | |
file_size = file_size / 1000 | |
size_unit = 'KB' | |
if int(file_size) == file_size: | |
file_size_str = f'{file_size}{size_unit}' | |
else: | |
file_size_str = f'{file_size:.2f}{size_unit}' | |
print(f'<a href="/{folder_path}/{i.encode("utf-8").decode("unicode-escape")}" target="_blank">{i.encode("utf-8").decode("unicode-escape")} - <span | |
class="small">[{file_size_str}]</span></a>') | |
print('</li>') | |
print('</ol>') | |
except Exception as ex: | |
print(ex) | |
print('</body></html>') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fixed the problem with non-latin file names.