Skip to content

Commit

Permalink
Static file and static directory
Browse files Browse the repository at this point in the history
  • Loading branch information
pylover committed Sep 18, 2019
1 parent 5dc534f commit 65aa418
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 11 deletions.
8 changes: 7 additions & 1 deletion nanohttp/application.py
Expand Up @@ -7,7 +7,7 @@

import pymlconf

from . import statuses
from . import statuses, static
from .request import Request
from .response import Response

Expand Down Expand Up @@ -107,3 +107,9 @@ def request(self):
def response(self):
return self.threadlocal.response

def staticfile(self, pattern, filename):
return self.route(pattern)(static.file(self, filename))

def staticdirectory(self, directory):
return self.route(r'/(.*)')(static.directory(self, directory))

10 changes: 6 additions & 4 deletions nanohttp/static.py
Expand Up @@ -22,12 +22,13 @@ def get():
return get


def serverfile(filename):
raise NotImplementedError()
def directory(app, rootpath):
def get(location):
filename = path.join(rootpath, location)

if not path.exists(filename):
raise notfound()

def directory(app, rootpath):
def get():
app.response.length = path.getsize(filename)
app.response.type = guess_type(path.split(filename)[1])[0]
with open(filename, 'rb') as f:
Expand All @@ -38,4 +39,5 @@ def get():

yield chunk


return get
8 changes: 2 additions & 6 deletions tests/test_static.py
Expand Up @@ -10,9 +10,7 @@ def test_staticfile(app, session, when, tmpdir):
with open(indexfilename, 'w') as f:
f.write('foo')

indexfile = static.file(app, indexfilename)

app.route(r'/a\.txt')(indexfile)
app.staticfile(r'/a\.txt', indexfilename)

with session(app, '/a.txt'):
assert status == 200
Expand All @@ -26,9 +24,7 @@ def test_staticdirectory(app, session, when, tmpdir):
with open(indexfilename, 'w') as f:
f.write('foo')

handler = static.directory(app, tmpdir)

app.route(r'/(.*)')(handler)
app.staticdirectory(tmpdir)

with session(app, '/index.txt'):
assert status == 200
Expand Down

0 comments on commit 65aa418

Please sign in to comment.