使用Shell

New in version 0.3.

One of the reasons everybody loves Python is the interactive shell. It basically allows you to execute Python commands in real time and immediately get results back. Flask itself does not come with an interactive shell, because it does not require any specific setup upfront, just import your application and start playing around.

然而这里有一些易于获得的助手,可以帮助您在 Shell 遨游时获得更为愉悦的体验。The main issue with interactive console sessions is that you’re not triggering a request like a browser does which means that g, request and others are not available. But the code you want to test might depend on them, so what can you do?

This is where some helper functions come in handy. Keep in mind however that these functions are not only there for interactive shell usage, but also for unittesting and other situations that require a faked request context.

Generally it’s recommended that you read the The Request Context chapter of the documentation first.

命令行接口

从Flask 0.11开始, 使用shell的推荐方式是Flask shell命令,它自动为你完成很多工作。例如,shell自动初始化并带有一个加载好的应用上下文。

详细信息请参阅命令行接口

创建一个请求上下文

The easiest way to create a proper request context from the shell is by using the test_request_context method which creates us a RequestContext:

>>> ctx = app.test_request_context()

一般来说,你可以使用with语句来激活这个请求对象, 但是在shell中,调用push()方法和pop()方法会更简单:

>>> ctx.push()

From that point onwards you can work with the request object until you call pop:

>>> ctx.pop()

激发请求发送前后的调用

By just creating a request context, you still don’t have run the code that is normally run before a request. This might result in your database being unavailable if you are connecting to the database in a before-request callback or the current user not being stored on the g object etc.

然而,你自己就可以很容易地完成这件事。只需调用preprocess_request()

>>> ctx = app.test_request_context()
>>> ctx.push()
>>> app.preprocess_request()

Keep in mind that the preprocess_request() function might return a response object, in that case just ignore it.

To shutdown a request, you need to trick a bit before the after request functions (triggered by process_response()) operate on a response object:

>>> app.process_response(app.response_class())
<Response 0 bytes [200 OK]>
>>> ctx.pop()

The functions registered as teardown_request() are automatically called when the context is popped. So this is the perfect place to automatically tear down resources that were needed by the request context (such as database connections).

一步提升 Shell 使用体验

If you like the idea of experimenting in a shell, create yourself a module with stuff you want to star import into your interactive session. There you could also define some more helper methods for common things such as initializing the database, dropping tables etc.

Just put them into a module (like shelltools) and import from there:

>>> from shelltools import *