Wizard
Wizard

Reputation: 22113

Retrieve the source code of request object

For the curiosity, I test within a CBV by adding print statement:

def post(self, request, block_id):
    sf = inspect.getsourcefile(request)
    code = inspect.getsouce(request)

However, I got the error:

 TypeError: <WSGIRequest: POST '/article/create/1'> is not a module, class, method, function, traceback, frame, or code object.

Request is an object but it prompts that none of a module, class, method, function, traceback, frame, or code object.

How does this happen?

Upvotes: 0

Views: 152

Answers (1)

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

Quite simply: inspect.getsource() and inspect.getsourcefile() check their first argument's type and raise a TypeError if it's neither a module (instance of the module class), a class (instance of the type class), method (instance of the instancemethod type), function (instance of the function class), traceback (instance of the traceback type), etc etc... FWIW those limitations are clearly documented:

>>> import inspect
>>> help(inspect.getsource)

Help on function getsource in module inspect:

getsource(object)
    Return the text of the source code for an object.

    The argument may be a module, class, method, function, traceback, frame,
    or code object.  The source code is returned as a single string.  An
    IOError is raised if the source code cannot be retrieved.

Your request object is none of those, so inspect refuses it by raising a TypeError, which makes senses since it only can get the source code for something that does have a source code component.

If you want the source code for the WSGRequest class, you have to pass the class itself:

def post(self, request, block_id):
    sf = inspect.getsourcefile(type(request))
    code = inspect.getsouce(type(request))

Upvotes: 1

Related Questions