Skip to content

Commit

Permalink
Add asyncio file upload example
Browse files Browse the repository at this point in the history
  • Loading branch information
miguelgrinberg committed Nov 16, 2022
1 parent 24d74fb commit c841cbe
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
5 changes: 3 additions & 2 deletions examples/uploads/uploads.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from microdot import Microdot, send_file
from microdot import Microdot, send_file, Request

app = Microdot()
Request.max_content_length = 1024 * 1024 # 1MB (change as needed)


@app.get('/')
Expand Down Expand Up @@ -30,4 +31,4 @@ def upload(request):


if __name__ == '__main__':
app.run()
app.run(debug=True)
34 changes: 34 additions & 0 deletions examples/uploads/uploads_async.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from microdot_asyncio import Microdot, send_file, Request

app = Microdot()
Request.max_content_length = 1024 * 1024 # 1MB (change as needed)


@app.get('/')
async def index(request):
return send_file('index.html')


@app.post('/upload')
async def upload(request):
# obtain the filename and size from request headers
filename = request.headers['Content-Disposition'].split(
'filename=')[1].strip('"')
size = int(request.headers['Content-Length'])

# sanitize the filename
filename = filename.replace('/', '_')

# write the file to the files directory in 1K chunks
with open('files/' + filename, 'wb') as f:
while size > 0:
chunk = await request.stream.read(min(size, 1024))
f.write(chunk)
size -= len(chunk)

print('Successfully saved file: ' + filename)
return ''


if __name__ == '__main__':
app.run(debug=True)

0 comments on commit c841cbe

Please sign in to comment.