Skip to content
Myr

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

15 files+984 added−0 removed

added:examples/apishowcase/static/style.css+7 added
added:examples/apishowcase/templates/counter.html+12 added
added:examples/apishowcase/templates/hello.html+13 added
added:examples/apishowcase/templates/index.html+11 added
added:examples/apishowcase/templates/layout.html+8 added
added:examples/apishowcase/apishowcase.py+30 added
1from flask import Flask, abort, redirect, request, session, \2 render_template, url_for34#: 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.6app = Flask(__name__)789@app.route('/', methods=['GET'])10def index():11 """Show an overview page"""12 return render_template('index.html')131415@app.route('/hello/', methods=['GET', 'POST'])16def 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)212223@app.route('/hello/<name>', methods=['GET'])24def hello(name):25 """Greet name friendly"""26 return render_template('hello.html', name=name)272829if __name__ == '__main__':30 app.run(debug=True)
added:examples/minitwit/static/style.css+178 added
1body {2 background: #CAECE9;3 font-family: 'Trebuchet MS', sans-serif;4 font-size: 14px;5}67a {8 color: #26776F;9}1011a:hover {12 color: #333;13}1415input[type="text"],16input[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}2627input[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}3839div.page {40 background: white;41 border: 1px solid #6ECCC4;42 width: 700px;43 margin: 30px auto;44}4546div.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}5556div.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}6566div.page div.navigation a {67 color: #444;68 font-weight: bold;69}7071div.page h2 {72 margin: 0 0 15px 0;73 color: #105751;74 text-shadow: 0 1px 2px #ccc;75}7677div.page div.body {78 padding: 10px;79}8081div.page div.footer {82 background: #eee;83 color: #888;84 padding: 5px 10px;85 font-size: 12px;86}8788div.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}9697div.page ul.messages {98 list-style: none;99 margin: 0;100 padding: 0;101}102103div.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}112113div.page ul.messages p {114 margin: 0;115}116117div.page ul.messages li img {118 float: left;119 padding: 0 10px 0 0;120}121122div.page ul.messages li small {123 font-size: 0.9em;124 color: #888;125}126127div.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}135136div.page div.twitbox h3 {137 margin: 0;138 font-size: 1em;139 color: #2C7E76;140}141142div.page div.twitbox p {143 margin: 0;144}145146div.page div.twitbox input[type="text"] {147 width: 585px;148}149150div.page div.twitbox input[type="submit"] {151 width: 70px;152 margin-left: 5px;153}154155ul.flashes {156 list-style: none;157 margin: 10px 10px 0 10px;158 padding: 0;159}160161ul.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}169170div.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
added:examples/minitwit/templates/login.html+16 added
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>&mdash; {{ 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 -*-2from __future__ import with_statement3import re4import time5import sqlite36from hashlib import md57from datetime import datetime8from contextlib import closing9from flask import Flask, request, session, url_for, redirect, \10 render_template, abort, g, flash, generate_password_hash, \11 check_password_hash121314# configuration15DATABASE = '/tmp/minitwit.db'16PER_PAGE = 3017DEBUG = True18SECRET_KEY = 'development key'1920# create our little application :)21app = Flask(__name__)222324def connect_db():25 """Returns a new database connection to the database."""26 return sqlite3.connect(DATABASE)272829def 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()353637def 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 rv434445def 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 None505152def format_datetime(timestamp):53 """Format a timestamp for display"""54 return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d @ %H:%M')555657def 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)616263@app.request_init64def 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)727374@app.request_shutdown75def after_request(request):76 """Closes the database again at the end of the request."""77 g.db.close()78 return request798081@app.route('/')82def 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]))949596@app.route('/public')97def 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]))102103104@app.route('/<username>')105def 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)121122123@app.route('/<username>/follow')124def 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))135136137@app.route('/<username>/unfollow')138def 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))149150151@app.route('/add_message')152def 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'))162163164@app.route('/login')165def 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)182183184@app.route('/register')185def 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)210211212@app.route('/logout')213def logout():214 flash('You were logged out')215 session.pop('user_id', None)216 return redirect(url_for('public_timeline'))217218219# add some filters to jinja and set the secret key and debug mode220# from the configuration.221app.jinja_env.filters['datetimeformat'] = format_datetime222app.jinja_env.filters['gravatar'] = gravatar_url223app.secret_key = SECRET_KEY224app.debug = DEBUG225226227if __name__ == '__main__':228 app.run()
added:examples/minitwit/schema.sql+21 added
1drop table if exists user;2create 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);89drop table if exists follower;10create table follower (11 who_id integer,12 whom_id integer13);1415drop table if exists message;16create 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*.pyo4env
added:flask.py+356 added
1# -*- coding: utf-8 -*-2"""3 flask4 ~~~~~56 A microframework based on Werkzeug. It's extensively documented7 and follows best practice patterns.89 :copyright: (c) 2010 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""12import os13import sys14import pkg_resources15from threading import local16from jinja2 import Environment, PackageLoader17from werkzeug import Request, Response, LocalStack, LocalProxy18from werkzeug.routing import Map, Rule19from werkzeug.exceptions import HTTPException, InternalServerError20from werkzeug.contrib.securecookie import SecureCookie2122# try to import the json helpers23try:24 from simplejson import loads as load_json, dumps as dump_json25except ImportError:26 try:27 from json import loads as load_json, dumps as dump_json28 except ImportError:29 pass3031# utilities we import from Werkzeug and Jinja2 that are unused32# in the module but are exported as public interface.33from werkzeug import abort, redirect, secure_filename, cached_property, \34 html, import_string, generate_password_hash, check_password_hash35from jinja2 import Markup, escape363738class FlaskRequest(Request):39 """The request object used by default in flask. Remembers the40 matched endpoint and view arguments.41 """4243 def __init__(self, environ):44 Request.__init__(self, environ)45 self.endpoint = None46 self.view_args = None474849class 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'555657class _RequestGlobals(object):58 pass596061class _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 """6768 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 = None757677def url_for(endpoint, **values):78 """Generates a URL to the given endpoint with the method provided.7980 :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)848586def jsonified(**values):87 """Returns a json response"""88 return current_app.response_class(dump_json(values),89 mimetype='application/json')909192def 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]9899100def 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 flashes110111112def 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)117118119def 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)124125126class 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 """132133 #: the class that is used for request objects134 request_class = FlaskRequest135136 #: the class that is used for response objects137 response_class = FlaskResponse138139 #: 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'143144 #: 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 = None148149 #: The secure cookie uses this for the name of the session cookie150 session_cookie_name = 'session'151152 #: options that are passed directly to the Jinja2 environment153 jinja_options = dict(154 autoescape=True,155 extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']156 )157158 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()166167 if self.static_path is not None:168 self.url_map.add(Rule(self.static_path + '/<filename>',169 build_only=True, endpoint='static'))170171 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 )180181 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)188189 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)201202 @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)207208 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)211212 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)220221 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)225226 def route(self, rule, **options):227 """A decorator that is used to register a view function for a228 given URL rule. Example::229230 @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 decorator241242 def errorhandler(self, code):243 """A decorator that is used to register a function give a given244 error code. Example::245246 @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 decorator254255 def request_init(self, f):256 """Registers a function to run before each request."""257 self.request_init_funcs.append(f)258 return f259260 def request_shutdown(self, f):261 """Register a function to be run after each request."""262 self.request_shutdown_funcs.append(f)263 return f264265 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 rv273274 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)293294 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)305306 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 rv317318 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 response328329 def wsgi_app(self, environ, start_response):330 """The actual WSGI application. This is not implemented in331 `__call__` so that middlewares can be applied:332333 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()345346 def __call__(self, environ, start_response):347 """Shortcut for :attr:`wsgi_app`"""348 return self.wsgi_app(environ, start_response)349350351# context locals352_request_ctx_stack = LocalStack()353current_app = LocalProxy(lambda: _request_ctx_stack.top.app)354request = LocalProxy(lambda: _request_ctx_stack.top.request)355session = LocalProxy(lambda: _request_ctx_stack.top.session)356g = LocalProxy(lambda: _request_ctx_stack.top.g)