Initial checkin of stuff that exists so far.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · the first commit · Browse files · 15 files·+984 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+984 added−0 removed
- other:+984 added−0 removed
Provenance
- Commit
33850c0- Tree
39953c1- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>
15 files changed+984 added−0 removed
added:examples/apishowcase/static/style.css+7 added
1234567body { font-family: 'Trebuchet MS', sans-serif;}
a { color: #44AD80;}added:examples/apishowcase/templates/counter.html+12 added
123456789101112{% extends "layout.html" %}{% block body %}<p> This is an example application that shows how the Werkzeug powered Flask microframework works.<p> The various parts of the example application:<ul> <li><a href="{{ url_for('hello_user') }}">Hello World</a> <li><a href="{{ url_for('counter') }}">Counter</a></ul>{% endblock %}added:examples/apishowcase/templates/hello.html+13 added
12345678910111213{% extends "layout.html" %}{% block body %} {% if name %} <h2>Hello {{ name }}!</h2> {% else %} <h3>Hello Stranger …</h3> <form action="{{ url_for('hello_user') }}" method="post"> <p>… What's your name? <p><input type=text name=name size=30> <input type=submit value="That's me"> </form> {% endif %}{% endblock %}added:examples/apishowcase/templates/index.html+11 added
1234567891011{% extends "layout.html" %}{% block body %}<p> This is an example application that shows how the Werkzeug powered Flask microframework works.<p> The various parts of the example application:<ul> <li><a href="{{ url_for('hello_user') }}">Hello World</a></ul>{% endblock %}added:examples/apishowcase/templates/layout.html+8 added
12345678<!doctype html><title>Flask API Showcase</title><link rel=stylesheet href="{{ url_for('static', filename='style.css') }}" type=text/css><h1>Flask API Showcase</h1>{% if request.endpoint != 'index' %}<div class=backlink><a href="{{ url_for('index') }}">« back to index</a></div>{% endif %}{% block body %}{% endblock %}added:examples/apishowcase/apishowcase.py+30 added
1+from flask import Flask, abort, redirect, request, session, \2+ render_template, url_for3+4+#: create a new flask applications. We pass it the name of our module5+#: so that flask knows where to look for templates and static files.6+app = Flask(__name__)7+8+9+@app.route('/', methods=['GET'])10+def index():11+ """Show an overview page"""12+ return render_template('index.html')13+14+15+@app.route('/hello/', methods=['GET', 'POST'])16+def hello_user():17+ """Ask the user for a name and redirect to :func:`hello`"""18+ if request.method == 'POST':19+ return redirect(url_for('hello', name=request.form['name']))20+ return render_template('hello.html', name=None)21+22+23+@app.route('/hello/<name>', methods=['GET'])24+def hello(name):25+ """Greet name friendly"""26+ return render_template('hello.html', name=name)27+28+29+if __name__ == '__main__':30+ app.run(debug=True)added:examples/minitwit/static/style.css+178 added
1+body {2+ background: #CAECE9;3+ font-family: 'Trebuchet MS', sans-serif;4+ font-size: 14px;5+}6+7+a {8+ color: #26776F;9+}10+11+a:hover {12+ color: #333;13+}14+15+input[type="text"],16+input[type="password"] {17+ background: white;18+ border: 1px solid #BFE6E2;19+ padding: 2px;20+ font-family: 'Trebuchet MS', sans-serif;21+ font-size: 14px;22+ -moz-border-radius: 2px;23+ -webkit-border-radius: 2px;24+ color: #105751;25+}26+27+input[type="submit"] {28+ background: #105751;29+ border: 1px solid #073B36;30+ padding: 1px 3px;31+ font-family: 'Trebuchet MS', sans-serif;32+ font-size: 14px;33+ font-weight: bold;34+ -moz-border-radius: 2px;35+ -webkit-border-radius: 2px;36+ color: white;37+}38+39+div.page {40+ background: white;41+ border: 1px solid #6ECCC4;42+ width: 700px;43+ margin: 30px auto;44+}45+46+div.page h1 {47+ background: #6ECCC4;48+ margin: 0;49+ padding: 10px 14px;50+ color: white;51+ letter-spacing: 1px;52+ text-shadow: 0 0 3px #24776F;53+ font-weight: normal;54+}55+56+div.page div.navigation {57+ background: #DEE9E8;58+ padding: 4px 10px;59+ border-top: 1px solid #ccc;60+ border-bottom: 1px solid #eee;61+ color: #888;62+ font-size: 12px;63+ letter-spacing: 0.5px;64+}65+66+div.page div.navigation a {67+ color: #444;68+ font-weight: bold;69+}70+71+div.page h2 {72+ margin: 0 0 15px 0;73+ color: #105751;74+ text-shadow: 0 1px 2px #ccc;75+}76+77+div.page div.body {78+ padding: 10px;79+}80+81+div.page div.footer {82+ background: #eee;83+ color: #888;84+ padding: 5px 10px;85+ font-size: 12px;86+}87+88+div.page div.followstatus {89+ border: 1px solid #ccc;90+ background: #E3EBEA;91+ -moz-border-radius: 2px;92+ -webkit-border-radius: 2px;93+ padding: 3px;94+ font-size: 13px;95+}96+97+div.page ul.messages {98+ list-style: none;99+ margin: 0;100+ padding: 0;101+}102+103+div.page ul.messages li {104+ margin: 10px 0;105+ padding: 5px;106+ background: #F0FAF9;107+ border: 1px solid #DBF3F1;108+ -moz-border-radius: 5px;109+ -webkit-border-radius: 5px;110+ min-height: 48px;111+}112+113+div.page ul.messages p {114+ margin: 0;115+}116+117+div.page ul.messages li img {118+ float: left;119+ padding: 0 10px 0 0;120+}121+122+div.page ul.messages li small {123+ font-size: 0.9em;124+ color: #888;125+}126+127+div.page div.twitbox {128+ margin: 10px 0;129+ padding: 5px;130+ background: #F0FAF9;131+ border: 1px solid #94E2DA;132+ -moz-border-radius: 5px;133+ -webkit-border-radius: 5px;134+}135+136+div.page div.twitbox h3 {137+ margin: 0;138+ font-size: 1em;139+ color: #2C7E76;140+}141+142+div.page div.twitbox p {143+ margin: 0;144+}145+146+div.page div.twitbox input[type="text"] {147+ width: 585px;148+}149+150+div.page div.twitbox input[type="submit"] {151+ width: 70px;152+ margin-left: 5px;153+}154+155+ul.flashes {156+ list-style: none;157+ margin: 10px 10px 0 10px;158+ padding: 0;159+}160+161+ul.flashes li {162+ background: #B9F3ED;163+ border: 1px solid #81CEC6;164+ -moz-border-radius: 2px;165+ -webkit-border-radius: 2px;166+ padding: 4px;167+ font-size: 13px;168+}169+170+div.error {171+ margin: 10px 0;172+ background: #FAE4E4;173+ border: 1px solid #DD6F6F;174+ -moz-border-radius: 2px;175+ -webkit-border-radius: 2px;176+ padding: 4px;177+ font-size: 13px;178+}added:examples/minitwit/templates/layout.html+32 added
1234567891011121314151617181920212223242526272829303132<!doctype html><title>{% block title %}Welcome{% endblock %} | MiniTwit</title><link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}"><div class=page> <h1>MiniTwit</h1> <div class=navigation> {% if g.user %} <a href="{{ url_for('timeline') }}">my timeline</a> | <a href="{{ url_for('public_timeline') }}">public timeline</a> | <a href="{{ url_for('logout') }}">sign out [{{ g.user.username }}]</a> {% else %} <a href="{{ url_for('public_timeline') }}">public timeline</a> | <a href="{{ url_for('register') }}">sign up</a> | <a href="{{ url_for('login') }}">sign in</a> {% endif %} </div> {% with flashes = get_flashed_messages() %} {% if flashes %} <ul class=flashes> {% for message in flashes %} <li>{{ message }} {% endfor %} </ul> {% endif %} {% endwith %} <div class=body> {% block body %}{% endblock %} </div> <div class=footer> MiniTwit — A Flask Application </div></div>added:examples/minitwit/templates/login.html+16 added
12345678910111213141516{% extends "layout.html" %}{% block title %}Sign In{% endblock %}{% block body %} <h2>Sign In</h2> {% if error %}<div class=error><strong>Error:</strong> {{ error }}</div>{% endif %} <form action="" method=post> <dl> <dt>Username: <dd><input type=text name=username size=30 value="{{ request.form.username }}"> <dt>Password: <dd><input type=password name=password size=30> </dl> <div class=actions><input type=submit value="Sign In"></div> </form>{% endblock %}
added:examples/minitwit/templates/register.html+19 added
1+{% extends "layout.html" %}2+{% block title %}Sign Up{% endblock %}3+{% block body %}4+ <h2>Sign Up</h2>5+ {% if error %}<div class=error><strong>Error:</strong> {{ error }}</div>{% endif %}6+ <form action="" method=post>7+ <dl>8+ <dt>Username:9+ <dd><input type=text name=username size=30 value="{{ request.form.username }}">10+ <dt>E-Mail:11+ <dd><input type=text name=email size=30 value="{{ request.form.email }}">12+ <dt>Password:13+ <dd><input type=password name=password size=30>14+ <dt>Password <small>(repeat)</small>:15+ <dd><input type=password name=password2 size=30>16+ </dl>17+ <div class=actions><input type=submit value="Sign Up"></div>18+ </form>19+{% endblock %}added:examples/minitwit/templates/timeline.html+49 added
1+{% extends "layout.html" %}2+{% block title %}3+ {% if request.endpoint == 'public_timeline' %}4+ Public Timeline5+ {% elif request.endpoint == 'user_timeline' %}6+ {{ profile_user.username }}'s Timeline7+ {% else %}8+ My Timeline9+ {% endif %}10+{% endblock %}11+{% block body %}12+ <h2>{{ self.title() }}</h2>13+ {% if g.user %}14+ {% if request.endpoint == 'user_timeline' %}15+ <div class=followstatus>16+ {% if g.user.user_id == profile_user.user_id %}17+ This is you!18+ {% elif followed %}19+ You are currently following this user.20+ <a class=unfollow href="{{ url_for('unfollow_user', username=profile_user.username)21+ }}">Unfollow user</a>.22+ {% else %}23+ You are not yet following this user.24+ <a class=follow href="{{ url_for('follow_user', username=profile_user.username)25+ }}">Follow user</a>.26+ {% endif %}27+ </div>28+ {% elif request.endpoint == 'timeline' %}29+ <div class=twitbox>30+ <h3>What's on your mind {{ g.user.username }}?</h3>31+ <form action="{{ url_for('add_message') }}" method=post>32+ <p><input type=text name=text size=60><!--33+ --><input type=submit value="Share">34+ </form>35+ </div>36+ {% endif %}37+ {% endif %}38+ <ul class=messages>39+ {% for message in messages %}40+ <li><img src="{{ message.email|gravatar(size=48) }}"><p>41+ <strong><a href="{{ url_for('user_timeline', username=message.username)42+ }}">{{ message.username }}</a></strong>43+ {{ message.text }}44+ <small>— {{ message.pub_date|datetimeformat }}</small>45+ {% else %}46+ <li><em>There are no messages so far.</em>47+ {% endfor %}48+ </ul>49+{% endblock %}added:examples/minitwit/minitwit.py+228 added
1+# -*- coding: utf-8 -*-2+from __future__ import with_statement3+import re4+import time5+import sqlite36+from hashlib import md57+from datetime import datetime8+from contextlib import closing9+from flask import Flask, request, session, url_for, redirect, \10+ render_template, abort, g, flash, generate_password_hash, \11+ check_password_hash12+13+14+# configuration15+DATABASE = '/tmp/minitwit.db'16+PER_PAGE = 3017+DEBUG = True18+SECRET_KEY = 'development key'19+20+# create our little application :)21+app = Flask(__name__)22+23+24+def connect_db():25+ """Returns a new database connection to the database."""26+ return sqlite3.connect(DATABASE)27+28+29+def init_db():30+ """Creates the database tables."""31+ with closing(connect_db()) as db:32+ with app.open_resource('schema.sql') as f:33+ db.cursor().executescript(f.read())34+ db.commit()35+36+37+def query_db(query, args=(), one=False):38+ """Queries the database and returns a list of dictionaries."""39+ cur = g.db.execute(query, args)40+ rv = [dict((cur.description[idx][0], value)41+ for idx, value in enumerate(row)) for row in cur.fetchall()]42+ return (rv[0] if rv else None) if one else rv43+44+45+def get_user_id(username):46+ """Convenience method to look up the id for a username"""47+ rv = g.db.execute('select user_id from user where username = ?',48+ [username]).fetchone()49+ return rv[0] if rv else None50+51+52+def format_datetime(timestamp):53+ """Format a timestamp for display"""54+ return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d @ %H:%M')55+56+57+def gravatar_url(email, size=80):58+ """Return the gravatar image for the given email address"""59+ return 'http://www.gravatar.com/avatar/%s?d=identicon&s=%d' % \60+ (md5(email.lower().encode('utf-8')).hexdigest(), size)61+62+63+@app.request_init64+def before_request():65+ """Make sure we are connected to the database each request and look66+ up the current user so that we know he's there.67+ """68+ g.db = sqlite3.connect(DATABASE)69+ if 'user_id' in session:70+ g.user = query_db('select * from user where user_id = ?',71+ [session['user_id']], one=True)72+73+74+@app.request_shutdown75+def after_request(request):76+ """Closes the database again at the end of the request."""77+ g.db.close()78+ return request79+80+81+@app.route('/')82+def timeline():83+ if not 'user_id' in session:84+ return redirect(url_for('public_timeline'))85+ offset = request.args.get('offset', type=int)86+ return render_template('timeline.html', messages=query_db('''87+ select message.*, user.* from message, user88+ where message.author_id = user.user_id and (89+ user.user_id = ? or90+ user.user_id in (select whom_id from follower91+ where who_id = ?))92+ order by message.pub_date desc limit ?''',93+ [session['user_id'], session['user_id'], PER_PAGE]))94+95+96+@app.route('/public')97+def public_timeline():98+ return render_template('timeline.html', messages=query_db('''99+ select message.*, user.* from message, user100+ where message.author_id = user.user_id101+ order by message.pub_date desc limit ?''', [PER_PAGE]))102+103+104+@app.route('/<username>')105+def user_timeline(username):106+ profile_user = query_db('select * from user where username = ?',107+ [username], one=True)108+ if profile_user is None:109+ abort(404)110+ followd = False111+ if 'user_id' in session:112+ followed = query_db('''select 1 from follower where113+ follower.who_id = ? and follower.whom_id = ?''',114+ [session['user_id'], profile_user['user_id']], one=True) is not None115+ return render_template('timeline.html', messages=query_db('''116+ select message.*, user.* from message, user where117+ user.user_id = message.author_id and user.user_id = ?118+ order by message.pub_date desc limit ?''',119+ [profile_user['user_id'], PER_PAGE]), followed=followed,120+ profile_user=profile_user)121+122+123+@app.route('/<username>/follow')124+def follow_user(username):125+ if not 'user_id' in session:126+ abort(401)127+ whom_id = get_user_id(username)128+ if whom_id is None:129+ abort(404)130+ g.db.execute('insert into follower (who_id, whom_id) values (?, ?)',131+ [session['user_id'], whom_id])132+ g.db.commit()133+ flash('You are now following "%s"' % username)134+ return redirect(url_for('user_timeline', username=username))135+136+137+@app.route('/<username>/unfollow')138+def unfollow_user(username):139+ if not 'user_id' in session:140+ abort(401)141+ whom_id = get_user_id(username)142+ if whom_id is None:143+ abort(404)144+ g.db.execute('delete from follower where who_id=? and whom_id=?',145+ [session['user_id'], whom_id])146+ g.db.commit()147+ flash('You are no longer following "%s"' % username)148+ return redirect(url_for('user_timeline', username=username))149+150+151+@app.route('/add_message')152+def add_message():153+ if 'user_id' not in session:154+ abort(401)155+ if request.form['text']:156+ g.db.execute('''insert into message (author_id, text, pub_date)157+ values (?, ?, ?)''', (session['user_id'], request.form['text'],158+ int(time.time())))159+ g.db.commit()160+ flash('Your message was recorded')161+ return redirect(url_for('timeline'))162+163+164+@app.route('/login')165+def login():166+ if 'user_id' in session:167+ return redirect(url_for('timeline'))168+ error = None169+ if request.method == 'POST':170+ user = query_db('''select * from user where171+ username = ?''', [request.form['username']], one=True)172+ if user is None:173+ error = 'Invalid username'174+ elif not check_password_hash(user['pw_hash'],175+ request.form['password']):176+ error = 'Invalid password'177+ else:178+ flash('You were logged in')179+ session['user_id'] = user['user_id']180+ return redirect(url_for('timeline'))181+ return render_template('login.html', error=error)182+183+184+@app.route('/register')185+def register():186+ if 'user_id' in session:187+ return redirect(url_for('timeline'))188+ error = None189+ if request.method == 'POST':190+ if not request.form['username']:191+ error = 'You have to enter a username'192+ elif not request.form['email'] or \193+ '@' not in request.form['email']:194+ error = 'You have to enter a valid email address'195+ elif not request.form['password']:196+ error = 'You have to enter a password'197+ elif request.form['password'] != request.form['password2']:198+ error = 'The two passwords to not match'199+ elif get_user_id(request.form['username']) is not None:200+ error = 'The username is already taken'201+ else:202+ g.db.execute('''insert into user (203+ username, email, pw_hash) values (?, ?, ?)''',204+ [request.form['username'], request.form['email'],205+ generate_password_hash(request.form['password'])])206+ g.db.commit()207+ flash('You were successfully registered and can login now')208+ return redirect(url_for('login'))209+ return render_template('register.html', error=error)210+211+212+@app.route('/logout')213+def logout():214+ flash('You were logged out')215+ session.pop('user_id', None)216+ return redirect(url_for('public_timeline'))217+218+219+# add some filters to jinja and set the secret key and debug mode220+# from the configuration.221+app.jinja_env.filters['datetimeformat'] = format_datetime222+app.jinja_env.filters['gravatar'] = gravatar_url223+app.secret_key = SECRET_KEY224+app.debug = DEBUG225+226+227+if __name__ == '__main__':228+ app.run()added:examples/minitwit/schema.sql+21 added
1+drop table if exists user;2+create table user (3+ user_id integer primary key autoincrement,4+ username string not null,5+ email string not null,6+ pw_hash string not null7+);8+9+drop table if exists follower;10+create table follower (11+ who_id integer,12+ whom_id integer13+);14+15+drop table if exists message;16+create table message (17+ message_id integer primary key autoincrement,18+ author_id integer not null,19+ text string not null,20+ pub_date integer21+);added:.gitignore+4 added
1+.DS_Store2+*.pyc3+*.pyo4+envadded:flask.py+356 added
1+# -*- coding: utf-8 -*-2+"""3+ flask4+ ~~~~~5+6+ A microframework based on Werkzeug. It's extensively documented7+ and follows best practice patterns.8+9+ :copyright: (c) 2010 by Armin Ronacher.10+ :license: BSD, see LICENSE for more details.11+"""12+import os13+import sys14+import pkg_resources15+from threading import local16+from jinja2 import Environment, PackageLoader17+from werkzeug import Request, Response, LocalStack, LocalProxy18+from werkzeug.routing import Map, Rule19+from werkzeug.exceptions import HTTPException, InternalServerError20+from werkzeug.contrib.securecookie import SecureCookie21+22+# try to import the json helpers23+try:24+ from simplejson import loads as load_json, dumps as dump_json25+except ImportError:26+ try:27+ from json import loads as load_json, dumps as dump_json28+ except ImportError:29+ pass30+31+# utilities we import from Werkzeug and Jinja2 that are unused32+# in the module but are exported as public interface.33+from werkzeug import abort, redirect, secure_filename, cached_property, \34+ html, import_string, generate_password_hash, check_password_hash35+from jinja2 import Markup, escape36+37+38+class FlaskRequest(Request):39+ """The request object used by default in flask. Remembers the40+ matched endpoint and view arguments.41+ """42+43+ def __init__(self, environ):44+ Request.__init__(self, environ)45+ self.endpoint = None46+ self.view_args = None47+48+49+class FlaskResponse(Response):50+ """The response object that is used by default in flask. Works like the51+ response object from Werkzeug but is set to have a HTML mimetype by52+ default.53+ """54+ default_mimetype = 'text/html'55+56+57+class _RequestGlobals(object):58+ pass59+60+61+class _RequestContext(object):62+ """The request context contains all request relevant information. It is63+ created at the beginning of the request and pushed to the64+ `_request_ctx_stack` and removed at the end of it. It will create the65+ URL adapter and request object for the WSGI environment provided.66+ """67+68+ def __init__(self, app, environ):69+ self.app = app70+ self.url_adapter = app.url_map.bind_to_environ(environ)71+ self.request = app.request_class(environ)72+ self.session = app.open_session(self.request)73+ self.g = _RequestGlobals()74+ self.flashes = None75+76+77+def url_for(endpoint, **values):78+ """Generates a URL to the given endpoint with the method provided.79+80+ :param endpoint: the endpoint of the URL (name of the function)81+ :param values: the variable arguments of the URL rule82+ """83+ return _request_ctx_stack.top.url_adapter.build(endpoint, values)84+85+86+def jsonified(**values):87+ """Returns a json response"""88+ return current_app.response_class(dump_json(values),89+ mimetype='application/json')90+91+92+def flash(message):93+ """Flashes a message to the next request. In order to remove the94+ flashed message from the session and to display it to the user,95+ the template has to call :func:`get_flashed_messages`.96+ """97+ session['_flashes'] = (session.get('_flashes', [])) + [message]98+99+100+def get_flashed_messages():101+ """Pulls all flashed messages from the session and returns them.102+ Further calls in the same request to the function will return103+ the same messages.104+ """105+ flashes = _request_ctx_stack.top.flashes106+ if flashes is None:107+ _request_ctx_stack.top.flashes = flashes = \108+ session.pop('_flashes', [])109+ return flashes110+111+112+def render_template(template_name, **context):113+ """Renders a template from the template folder with the given114+ context.115+ """116+ return current_app.jinja_env.get_template(template_name).render(context)117+118+119+def render_template_string(source, **context):120+ """Renders a template from the given template source string121+ with the given context.122+ """123+ return current_app.jinja_env.from_string(source).render(context)124+125+126+class Flask(object):127+ """The flask object implements a WSGI application and acts as the central128+ object. It is passed the name of the module or package of the application129+ and optionally a configuration. When it's created it sets up the130+ template engine and provides ways to register view functions.131+ """132+133+ #: the class that is used for request objects134+ request_class = FlaskRequest135+136+ #: the class that is used for response objects137+ response_class = FlaskResponse138+139+ #: path for the static files. If you don't want to use static files140+ #: you can set this value to `None` in which case no URL rule is added141+ #: and the development server will no longer serve any static files.142+ static_path = '/static'143+144+ #: if a secret key is set, cryptographic components can use this to145+ #: sign cookies and other things. Set this to a complex random value146+ #: when you want to use the secure cookie for instance.147+ secret_key = None148+149+ #: The secure cookie uses this for the name of the session cookie150+ session_cookie_name = 'session'151+152+ #: options that are passed directly to the Jinja2 environment153+ jinja_options = dict(154+ autoescape=True,155+ extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']156+ )157+158+ def __init__(self, package_name):159+ self.debug = False160+ self.package_name = package_name161+ self.view_functions = {}162+ self.error_handlers = {}163+ self.request_init_funcs = []164+ self.request_shutdown_funcs = []165+ self.url_map = Map()166+167+ if self.static_path is not None:168+ self.url_map.add(Rule(self.static_path + '/<filename>',169+ build_only=True, endpoint='static'))170+171+ self.jinja_env = Environment(loader=self.create_jinja_loader(),172+ **self.jinja_options)173+ self.jinja_env.globals.update(174+ url_for=url_for,175+ request=request,176+ session=session,177+ g=g,178+ get_flashed_messages=get_flashed_messages179+ )180+181+ def create_jinja_loader(self):182+ """Creates the Jinja loader. By default just a package loader for183+ the configured package is returned that looks up templates in the184+ `templates` folder. To add other loaders it's possible to185+ override this method.186+ """187+ return PackageLoader(self.package_name)188+189+ def run(self, host='localhost', port=5000, **options):190+ """Runs the application on a local development server"""191+ from werkzeug import run_simple192+ if 'debug' in options:193+ self.debug = options.pop('debug')194+ if self.static_path is not None:195+ options['static_files'] = {196+ self.static_path: (self.package_name, 'static')197+ }198+ options.setdefault('use_reloader', self.debug)199+ options.setdefault('use_debugger', self.debug)200+ return run_simple(host, port, self, **options)201+202+ @cached_property203+ def test(self):204+ """A test client for this application"""205+ from werkzeug import Client206+ return Client(self, self.response_class, use_cookies=True)207+208+ def open_resource(self, resource):209+ """Opens a resource from the application's resource folder"""210+ return pkg_resources.resource_stream(self.package_name, resource)211+212+ def open_session(self, request):213+ """Creates or opens a new session. Default implementation requires214+ that `securecookie.secret_key` is set.215+ """216+ key = self.secret_key217+ if key is not None:218+ return SecureCookie.load_cookie(request, self.session_cookie_name,219+ secret_key=key)220+221+ def save_session(self, session, response):222+ """Saves the session if it needs updates."""223+ if session is not None:224+ session.save_cookie(response, self.session_cookie_name)225+226+ def route(self, rule, **options):227+ """A decorator that is used to register a view function for a228+ given URL rule. Example::229+230+ @app.route('/')231+ def index():232+ return 'Hello World'233+ """234+ def decorator(f):235+ if 'endpoint' not in options:236+ options['endpoint'] = f.__name__237+ self.url_map.add(Rule(rule, **options))238+ self.view_functions[options['endpoint']] = f239+ return f240+ return decorator241+242+ def errorhandler(self, code):243+ """A decorator that is used to register a function give a given244+ error code. Example::245+246+ @app.errorhandler(404)247+ def page_not_found():248+ return 'This page does not exist', 404249+ """250+ def decorator(f):251+ self.error_handlers[code] = f252+ return f253+ return decorator254+255+ def request_init(self, f):256+ """Registers a function to run before each request."""257+ self.request_init_funcs.append(f)258+ return f259+260+ def request_shutdown(self, f):261+ """Register a function to be run after each request."""262+ self.request_shutdown_funcs.append(f)263+ return f264+265+ def match_request(self):266+ """Matches the current request against the URL map and also267+ stores the endpoint and view arguments on the request object268+ is successful, otherwise the exception is stored.269+ """270+ rv = _request_ctx_stack.top.url_adapter.match()271+ request.endpoint, request.view_args = rv272+ return rv273+274+ def dispatch_request(self):275+ """Does the request dispatching. Matches the URL and returns the276+ return value of the view or error handler. This does not have to277+ be a response object. In order to convert the return value to a278+ proper response object, call :func:`make_response`.279+ """280+ try:281+ endpoint, values = self.match_request()282+ return self.view_functions[endpoint](**values)283+ except HTTPException, e:284+ handler = self.error_handlers.get(e.code)285+ if handler is None:286+ return e287+ return handler(e)288+ except Exception, e:289+ handler = self.error_handlers.get(500)290+ if self.debug or handler is None:291+ raise292+ return handler(e)293+294+ def make_response(self, rv):295+ """Converts the return value from a view function to a real296+ response object that is an instance of :attr:`response_class`.297+ """298+ if isinstance(rv, self.response_class):299+ return rv300+ if isinstance(rv, basestring):301+ return self.response_class(rv)302+ if isinstance(rv, tuple):303+ return self.response_class(*rv)304+ return self.response_class.force_type(rv, request.environ)305+306+ def preprocess_request(self):307+ """Called before the actual request dispatching and will308+ call every as :func:`request_init` decorated function.309+ If any of these function returns a value it's handled as310+ if it was the return value from the view and further311+ request handling is stopped.312+ """313+ for func in self.request_init_funcs:314+ rv = func()315+ if rv is not None:316+ return rv317+318+ def process_response(self, response):319+ """Can be overridden in order to modify the response object320+ before it's sent to the WSGI server.321+ """322+ session = _request_ctx_stack.top.session323+ if session is not None:324+ self.save_session(session, response)325+ for handler in self.request_shutdown_funcs:326+ response = handler(response)327+ return response328+329+ def wsgi_app(self, environ, start_response):330+ """The actual WSGI application. This is not implemented in331+ `__call__` so that middlewares can be applied:332+333+ app.wsgi_app = MyMiddleware(app.wsgi_app)334+ """335+ _request_ctx_stack.push(_RequestContext(self, environ))336+ try:337+ rv = self.preprocess_request()338+ if rv is None:339+ rv = self.dispatch_request()340+ response = self.make_response(rv)341+ response = self.process_response(response)342+ return response(environ, start_response)343+ finally:344+ _request_ctx_stack.pop()345+346+ def __call__(self, environ, start_response):347+ """Shortcut for :attr:`wsgi_app`"""348+ return self.wsgi_app(environ, start_response)349+350+351+# context locals352+_request_ctx_stack = LocalStack()353+current_app = LocalProxy(lambda: _request_ctx_stack.top.app)354+request = LocalProxy(lambda: _request_ctx_stack.top.request)355+session = LocalProxy(lambda: _request_ctx_stack.top.session)356+g = LocalProxy(lambda: _request_ctx_stack.top.g)