Skip to content
Myr

Added interactive Python docs, fixed part style.

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 · parent 9d98ad5 · Browse files · 8 files+215 added−81 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

8 files+215 added−81 removed

  • tests:+17 added−0 removed
  • other:+198 added−81 removed

8 files+215 added−81 removed

added:docs/contents.rst.inc+43 added
1User's Guide2------------34This part of the documentation is written text and should give you an idea5how to work with Flask. It's a series of step-by-step instructions for6web development.78.. toctree::9 :maxdepth: 21011 foreword12 installation13 quickstart14 tutorial/index15 testing16 errorhandling17 shell18 patterns/index19 deploying/index20 becomingbig2122API Reference23-------------2425If you are looking for information on a specific function, class or26method, this part of the documentation is for you.2728.. toctree::29 :maxdepth: 23031 api3233Additional Notes34----------------3536Design notes, legal information and changelog are here for the interested.3738.. toctree::39 :maxdepth: 24041 design42 license43 changelog
modified:docs/flaskstyle.sty+4 added-4 removed
1\pagenumbering{arabic}1\definecolor{TitleColor}{rgb}{0,0,0}2\definecolor{InnerLinkColor}{rgb}{0,0,0}34\renewcommand{\maketitle}{%
65 unmodified lines
70\ChTitleVar{\raggedleft \rm\Huge}7172\renewcommand\thepart{\@Roman\c@part}73\renewcommand\part{%74 \pagestyle{empty}75 \if@noskipsec \leavevmode \fi76 \cleardoublepage77 \vspace*{8cm}%77 \vspace*{6cm}%78 \@afterindentfalse79 \secdef\@part\@spart}8081\def\@part[#1]#2{%
2 unmodified lines
84 \addcontentsline{toc}{part}{\thepart\hspace{1em}#1}%85 \else86 \addcontentsline{toc}{part}{#1}%87 \fi88 {\parindent \z@ \center88 {\parindent \z@ %\center89 \interlinepenalty \@M90 \normalfont91 \ifnum \c@secnumdepth >\m@ne92 \rm\Large \partname~\thepart
4 unmodified lines
97 \nobreak98 \vskip 8ex99 \@afterheading}100\def\@spart#1{%101 {\parindent \z@ \center101 {\parindent \z@ %\center102 \interlinepenalty \@M103 \normalfont104 \huge \bfseries #1\par}%105 \nobreak
13 unmodified lines
modified:docs/index.rst+1 added-42 removed
25 unmodified lines
2627.. _Jinja2: http://jinja.pocoo.org/2/28.. _Werkzeug: http://werkzeug.pocoo.org/2930User's Guide31------------3233This part of the documentation is written text and should give you an idea34how to work with Flask. It's a series of step-by-step instructions for35web development.3637.. toctree::38 :maxdepth: 23940 foreword41 installation42 quickstart43 tutorial/index44 testing45 errorhandling46 patterns/index47 deploying/index48 becomingbig4950API Reference51-------------5253If you are looking for information on a specific function, class or54method, this part of the documentation is for you:5556.. toctree::57 :maxdepth: 25859 api6061Additional Notes62----------------6364Design notes, legal information and changelog are here for the interested:6566.. toctree::67 :maxdepth: 26869 design70 license71 changelog30.. include:: contents.rst.inc
modified:docs/latexindex.rst+1 added-33 removed
1 unmodified line
23Flask Documentation4===================56User's Guide7------------89.. toctree::10 :maxdepth: 31112 foreword13 installation14 quickstart15 tutorial/index16 testing17 errorhandling18 patterns/index19 deploying/index20 becomingbig2122API Reference23-------------2425.. toctree::26 :maxdepth: 32728 api2930Additional Notes31----------------3233.. toctree::34 :maxdepth: 33536 design37 license38 changelog6.. include:: contents.rst.inc
added:docs/shell.rst+110 added
1Working with the Shell2======================34.. versionadded:: 0.556One of the reasons everybody loves Python is the interactive shell. It7basically allows you to execute Python commands in real time and8immediately get results back. Flask itself does not come with an9interactive shell, because it does not require any specific setup upfront,10just import your application and start playing around.1112There are however some handy helpers to make playing around in the shell a13more pleasant experience. The main issue with interactive console14sessions is that you're not triggering a request like a browser does which15means that :data:`~flask.g`, :data:`~flask.request` and others are not16available. But the code you want to test might depend on them, so what17can you do?1819This is where some helper functions come in handy. Keep in mind however20that these functions are not only there for interactive shell usage, but21also for unittesting and other situations that require a faked request22context.2324Diving into Context Locals25--------------------------2627Say you have a utility function that returns the URL the user should be28redirected to. Imagine it would always redirect to the URL's ``next``29parameter or the HTTP referrer or the index page::3031 from flask import request, url_for3233 def redirect_url():34 return request.args.get('next') or \35 request.referrer or \36 url_for('index')3738As you can see, it accesses the request object. If you try to run this39from a plain Python shell, this is the exception you will see:4041>>> redirect_url()42Traceback (most recent call last):43 File "<stdin>", line 1, in <module>44AttributeError: 'NoneType' object has no attribute 'request'4546That makes a lot of sense because we currently do not have a request we47could access. So we have to make a request and bind it to the current48context. The :attr:`~flask.Flask.test_request_context` method can create49us a request context:5051>>> ctx = app.test_request_context('/?next=http://example.com/')5253This context can be used in two ways. Either with the `with` statement54(which unfortunately is not very handy for shell sessions). The55alternative way is to call the `push` and `pop` methods:5657>>> ctx.push()5859From that point onwards you can work with the request object:6061>>> redirect_url()62u'http://example.com/'6364Until you call `pop`:6566>>> ctx.pop()67>>> redirect_url()68Traceback (most recent call last):69 File "<stdin>", line 1, in <module>70AttributeError: 'NoneType' object has no attribute 'request'717273Firing Before/After Request74---------------------------7576By just creating a request context, you still don't have run the code that77is normally run before a request. This probably results in your database78being unavailable, the current user not being stored on the79:data:`~flask.g` object etc.8081This however can easily be done yourself. Just call82:meth:`~flask.Flask.preprocess_request`:8384>>> ctx = app.test_request_context()85>>> ctx.push()86>>> app.preprocess_request()8788Keep in mind that the :meth:`~flask.Flask.preprocess_request` function89might return a response object, in that case just ignore it.9091To shutdown a request, you need to trick a bit before the after request92functions (triggered by :meth:`~flask.Flask.process_response`) operate on93a response object:9495>>> app.process_response(app.response_class())96<Response 0 bytes [200 OK]>97>>> ctx.pop()9899100Further Improving the Shell Experience101--------------------------------------102103If you like the idea of experimenting in a shell, create yourself a module104with stuff you want to star import into your interactive session. There105you could also define some more helper methods for common things such as106initializing the database, dropping tables etc.107108Just put them into a module (like `shelltools` and import from there):109110>>> from shelltools import *
modified:tests/flask_tests.py+17 added
51 unmodified lines
52 assert index() == 'Hello World!'53 with app.test_request_context('/meh'):54 assert meh() == 'http://localhost/meh'5556 def test_manual_context_binding(self):57 app = flask.Flask(__name__)58 @app.route('/')59 def index():60 return 'Hello %s!' % flask.request.args['name']6162 ctx = app.test_request_context('/?name=World')63 ctx.push()64 assert index() == 'Hello World!'65 ctx.pop()66 try:67 index()68 except AttributeError:69 pass70 else:71 assert 0, 'expected runtime error'727374class BasicFunctionalityTestCase(unittest.TestCase):7576 def test_request_dispatching(self):77 app = flask.Flask(__name__)
630 unmodified lines
modified:CHANGES+4 added
11 unmodified lines
12- the application now configures a :class:`logging.Handler` and will13 log request handling exceptions to that logger when not in debug14 mode. This makes it possible to receive mails on server errors15 for example.16- added support for context binding that does not require the use of17 the with statement for playing in the console.18- the request context is now available within the with statement making19 it possible to further push the request context or pop it.2021Version 0.222-----------23
21 unmodified lines
modified:flask.py+35 added-2 removed
145 unmodified lines
146 self.url_adapter.match()147 except HTTPException, e:148 self.request.routing_exception = e149150 def __enter__(self):150 def push(self):151 """Binds the request context."""152 _request_ctx_stack.push(self)153154 def pop(self):155 """Pops the request context."""156 _request_ctx_stack.pop()157158 def __enter__(self):159 self.push()160 return self161162 def __exit__(self, exc_type, exc_value, tb):163 # do not pop the request stack if we are in debug mode and an164 # exception happened. This will allow the debugger to still165 # access the request object in the interactive shell.166 if tb is None or not self.app.debug:158 _request_ctx_stack.pop()167 self.pop()168169170def url_for(endpoint, **values):171 """Generates a URL to the given endpoint with the method provided.
1038 unmodified lines
12101211 with app.request_context(environ):1212 do_something_with(request)12131214 The object returned can also be used without the `with` statement1215 which is useful for working in the shell. The example above is1216 doing exactly the same as this code::12171218 ctx = app.request_context(environ)1219 ctx.push()1220 try:1221 do_something_with(request)1222 finally:1223 ctx.pop()12241225 The big advantage of this approach is that you can use it without1226 the try/finally statement in a shell for interactive testing:12271228 >>> ctx = app.test_request_context()1229 >>> ctx.bind()1230 >>> request.path1231 u'/'1232 >>> ctx.unbind()12331234 .. versionchanged:: 0.51235 Added support for non-with statement usage and `with` statement1236 is now passed the ctx object.12371238 :param environ: a WSGI environment1239 """1240 return _RequestContext(self, environ)1241
23 unmodified lines