Merge branch 'master' of github.com:mitsuhiko/flask
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 · parents 43c6a1e, 0ba758d · Browse files · 21 files·+166 added−56 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
21 files+166 added−56 removed
- other:+166 added−56 removed
Provenance
- Commit
2e816f5- Tree
45be7f3- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent 1
43c6a1e- Parent 2
0ba758d
21 files changed+166 added−56 removed
modified:docs/deploying/cgi.rst+12 added-1 removed
33 unmodified lines34 Usually there are two ways to configure the server. Either just copy the35 `.cgi` into a `cgi-bin` (and use `mod_rewrite` or something similar to36 rewrite the URL) or let the server point to the file directly.37 38-In Apache for example you can put a like like this into the config:38+In Apache for example you can put something like this into the config:39 40 .. sourcecode:: apache41 42 ScriptAlias /app /path/to/the/application.cgi43 44+On shared webhosting, though, you might not have access to your Apache config.45+In this case, a file called `.htaccess`, sitting in the public directory you want46+your app to be available, works too but the `ScriptAlias` directive won't47+work in that case:48+49+.. sourcecode:: apache50+ 51+ RewriteEngine On52+ RewriteCond %{REQUEST_FILENAME} !-f # Don't interfere with static files53+ RewriteRule ^(.*)$ /path/to/the/application.cgi/$1 [L]54+55 For more information consult the documentation of your webserver.56 57 .. _App Engine: http://code.google.com/appengine/modified:docs/deploying/fastcgi.rst+1 added-1 removed
100 unmodified lines101 self.app = app102 103 def __call__(self, environ, start_response):104 environ['SCRIPT_NAME'] = ''105- return self.app(environ, start_response)105+ return self.app(environ, start_response)106 107 app = ScriptNameStripper(app)108 109 if __name__ == '__main__':110 unmodified linesmodified:docs/patterns/mongokit.rst-3 removed
120 unmodified lines121 >>> collection = connection['test'].users122 >>> user = {'name': u'admin', 'email': u'admin@localhost'}123 >>> collection.insert(user)124 125-print list(collection.find())126-print collection.find_one({'name': u'admin'})127-125 MongoKit will automatically commit for us.126 127 To query your database, you use the collection directly:128 13 unmodified linesmodified:docs/becomingbig.rst+3 added-2 removed
23 unmodified lines24 :ref:`signals`. You can provide custom classes for things like the request and25 response objects. Dig deeper on the APIs you use, and look for the26 customizations which are available out of the box in a Flask release. Look for27 ways in which your project can be refactored into a collection of utilities and28-Flask extensions. Explore the many extensions in the community, and look for29-patterns to build your own extensions if you do not find the tools you need.28+Flask extensions. Explore the many `extensions29+<http://flask.pocoo.org/extensions/>` in the community, and look for patterns to30+build your own extensions if you do not find the tools you need.31 32 Subclass.33 ---------34 67 unmodified linesmodified:docs/extensiondev.rst+4 added-4 removed
45 unmodified lines46 registered on PyPI. Also the development checkout link should work so47 that people can easily install the development version into their48 virtualenv without having to download the library by hand.49 50-Flask extensions must be licensed as BSD or MIT or a more liberal license51-to be enlisted on the Flask Extension Registry. Keep in mind that the52-Flask Extension Registry is a moderated place and libraries will be53-reviewed upfront if they behave as required.50+Flask extensions must be licensed under a BSD, MIT or more liberal license51+to be able to be enlisted in the Flask Extension Registry. Keep in mind52+that the Flask Extension Registry is a moderated place and libraries will53+be reviewed upfront if they behave as required.54 55 "Hello Flaskext!"56 -----------------57 364 unmodified linesmodified:docs/quickstart.rst+3 added-2 removed
512 unmodified lines513 request.form['password']):514 return log_the_user_in(request.form['username'])515 else:516 error = 'Invalid username/password'517- # this is executed if the request method was GET or the518- # credentials were invalid517+ # the code below this is executed if the request method518+ # was GET or the credentials were invalid519+ return render_template('login.html', error=error)520 521 What happens if the key does not exist in the `form` attribute? In that522 case a special :exc:`KeyError` is raised. You can catch it like a523 standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request330 unmodified linesadded:examples/blueprintexample/simple_page/templates/pages/hello.html+5 added
12345{% extends "pages/layout.html" %}
{% block body %} Hello{% endblock %}No newline at end of fileadded:examples/blueprintexample/simple_page/templates/pages/index.html+5 added
12345{% extends "pages/layout.html" %}
{% block body %} Blueprint example page{% endblock %}No newline at end of fileadded:examples/blueprintexample/simple_page/templates/pages/layout.html+25 added
1+<!doctype html>2+<title>Simple Page Blueprint</title>3+<div class=page>4+ <h1>This is blueprint example</h1>5+ <p>6+ A simple page blueprint is registered under / and /pages<br/>7+ you can access it using this urls:8+ <ul>9+ <li><a href="{{ url_for('simple_page.show', page='hello') }}">/hello</a></li>10+ <li><a href="{{ url_for('simple_page.show', page='world') }}">/world</a></li>11+ </ul>12+ </p>13+ <p>14+ Also you can register the same blueprint under another path15+ <ul>16+ <li><a href="/pages/hello">/pages/hello</a></li>17+ <li><a href="/pages/world">/pages/world</a></li>18+ </ul>19+ </p>20+ 21+22+ 23+ {% block body %}24+ {% endblock %}25+</div>added:examples/blueprintexample/simple_page/templates/pages/world.html+5 added
1+{% extends "pages/layout.html" %}2+3+{% block body %}4+ World5+{% endblock %}added:examples/blueprintexample/simple_page/__init__.py
added:examples/blueprintexample/simple_page/simple_page.py+13 added
1+from flask import Blueprint, render_template, abort2+from jinja2 import TemplateNotFound3+4+simple_page = Blueprint('simple_page', __name__,5+ template_folder='templates')6+7+@simple_page.route('/', defaults={'page': 'index'})8+@simple_page.route('/<page>')9+def show(page):10+ try:11+ return render_template('pages/%s.html' % page)12+ except TemplateNotFound:13+ abort(404)added:examples/blueprintexample/blueprintexample_test.py+36 added
1+# -*- coding: utf-8 -*-2+"""3+ Blueprint Example Tests4+ ~~~~~~~~~~~~~~5+6+ Tests the Blueprint example app7+"""8+import blueprintexample9+import unittest10+11+12+class BlueprintExampleTestCase(unittest.TestCase):13+14+ def setUp(self):15+ self.app = blueprintexample.app.test_client()16+ 17+ def test_urls(self):18+ r = self.app.get('/')19+ self.assertEquals(r.status_code, 200)20+ 21+ r = self.app.get('/hello')22+ self.assertEquals(r.status_code, 200)23+ 24+ r = self.app.get('/world')25+ self.assertEquals(r.status_code, 200)26+ 27+ #second blueprint instance28+ r = self.app.get('/pages/hello')29+ self.assertEquals(r.status_code, 200)30+ 31+ r = self.app.get('/pages/world')32+ self.assertEquals(r.status_code, 200)33+ 34+ 35+if __name__ == '__main__':36+ unittest.main()added:examples/blueprintexample/blueprintexample.py+11 added
1+from flask import Flask2+from simple_page.simple_page import simple_page3+4+app = Flask(__name__)5+app.register_blueprint(simple_page)6+# Blueprint can be registered many times7+app.register_blueprint(simple_page, url_prefix='/pages') 8+9+10+if __name__ == '__main__':11+ app.run(debug=True)modified:flask/testsuite/basic.py+23 added
951 unmodified lines952 953 self.assert_equal(c.get('/de/').data, '/de/about')954 self.assert_equal(c.get('/de/about').data, '/foo')955 self.assert_equal(c.get('/foo').data, '/en/about')956+ 957+ def test_inject_blueprint_url_defaults(self):958+ app = flask.Flask(__name__)959+ bp = flask.Blueprint('foo.bar.baz', __name__, 960+ template_folder='template')961 962+ @bp.url_defaults963+ def bp_defaults(endpoint, values):964+ values['page'] = 'login'965+ @bp.route('/<page>')966+ def view(page): pass967+968+ app.register_blueprint(bp)969+970+ values = dict()971+ app.inject_url_defaults('foo.bar.baz.view', values)972+ expected = dict(page='login')973+ self.assert_equal(values, expected) 974+975+ with app.test_request_context('/somepage'):976+ url = flask.url_for('foo.bar.baz.view')977+ expected = '/login'978+ self.assert_equal(url, expected)979+980 def test_debug_mode_complains_after_first_request(self):981 app = flask.Flask(__name__)982 app.debug = True983 @app.route('/')228 unmodified linesmodified:flask/testsuite/helpers.py+1 added-18 removed
71 unmodified lines72 return flask.jsonify(**d)73 @app.route('/dict')74 def return_dict():75 return flask.jsonify(d)76- @app.route("/unpadded")77- def return_padded_false():78- return flask.jsonify(d, padded=False)79- @app.route("/padded")80- def return_padded_true():81- return flask.jsonify(d, padded=True)82- @app.route("/padded_custom")83- def return_padded_json_custom_callback():84- return flask.jsonify(d, padded='my_func_name')76 c = app.test_client()86- for url in '/kw', '/dict', '/unpadded':77+ for url in '/kw', '/dict':78 rv = c.get(url)79 self.assert_equal(rv.mimetype, 'application/json')80 self.assert_equal(flask.json.loads(rv.data), d)90- for get_arg in 'callback=funcName', 'jsonp=funcName':91- rv = c.get('/padded?' + get_arg)92- self.assert_( rv.data.startswith("funcName(") )93- self.assert_( rv.data.endswith(")") )94- rv_json = rv.data.split('(')[1].split(')')[0]95- self.assert_equal(flask.json.loads(rv_json), d)96- rv = c.get('/padded_custom?my_func_name=funcName')97- self.assert_( rv.data.startswith("funcName(") )81 82 def test_json_attr(self):83 app = flask.Flask(__name__)84 @app.route('/add', methods=['POST'])323 unmodified linesmodified:flask/app.py+1 added-1 removed
1488 unmodified lines1489 .. versionadded:: 0.71490 """1491 funcs = self.url_default_functions.get(None, ())1492 if '.' in endpoint:1493- bp = endpoint.split('.', 1)[0]1493+ bp = endpoint.rsplit('.', 1)[0]1494 funcs = chain(funcs, self.url_default_functions.get(bp, ()))1495 for func in funcs:1496 func(endpoint, values)1497 204 unmodified linesmodified:flask/ctx.py+1 added-1 removed
38 unmodified lines39 40 @app.route('/')41 def index():42 @after_this_request43- def add_header():43+ def add_header(response):44 response.headers['X-Foo'] = 'Parachute'45 return response46 return 'Hello World!'47 236 unmodified linesmodified:flask/helpers.py+1 added-23 removed
116 unmodified lines117 security reasons only objects are supported toplevel. For more118 information about this, have a look at :ref:`json-security`.119 120 .. versionadded:: 0.2121-122- .. versionadded:: 0.9123- If the ``padded`` argument is true, the JSON object will be padded124- for JSONP calls and the response mimetype will be changed to125- ``application/javascript``. By default, the request arguments ``callback``126- and ``jsonp`` will be used as the name for the callback function.127- This will work with jQuery and most other JavaScript libraries128- by default.129-130- If the ``padded`` argument is a string, jsonify will look for131- the request argument with the same name and use that value as the132- callback-function name.121 """122 if __debug__:123 _assert_have_json()136- if 'padded' in kwargs:137- if isinstance(kwargs['padded'], str):138- callback = request.args.get(kwargs['padded']) or 'jsonp'139- else:140- callback = request.args.get('callback') or \141- request.args.get('jsonp') or 'jsonp'142- del kwargs['padded']143- json_str = json.dumps(dict(*args, **kwargs), indent=None)144- content = str(callback) + "(" + json_str + ")"145- return current_app.response_class(content, mimetype='application/javascript')124 return current_app.response_class(json.dumps(dict(*args, **kwargs),125 indent=None if request.is_xhr else 2), mimetype='application/json')126 127 378 unmodified lines506 507 rv.cache_control.public = True508 if cache_timeout is None:509 cache_timeout = current_app.get_send_file_max_age(filename)532- if cache_timeout:510+ if cache_timeout is not None:511 rv.cache_control.max_age = cache_timeout512 rv.expires = int(time() + cache_timeout)513 514 if add_etags and filename is not None:306 unmodified linesmodified:scripts/flaskext_compat.py+1 added
7 unmodified lines8 9 Usage::10 11 import flaskext_compat12+ flaskext_compat.activate()13 from flask.ext import foo14 15 :copyright: (c) 2011 by Armin Ronacher.16 :license: BSD, see LICENSE for more details.109 unmodified linesadded:.travis.yml+15 added
1+language: python2+3+python:4+ - 2.55+ - 2.66+ - 2.77+ - pypy8+9+before_install: pip install simplejson10+11+script: python setup.py test12+13+branches:14+ except:15+ - website