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
Provenance
- Commit
ef0dc18- Tree
367df61- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
9d98ad5
8 files changed+215 added−81 removed
added:docs/contents.rst.inc+43 added
1+User's Guide2+------------3+4+This part of the documentation is written text and should give you an idea5+how to work with Flask. It's a series of step-by-step instructions for6+web development.7+8+.. toctree::9+ :maxdepth: 210+11+ foreword12+ installation13+ quickstart14+ tutorial/index15+ testing16+ errorhandling17+ shell18+ patterns/index19+ deploying/index20+ becomingbig21+22+API Reference23+-------------24+25+If you are looking for information on a specific function, class or26+method, this part of the documentation is for you.27+28+.. toctree::29+ :maxdepth: 230+31+ api32+33+Additional Notes34+----------------35+36+Design notes, legal information and changelog are here for the interested.37+38+.. toctree::39+ :maxdepth: 240+41+ design42+ license43+ changelogmodified:docs/flaskstyle.sty+4 added-4 removed
1-\pagenumbering{arabic}1 \definecolor{TitleColor}{rgb}{0,0,0}2 \definecolor{InnerLinkColor}{rgb}{0,0,0}3 4 \renewcommand{\maketitle}{%65 unmodified lines70 \ChTitleVar{\raggedleft \rm\Huge}71 72 \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}80 81 \def\@part[#1]#2{%2 unmodified lines84 \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~\thepart4 unmodified lines97 \nobreak98 \vskip 8ex99 \@afterheading}100 \def\@spart#1{%101- {\parindent \z@ \center101+ {\parindent \z@ %\center102 \interlinepenalty \@M103 \normalfont104 \huge \bfseries #1\par}%105 \nobreak13 unmodified linesmodified:docs/index.rst+1 added-42 removed
25 unmodified lines26 27 .. _Jinja2: http://jinja.pocoo.org/2/28 .. _Werkzeug: http://werkzeug.pocoo.org/29 30-User's Guide31-------------32-33-This part of the documentation is written text and should give you an idea34-how to work with Flask. It's a series of step-by-step instructions for35-web development.36-37-.. toctree::38- :maxdepth: 239-40- foreword41- installation42- quickstart43- tutorial/index44- testing45- errorhandling46- patterns/index47- deploying/index48- becomingbig49-50-API Reference51--------------52-53-If you are looking for information on a specific function, class or54-method, this part of the documentation is for you:55-56-.. toctree::57- :maxdepth: 258-59- api60-61-Additional Notes62-----------------63-64-Design notes, legal information and changelog are here for the interested:65-66-.. toctree::67- :maxdepth: 268-69- design70- license71- changelog30+.. include:: contents.rst.incmodified:docs/latexindex.rst+1 added-33 removed
1 unmodified line2 3 Flask Documentation4 ===================5 6-User's Guide7-------------8-9-.. toctree::10- :maxdepth: 311-12- foreword13- installation14- quickstart15- tutorial/index16- testing17- errorhandling18- patterns/index19- deploying/index20- becomingbig21-22-API Reference23--------------24-25-.. toctree::26- :maxdepth: 327-28- api29-30-Additional Notes31-----------------32-33-.. toctree::34- :maxdepth: 335-36- design37- license38- changelog6+.. include:: contents.rst.incadded:docs/shell.rst+110 added
1+Working with the Shell2+======================3+4+.. versionadded:: 0.55+6+One of the reasons everybody loves Python is the interactive shell. It7+basically allows you to execute Python commands in real time and8+immediately get results back. Flask itself does not come with an9+interactive shell, because it does not require any specific setup upfront,10+just import your application and start playing around.11+12+There are however some handy helpers to make playing around in the shell a13+more pleasant experience. The main issue with interactive console14+sessions is that you're not triggering a request like a browser does which15+means that :data:`~flask.g`, :data:`~flask.request` and others are not16+available. But the code you want to test might depend on them, so what17+can you do?18+19+This is where some helper functions come in handy. Keep in mind however20+that these functions are not only there for interactive shell usage, but21+also for unittesting and other situations that require a faked request22+context.23+24+Diving into Context Locals25+--------------------------26+27+Say you have a utility function that returns the URL the user should be28+redirected to. Imagine it would always redirect to the URL's ``next``29+parameter or the HTTP referrer or the index page::30+31+ from flask import request, url_for32+33+ def redirect_url():34+ return request.args.get('next') or \35+ request.referrer or \36+ url_for('index')37+38+As you can see, it accesses the request object. If you try to run this39+from a plain Python shell, this is the exception you will see:40+41+>>> redirect_url()42+Traceback (most recent call last):43+ File "<stdin>", line 1, in <module>44+AttributeError: 'NoneType' object has no attribute 'request'45+46+That makes a lot of sense because we currently do not have a request we47+could access. So we have to make a request and bind it to the current48+context. The :attr:`~flask.Flask.test_request_context` method can create49+us a request context:50+51+>>> ctx = app.test_request_context('/?next=http://example.com/')52+53+This context can be used in two ways. Either with the `with` statement54+(which unfortunately is not very handy for shell sessions). The55+alternative way is to call the `push` and `pop` methods:56+57+>>> ctx.push()58+59+From that point onwards you can work with the request object:60+61+>>> redirect_url()62+u'http://example.com/'63+64+Until you call `pop`:65+66+>>> ctx.pop()67+>>> redirect_url()68+Traceback (most recent call last):69+ File "<stdin>", line 1, in <module>70+AttributeError: 'NoneType' object has no attribute 'request'71+72+73+Firing Before/After Request74+---------------------------75+76+By just creating a request context, you still don't have run the code that77+is normally run before a request. This probably results in your database78+being unavailable, the current user not being stored on the79+:data:`~flask.g` object etc.80+81+This however can easily be done yourself. Just call82+:meth:`~flask.Flask.preprocess_request`:83+84+>>> ctx = app.test_request_context()85+>>> ctx.push()86+>>> app.preprocess_request()87+88+Keep in mind that the :meth:`~flask.Flask.preprocess_request` function89+might return a response object, in that case just ignore it.90+91+To shutdown a request, you need to trick a bit before the after request92+functions (triggered by :meth:`~flask.Flask.process_response`) operate on93+a response object:94+95+>>> app.process_response(app.response_class())96+<Response 0 bytes [200 OK]>97+>>> ctx.pop()98+99+100+Further Improving the Shell Experience101+--------------------------------------102+103+If you like the idea of experimenting in a shell, create yourself a module104+with stuff you want to star import into your interactive session. There105+you could also define some more helper methods for common things such as106+initializing the database, dropping tables etc.107+108+Just put them into a module (like `shelltools` and import from there):109+110+>>> from shelltools import *modified:tests/flask_tests.py+17 added
51 unmodified lines52 assert index() == 'Hello World!'53 with app.test_request_context('/meh'):54 assert meh() == 'http://localhost/meh'55 56+ 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']61 62+ 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'72+73+74 class BasicFunctionalityTestCase(unittest.TestCase):75 76 def test_request_dispatching(self):77 app = flask.Flask(__name__)630 unmodified linesmodified:CHANGES+4 added
11 unmodified lines12 - 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.20 21 Version 0.222 -----------23 21 unmodified linesmodified:flask.py+35 added-2 removed
145 unmodified lines146 self.url_adapter.match()147 except HTTPException, e:148 self.request.routing_exception = e149 150- def __enter__(self):150+ def push(self):151+ """Binds the request context."""152 _request_ctx_stack.push(self)153 154+ def pop(self):155+ """Pops the request context."""156+ _request_ctx_stack.pop()157+158+ def __enter__(self):159+ self.push()160+ return self161+162 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()168 169 170 def url_for(endpoint, **values):171 """Generates a URL to the given endpoint with the method provided.1038 unmodified lines1210 1211 with app.request_context(environ):1212 do_something_with(request)1213 1214+ 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::1217+1218+ ctx = app.request_context(environ)1219+ ctx.push()1220+ try:1221+ do_something_with(request)1222+ finally:1223+ ctx.pop()1224+1225+ The big advantage of this approach is that you can use it without1226+ the try/finally statement in a shell for interactive testing:1227+1228+ >>> ctx = app.test_request_context()1229+ >>> ctx.bind()1230+ >>> request.path1231+ u'/'1232+ >>> ctx.unbind()1233+1234+ .. versionchanged:: 0.51235+ Added support for non-with statement usage and `with` statement1236+ is now passed the ctx object.1237+1238 :param environ: a WSGI environment1239 """1240 return _RequestContext(self, environ)1241 23 unmodified lines