django management commands and user
i use the django cu开发者_运维知识库stom management/commands quite a bit. i would like to provide access to my views via some of these scripts; however i'm in a quandary about how to do this for authenticated users. i'm not really using the middleware libraries, so all i need is access to the request.META['REMOTE_USER']; is there a recommended why i can fake this? eg,
def poll_view( request ):
user = None
if 'META' in request and 'REMOTE_USER' in request.META:
user = request.META['REMOTE_USER']
if not user == None:
do_something()
and in my management/command script i have:
class Command(BaseCommand):
def handle(self, *args, **kwargs):
req = ???
poll_view( req )
Perhaps you can refactor your view to extract just the functionality you need and put it in a helper module. That way, you can call this function in both the view and the management command.
Example:
-----------in a file named somewhere.py----------
def do_this():
#do these
pass
------------in your view-------------------------
from somewhere import do_this
def my_view(request):
user = request.META.get('REMOTE_USER', None)
if user:
do_this()
-----------in your management command----------
from somewhere import do_this
class my_command(...):
def handle(self, args*, kwargs**):
do_this()
Well the management commands are just functions, so instead of calling the view from the command, call the command from the view and pass the request as a parameter
views.py
from managment import Command
def some_view(request):
Command._private_function(request=request)
commands.py
class Command(...):
def _private_function(request=None):
if request:
// do action with request details (i.e. coming from a view)
else:
// do action without (i.e. coming from command line)
def handle(self,...):
_private_function()
This allows you to perform the main logic of your admin-command from either the command line, or from a view (i.e. the web). You need to be careful though and be sure that you actually want the person with access to the view (authenticated user) to perform whatever action it is
精彩评论