I'm building a custom function to pull the data from mongodb
and want to see the data what it is look like before the manipulation.
say I have a function to request the data from mongodb
Here is how my models.py looks like
from bson import json_util
from django.db import models
from django.http import JsonResponse
from pymongo import MongoClient
from bson.json_util import dumps
from bson.json_util import loads
import json
import pymongo
def data_pull(request):
request_data = request.POST.get('Hello', None)
if __name__ == "__main__":
data_pull(request)
to run the models.py I do python models.py
from the command line but getting this error
NameError: name 'request' is not defined
So basically I want to test this data_pull
function from models.py and see that what the data looks like. How can I feed this request
call into the function and see the output from commandline?
CodePudding user response:
This part of your code seems strange:
if __name__ == "__main__":
data_pull(request)
Usually, if you pass a request
as argument, you would call the function data_pull()
from a view and pass the request as an argument in the function call.
You cannot just use if __name__ == "__main__":
and expect a request object to appear, you need to create one yourself or use the request object that is created by the views (the django engine takes care of if for the most part).
More info in the docs: https://docs.djangoproject.com/en/3.2/ref/request-response/#quick-overview
EDIT: if you want a HttpRequest
object, that usually means that you want the data that is sent from a webbrowser (the data that the django engine places inside request.GET
and request.POST
and others). That means that you should probably call you function data_pull()
from a view.
For example this code in your 'views' file (code from https://docs.djangoproject.com/en/3.2/topics/class-based-views/intro/#using-class-based-views):
from django.http import HttpResponse
from django.views import View
# since you function is declared in 'models', we import it here
from .models import data_pull
class MyView(View):
def get(self, request):
# call the function passing request as argument
data_pull(request)
return HttpResponse('result')