How to print out request.body data in django? - django

Just working through the Django tutorials and playing around with stuff. Was going through the HttpResponse and HttpRequest docs and I'm just trying to print out data to see how things work.
However, when I try to print to console the request.body I get nothing back.
def detail(request, question_id):
current_question_selected = Question.objects.get(pk=question_id)
choices_for_question = current_question_selected.choice_set.all()
context = {"choices_for_question":choices_for_question, "current_question_selected":current_question_selected}
#print(request.META["REMOTE_USER"])
print(request.body)
return render(request, 'polls/detailtext.html', context)
This is what gets pritned to the screen, the letter 'b' with an empty string
[28/Jun/2022 10:59:56] "GET /polls/1/ HTTP/1.1" 200 456
b''
Not sure what i'm missing

The print displays an empty string because GET does not accept a body. Taken directly from the Mozilla Web APIs docs:
Note that a request using the GET or HEAD method cannot have a body and null is return in these cases.
If you want to pass data in a GET request, you need to pass them as parameters instead. Then, you can access the parameters using request.GET (HttpRequest.GET) or access them individually with request.GET.get('key').

Related

Tweepy location on Twitter API filter always throws 406 error

I'm using the following code (from django management commands) to listen to the Twitter stream - I've used the same code on a seperate command to track keywords successfully - I've branched this out to use location, and (apparently rightly) wanted to test this out without disrupting my existing analysis that's running.
I've followed the docs and have made sure the box is in Long/Lat format (in fact, I'm using the example long/lat from the Twitter docs now). It looks broadly the same as the question here, and I tried using their version of the code from the answer - same error. If I switch back to using 'track=...', the same code works, so it's a problem with the location filter.
Adding a print debug inside streaming.py in tweepy so I can see what's happening, I print out the self.parameters self.url and self.headers from _run, and get:
{'track': 't,w,i,t,t,e,r', 'delimited': 'length', 'locations': '-121.7500,36.8000,-122.7500,37.8000'}
/1.1/statuses/filter.json?delimited=length and
{'Content-type': 'application/x-www-form-urlencoded'}
respectively - seems to me to be missing the search for location in some way shape or form. I don't believe I'm/I'm obviously not the only one using tweepy location search, so think it's more likely a problem in my use of it than a bug in tweepy (I'm on 2.3.0), but my implementation looks right afaict.
My stream handling code is here:
consumer_key = 'stuff'
consumer_secret = 'stuff'
access_token='stuff'
access_token_secret_var='stuff'
import tweepy
import json
# This is the listener, resposible for receiving data
class StdOutListener(tweepy.StreamListener):
def on_data(self, data):
# Twitter returns data in JSON format - we need to decode it first
decoded = json.loads(data)
#print type(decoded), decoded
# Also, we convert UTF-8 to ASCII ignoring all bad characters sent by users
try:
user, created = read_user(decoded)
print "DEBUG USER", user, created
if decoded['lang'] == 'en':
tweet, created = read_tweet(decoded, user)
print "DEBUG TWEET", tweet, created
else:
pass
except KeyError,e:
print "Error on Key", e
pass
except DataError, e:
print "DataError", e
pass
#print user, created
print ''
return True
def on_error(self, status):
print status
l = StdOutListener()
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret_var)
stream = tweepy.Stream(auth, l)
#locations must be long, lat
stream.filter(locations=[-121.75,36.8,-122.75,37.8], track='twitter')
The issue here was the order of the coordinates.
Correct format is:
SouthWest Corner(Long, Lat), NorthEast Corner(Long, Lat). I had them transposed. :(
The streaming API doesn't allow to filter by location AND keyword simultaneously.
you must refer to this answer i had the same problem earlier
https://stackoverflow.com/a/22889470/4432830

how to use django object in session

I was wondering how i can check if a object is in session and depending on that, do something.
def login_character(request, character_name):
request.session['character'] = Character.objects.get(name=character_name)
return HttpResponseRedirect(reverse('index'))
some other function:
if request.session['character']:
print request.session['character'].name
else:
print "nothing to see here"
How i try it, i kepe getting back to a KeyError
session uses the standard Python dictionary interface, so you want either:
if 'character' in request.session:
print request.session['character'].name
else:
print "nothing to see here"
Or, in some cases, request.session.get('character') if you just want to have a default value if the key is not present.

json? in Django URL regex

This question might reveal a gaping hole in my knowledge of json queries, but I'm trying to get json data to display on a view with the following URL.
http://localhost:8000/structures/hydrants/json?id=%3D2/
Here's my URL regex:
url(r'^hydrants/json\\?id=(?P<hydrant_id>\d+)/$', views.hydrant_json, name='hydrant_json'),
and the view:
def hydrant_json(request, hydrant_id):
hydrant = get_object_or_404(Hydrant, pk=hydrant_id)
data = [hydrant.json()]
return HttpResponse(json.dumps(data), content_type='application/json')
Obviously, the question mark is throwing it off, because if I make the regex
url(r'^hydrants/json/id=(?P<hydrant_id>\d+)/$', views.hydrant_json, name='hydrant_json'),
then the following URL will work:
http://localhost:8000/structures/hydrants/json/id%3D2/
Thanks in advance!
If you want to send the data as GET parameters, you can simply do:
url(r'^hydrants/json/$', views.hydrant_json, name='hydrant_json'),
url(r'^hydrants/json/(?P<hydrant_id>\d+)/$', views.hydrant_json, name='hydrant_json_with_key'),
and views:
def hydrant_json(request, hydrant_id=None):
if not hydrant_id:
hydrant_id = request.GET.get('id')
if not hydrant_id: #if hydrant_id is not received for some reason, throw 404.
raise Http404
hydrant = get_object_or_404(Hydrant, pk=hydrant_id)
data = [hydrant.json()]
return HttpResponse(json.dumps(data), content_type='application/json')
Here, you are defining flexible ways of sending hydrant_id into the view.
By default, for a GET request, request.GET would have all the get parameters - example: ?id=123
Also, if you want to send hydrant_id as a part of the URL, You can just do
http://localhost:8000/structures/hydrants/json/302/
Please note, 3D2 would never get matched as a URL in the regex because your URL is looking for \d+ which is digits only.

Is django-lazysignup allow_lazy_user decorator calling the wrapped view twice?

I'm using "django-lazysignup 0.8" with Django 1.3.
When I do this:
The view
#allow_lazy_user
def page_edit(request):
if request.method == 'GET':
if is_lazy_user(request.user):
b2 = Page.objects.create(user=request.user)
print request.user.username
return render_to_response('page_editor.html',{'page':b2})
the console output shows that the view seems to be called twice (b2 called twice and creates the Page object twice, and the print statment prints twice)
Here is the output screen :
Output:
7707089a583a424caf0face130cb20 # this is the reult of print request.user.username
[12/Mar/2012 15:02:45] "GET /edit/ HTTP/1.1" 200 8368
7707089a583a424caf0face130cb20
[12/Mar/2012 15:02:46] "GET /edit/images/favicon.ico HTTP/1.1" 200 8368
I don't need this to happen, the view should be called once and create one Page object. Is there any solution?
I don't think this is related to Django-lazysignup.
If you look at the url for the second request:
/edit/images/favicon.ico
That looks to me like your browser trying to load the favicon for your website. That suggests you've used a relative path images/favicon.ico instead of an absolute path /images/favicon.ico.
It doesn't seem quite right that the favicon url has called the page_edit view. This suggests your url pattern is missing a $ to denote the end of string. You should change it to something like:
url('^edit/$', 'page_edit'),

Handling multiple sub-urls in Django's url.py file

In my djang urls pattern file, I'd like to hold a bunch of sub-url's but I don't want to make it ugly.
I have a file which handles all of my Ajax requests (it outputs different JSON files depending on the request it gets.
example (in my url.py):
in the form: (url, maps to)
(ajax/do_a, ajax.do_a)
ajax/do_b, ajax.do_b)
ajax/do_c, ajax.do_c)
ajax/do_d, ajax.do_d)
these are all sub-urls, eg.
mywebsite.com/ajax/do_a
mywebsite.com/ajax/do_b
etc.
Basically do_a,do_b,do_c,and do_d are all different request handlers sitting in the same same in the "ajax.py" file. I really don't want to be filling up my urls.py file with all of these urls for ajax requests. I was thinking of move this so that I only have
ajax/
in my url.py file and then somehow parse the ajax/ request url in my request handler (in the ajax.py file) so I can see what string came after the "ajax/". I'm not sure how to do this or if this would be a good idea to do this....Could anyone offer some advice? thanks :)
You could set up a dispatcher view for handling these. For example, in your urls.py:
(r'^ajax/do_(?P<do_token>(\d+))/$', 'do_dispatcher', {}, "di_dispatcher"),
Then, give yourself a view to handle it:
def do_a(request):
pass
def do_b(request):
pass
def do_c(request):
pass
DO_LOOKUP = {
'a' = do_a,
'b' = do_b,
'c' = do_c,
}
def do_dispatch(request, do_token):
do_func = DO_LOOKUP.get(do_token, None)
if do_func is None:
return HttpResponseNotFound("No do could be found for token '%s'!" % do_token)
else:
return do_func(request)