Changeset - df8186f89d4e
[Not reviewed]
master
0 0 1
cyrill - 9 months ago 2021-01-30 17:48:35
ake@headake.win
Added sample app with virtual hosts support
1 file changed with 42 insertions and 0 deletions:
0 comments (0 inline, 0 general)
files-vhosts.py
Show inline comments
 
new file 100755
 
import os
 
import mimetypes
 
from serpens import Serpens, SerpensResponse, error
 
 
DOCUMENT_ROOT = os.path.dirname(__file__)
 
 
app = Serpens()
 
 
@app.route('/')
 
def index(request):
 
    BASE_DIR = DOCUMENT_ROOT + '/' + request.hostname
 
    if os.path.isfile(BASE_DIR + '/index.gmi'):
 
        with open(BASE_DIR + '/index.gmi', 'rb') as f:
 
            return SerpensResponse(f.read(), 20, mediatype='text/gemini')
 
    else:
 
        output = ['# Index']
 
        for item in os.listdir(BASE_DIR):
 
            output.append('=> /{} {}'.format(item, item))
 
        return SerpensResponse('\n'.join(output).encode('utf-8'), 20, 'text/gemini')
 
 
@app.route('/{any:path}')
 
def file_access(request, path):
 
    BASE_DIR = DOCUMENT_ROOT + '/' + request.hostname
 
    full_path = os.path.join(BASE_DIR, path)
 
    if os.path.isdir(full_path):
 
        if os.path.isfile(full_path + '/index.gmi'):
 
            with open(full_path + '/index.gmi', 'rb') as f:
 
                return SerpensResponse(f.read(), 20, mediatype='text/gemini')
 
        else:
 
            output = ['# ' + path]
 
            for item in os.listdir(full_path):
 
                output.append('=> /{} {}'.format(os.path.join(path, item), item))
 
            return SerpensResponse('\n'.join(output).encode('utf-8'), 20, 'text/gemini')
 
    elif os.path.isfile(full_path):
 
        mediatype = mimetypes.guess_type(full_path)[0] or 'application/octet-stream'
 
        with open(full_path, 'rb') as f:
 
            return SerpensResponse(f.read(), 20, mediatype=mediatype)
 
    else:
 
        return error('Not found', 51)
 
 
 
application = app.wsgi
 
\ No newline at end of file
0 comments (0 inline, 0 general)