Created
October 22, 2012 11:00
-
-
Save benhosmer/3930988 to your computer and use it in GitHub Desktop.
bottle.py notes
This file contains 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
from bottle import route, run, static_file, request, abort, redirect, view, template | |
import re | |
# Serve a static html with templates | |
# Create an index.tpl and save it in /views | |
''' | |
#Sample index.tpl | |
<html> | |
<head> | |
<link rel="stylesheet" type="text/css" href="/static/styles.css" /> | |
</head> | |
<body> | |
Welcome to {{ name }} | |
<p>The Time is {{ current_time }} | |
</body> | |
</html> | |
''' | |
@route('/') | |
@view('index') | |
def index(name='bawk', current_time=datetime.now()): | |
return dict(name=name, current_time=current_time) | |
@route('/') | |
def index(name=['hello', 'World', 'from <a href="http://benhosmer.appspot.com">Google App Engine</a>']): | |
return '<br>'.join(name) | |
# Serving a static file | |
''' | |
# This works! NOTE: Use absolute path names | |
@route('/images/<filename:path>') | |
def send_image(filename): | |
return static_file(filename, root='/absolute/path/to/file') | |
''' | |
# This allows access to the /static directory and the css files | |
@route('/static/<filename:path>') | |
def send_css(filename): | |
return static_file(filename, root='/absolute/path/to/file') | |
# This works too to serve static files | |
@route('/images/<filename:re:.*\.jpg>') | |
def send_image(filename): | |
return static_file(filename, root='/absolute/path/to/file') | |
# Forced Downloads | |
@route('/download/<filename:path>') | |
def download(filename): | |
return static_file(filename, root='/absolute/path/to/file', download='_mycoolname') | |
# A custom access denied message | |
@route('/restricted') | |
def restricted(): | |
abort(401, "Sorry, access denied.") | |
# A custom 404 message | |
@route('/butt') | |
def restricted(): | |
abort(404, "Sorry, not found.") | |
# A redirect | |
@route('/joey') | |
def wrong(): | |
redirect("/") | |
# A very simple form generation | |
@route('/upload', method='GET') | |
def my_form(): | |
return'''<form action="/upload" method="post" enctype="multipart/form-data"> | |
<input type="text" name="name" /> | |
<input type="submit" name="submit" /> | |
</form>''' | |
# A simple upload | |
@route('/upload', method='POST') | |
def do_upload(): | |
name = request.forms.name | |
data = request.files.submit | |
if name: | |
return "Hello %s!" % (name) | |
return "You missed a field." | |
# Production with GAppEngine | |
#run(server="gae") | |
# Development | |
run(host='localhost', port=9090, debug=True, reloader=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment