MMakela MMakela - 7 months ago 17
Python Question

How to get request.user.id value to same function with API query with Python in Django

I'm pretty confused with classes and functions in Django, so I'm not sure, if I'm trying to do this right.

1) I have a function, where I do API query. I want to have API-token here from 2) (see below).

def API_search(request):
query = request.GET.get('query')
final_url = urllib2.Request('http://api.website.com', None, headers={'Content-Type':'application/json'})
base64string = base64.encodestring('%s:%s' % ('myusername', 'mypassword')).replace('\n', '')
final_url.add_header("Authorization", "Basic %s" % base64string)
json_obj = urllib2.urlopen(final_url)
readable_json = json.load(json_obj)
resultsOpen = []
for i in readable_json:
resultsOpen.append({
'subject': i['subject'],
})
return render(request, 'index/apiTest.html', {'objects_open': resultsOpen)


2) I have a class-based-function, where I do query to database and return API-token of current user. This only shows API-token on site now. I want it to be in API-query.

class UserDetail(DetailView):
model = User
def get_context_data(self, **kwargs):
context = super(UserDetail, self).get_context_data(**kwargs)
context['token_list'] = UserTokens.objects.values_list('apiToken', flat=True).get(pk=1)
return context


Both of these work on different templates, but I don't want it. I want to use the API-token variable context in the API-query. How I can do this?

edit: Added urls.py

from django.conf.urls import url
from index.views import UserDetail
from index import views

urlpatterns = [
url(r'^dbquery/$', UserDetail.as_view()),
url(r'^apitest/$', views.API_search),
]

Answer

Create a url definition in your urls.py which calls the API_search function. In your UserDetailView store this generated url inside an href and when the user clicks on it, call your API search function.

OR

If you want to call the API_Search directly from the UserDetailView call a HttpRedirectResponse to that url after generating the proper url.

EDIT: Based on the extra information provided, you can use this:

def API_search(request):
    user = request.user
    token = UserTokens.objects.values_list('apiToken', flat=True).get(pk=user.id)
    query = request.GET.get('query')
    final_url =  urllib2.Request('http://api.website.com', None, headers={'Content-Type':'application/json'})
    #use the token as you like
    base64string = base64.encodestring('%s:%s' % ('myusername', 'mypassword')).replace('\n', '')
    final_url.add_header("Authorization", "Basic %s" % base64string)   
    json_obj = urllib2.urlopen(final_url)
    readable_json = json.load(json_obj)
    resultsOpen = []
    for i in readable_json:
        resultsOpen.append({
            'subject': i['subject'],
            })
return render(request, 'index/apiTest.html', {'objects_open': resultsOpen)