i have been working with django to make an interactive web page. But when i try to make a Http request to a django view. It throws that error, even though i have the exact same code above and that works just fine. Here is my Python code:
def test(request):
default = {"Error" : "Could not make request"}
name = request.GET.get('showname')
token = getToken()
showJs = searchShowId(name, token)
if showJs.get('Error'):
try:
token = refreshToken(token)
showJs = searchShowId(name, token)
return JsonResponse(showJs)
except KeyError as error:
token = login()
showJs = searchShowId(name, token)
return JsonResponse(showJs)
else:
return JsonResponse(showJs)
def image(request):
default = {"Error" : "Could not make request"}
id = request.GET.get('id')
return JsonResponse(image(id))
this is the full error:
Traceback:
File "C:\Users\\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner
35. response = get_response(request)
File "C:\Users\\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "C:\Users\\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "E:\Documentos\Programming\DjangoProjects\mediaD\mediaDe\views.py" in image
33. return JsonResponse(image(id))
File "E:\Documentos\Programming\DjangoProjects\mediaD\mediaDe\views.py" in image
32. id = request.GET.get('id')
Exception Type: AttributeError at /image/
Exception Value: 'str' object has no attribute 'GET'
Javascript Code:
function search() {
console.log('Function Called')
var showName = document.getElementById('showName');
console.log(showName.value);
var name = stringToPost(showName.value);
$.ajax({
type: "GET",
url: "/request/",
data: {
showname: showName.value
},
success: function (dato) {
dato = dato['data'];
for (var i = 0; i < dato.length; i++) {
$.ajax({
type: "GET",
url: "/image/",
data: {
id : dato[i]['id']
},
success: function (datax) {
console.log(datax);
},
});
}
},
});
Like i already said, the test function works perfectly, but the image one doesnt. What could it be?
That's because in your image function, you return image(id) which calls the same function, but this time with id instead of a request object.
Try naming the 2 things differently, e.g. you can rename the view function to image_view.
Related
I am working on a project that takes signups from a Django form and transfers them to a website, the info is mainly the data ( Name, surname, email...) and some extra-information (tags).
One of the scripts give me the following error in the cronjob_logs;
Traceback (most recent call last): File
"/usr/local/lib/python2.7/dist-packages/django_cron/management/commands/runcrons.py",
line 71, in run_cron_with_cache_check manager.run(force) File
"/usr/local/lib/python2.7/dist-packages/django_cron/init.py", line
215, in run self.msg = self.cron_job.do() File
"/home/django/django_project/ogx/cron.py", line 31, in do ep_id =
get_ep_id(ep.email) File
"/home/django/django_project/ogx/graph_helper.py", line 75, in
get_ep_id ''', {"query": email}) File
"/usr/local/lib/python2.7/dist-packages/graphqlclient/client.py", line
11, in execute return self._send(query, variables) File
"/usr/local/lib/python2.7/dist-packages/graphqlclient/client.py", line
34, in _send raise e HTTPError: HTTP Error 500: Internal Server Error
The script was working normally some time ago, as for the graph_helper.py it is as follows;
def get_ep_id(email):
client = GraphQLClient(
'*this part I took off for confidentiality*')
result = client.execute('''
query Myquery($query: String!){
allPeople(q:$query)
{
data
{
id
full_name
}
}
}
''', {"query": email})
data = json.loads(result)
if len(data['data']['allPeople']['data']) > 0:
return data['data']['allPeople']['data'][0]['id']
else:
return None
The cron.py in question is the following;
class FetchEPsIDs(CronJobBase):
RUN_EVERY_MINS = 30
schedule = Schedule(run_every_mins=RUN_EVERY_MINS)
code = 'ogx.FetchEPsIDs' # a unique code
def do(self):
eps_query = mc_ogx_app.objects.filter(ep_id__isnull=True)
for ep in eps_query:
ep_id = get_ep_id(ep.email)
ep.ep_id = ep_id
ep.save()
As for the second script;
It is meant to update data called tags taken from the form and sent to the website through the API, now the script itself executes properly with no issues but it does not do what it is supposed to; Here you have the Cron...
class UpdateEpsTags(CronJobBase):
RUN_EVERY_MINS = 30
schedule = Schedule(run_every_mins=RUN_EVERY_MINS)
code = 'ogx.UpdateEpsTags' # a unique code
def do(self):
access_token = 'taken out for confidentiality'
eps_query = mc_ogx_app.objects.filter(ep_id__isnull=False, tags_uploaded=False)
for ep in eps_query:
if len(str(ep.ep_id)) >= 2:
tags_list = []
if ep.country_pref is not None:
tags_list.append(ep.country_pref.tag_id)
if ep.career_pref is not None:
tags_list.append(ep.career_pref.tag_id)
first_tags_list = return_user_tag_list(ep)
tags_list = tags_list + first_tags_list
if ep.product_ogv:
tags_list.append([7])
if ep.product_oge:
tags_list.append([9])
if ep.product_ogt:
tags_list.append([8])
try:
update_ep_tags(int(ep.ep_id), tags_list, access_token,ep.chosen_ref)
ep.tags_uploaded = True
ep.save()
except:
ep.save()
Now for the graphQl query in the script, it goes as follows;
def update_ep_tags(person_id, tags_list, token,referral):
client = GraphQLClient(
'taken out for confidentiality')
result = client.execute('''
mutation Mymutation($persons: [Int]!, $tags: [Int]!,$id: ID!, $referral: String!){
bulkTagUpdateForPeople(person_ids:$persons, tag_list_ids:$tags)
{
id
full_name
tag_lists
{
id
name
}
}
updatePerson(id:$id , person:
{
referral_type:$referral
})
{
full_name
referral_type
programmes
{
short_name
}
}
}
''', {"persons": [person_id], "tags": tags_list, "id": person_id, "referral": referral})
return result
Now executing the query on GraphQl I get Nullability mismatch on variable $id and argument id (ID / ID!).
Tried checking the datatypes and also running the query on Insomnia to check if it works, it does work just fine, I do not seem to grasp where the error is coming from
Solved:
What I am basically trying to do is reference using an email, the email is no longer supported by the API and therefor the query just gives a runtime error.
Error:
TypeError: loadshortlink() got multiple values for argument 'shortlink'
My urls.py:
path('s/<str:shortlink>',views.loadshortlink, name="get_longlink")
views.py:
def loadshortlink(shortlink):
print("Translating short link %s" % shortlink)
link = get_longlink(shortlink)
return render(request, 'shortlinks/openlong.html', {
'link': link
})
def get_longlink(shortlink):
print('Short link is %s' % shortlink)
links = Links.objects.filter(shortlink=shortlink)
if len(links)>1 or len(links)==1:
link = links[0].longlink
return link
else:
return 'No matched long links'
When I visit the url: http://127.0.0.1:8000/s/4nI
I get the error:
Internal Server Error: /s/4nI
Traceback (most recent call last):
File "/home/joel/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/joel/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/joel/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
TypeError: loadshortlink() got multiple values for argument 'shortlink'
Why is this happening?
First argument of view function should be request. You need to add it to loadshortlink:
def loadshortlink(request, shortlink):
print("Translating short link %s" % shortlink)
link = get_longlink(shortlink)
return render(request, 'shortlinks/openlong.html', {
'link': link
})
Actually, it is not able to handle the request because loadshortlink method is missing request parameter. Your code should be:
def loadshortlink(request, shortlink):
print("Translating short link %s" % shortlink)
link = get_longlink(shortlink)
return render(request, 'shortlinks/openlong.html', {
'link': link
})
def get_longlink(shortlink):
print('Short link is %s' % shortlink)
links = Links.objects.filter(shortlink=shortlink)
if len(links)>1 or len(links)==1:
link = links[0].longlink
return link
else:
return 'No matched long links'
I am trying to create and populate a playlist using the Spotify Web API. I am following this official reference, and I am using Python 3 with the requests module. Here is my code:
def spotify_write_playlist(auth, name, tracks, public=True):
ids = []
for track in tracks:
track_id = track.services['spotify']
if track_id: ids.append(track_id)
headers = {
"authorization":"Bearer " + auth.token,
"content-type":"application/json"
}
data = {
"name":name,
"public":public
}
r = makeRequest("https://api.spotify.com/v1/users/" + auth.username + "/playlists", "post", 201, json=data, headers=headers)
playlist_id = json.loads(r.content)['id']
data = {"uris":ids}
r = makeRequest("https://api.spotify.com/v1/users/" + auth.username + "/playlists/" + playlist_id + "/tracks", "post", 201, json=data, headers=headers)
return playlist_id
def makeRequest(url, method="get", expectedCode=200, *args, **kwargs):
while True:
r = requests.request(method, url, **kwargs)
if r.status_code == 429:
time.sleep(TMR_DELAY)
continue
elif r.status_code == expectedCode:
return r
else:
if "spotify.com" in url:
raise spotify.ApiError(r.status_code, expectedCode, r.content)
else:
raise youtube.ApiError(r.status_code, expectedCode, r.content)
The makeRequest function is a wrapper around requests.request that handles ratelimiting.
The above code when run with a bunch of sample tracks returns an error 400 at the first call of makeRequest, so my sample tracks can't be the issue as only the name and public variables are involved with that call.
The error response has no body, so no description of the error. This suggests I am probably missing something very obvious. Can anyone help?
The playlist creation request stopped erroring, and I have no idea why. I must of changed whatever was wrong when trying to diagnose the problem. I thought it was trying to create a playlist of the same name but spotify allows duplicate playlists. Maybe something was wrong with the token or token object I was using. Sorry.
However, I also found another issue when the previous one was cleared: the when adding to tracks you specify the track uri (spotify:track:abcdef123) not just the track id (abcdef123). I have revised spotify_write_playlists below:
def spotify_write_playlist(auth, name, tracks, public=True):
ids = []
for track in tracks:
track_id = track.services['spotify']
if track_id: ids.append("spotify:track:"+track_id)
headers = {
"authorization":"Bearer " + auth.token,
"content-type":"application/json"
}
data = {
"name":name,
"public":public
}
r = makeRequest("https://api.spotify.com/v1/users/" + auth.username + "/playlists", "post", 201, json=data, headers=headers)
playlist_id = json.loads(r.content)['id']
data = {"uris":ids}
r = makeRequest("https://api.spotify.com/v1/users/" + auth.username + "/playlists/" + playlist_id + "/tracks", "post", 201, json=data, headers=headers)
return playlist_id
I'm getting an uncaught syntax error: unexpected string the chrome console when running ajax where I am trying to add a row to the bottom of a html table with the saved data returned with json. I really can't spot it....
function create_person() {
console.log("create person is working!")
$.ajax({
url : "{% url 'tande:create_person' %}",
type: "POST",
data: { first_name : $('#person-first-name').val(), surname : $('#person-surname').val(), email : $('#person-email').val(), coach_id : $('#person-coach-id').val(), is_coach : $('#person-is-coach').val(), position : $('#person-position').val(), contract_type : $('#person-contract').val()},
success : function(json) {
$('#person-first-name').val('');
$('#person-surname').val('');
$('#person-email').val('');
$('#person-coach-id').val('');
$('#person-is-coach').val('');
$('#person-position').val('');
$('#person-contract').val('');
console.log(json);
// ERROR OCCURS ON FOLLOWING LINE
var html = '<tr><td>'+json.personid+'</td><td>'+json.personfirstname+' '+json.personsurname'</td><td>'+json.personposition+'</td><td>'+json.personcontract+'</td><td>'+json.personemail+'</td><td>'+json.personcoachid+'</td></tr>';
console.log("success");
$('div#talk').html(html);
console.log(html)
},
error : function(xhr,errmsg,err) {
// $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
// " <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log("uh oh");
}
});
};
The data is saved successfully and the json object is returned to the console, I just can't display it.
def create_person(request):
if request.method == "POST":
print "request post data in view"
firstname = request.POST.get('first_name')
print firstname
lastname = request.POST.get('surname')
emailadd = request.POST.get('email')
coachid = request.POST.get('coach_id')
isacoach = request.POST.get('is_coach')
positionheld = request.POST.get('position')
contracttype = request.POST.get('contract_type')
response_data = {}
starfruit = Person(first_name=firstname, surname=lastname, email=emailadd, coach_id=coachid, assign_as_coach=isacoach, position=positionheld, contract_type=contracttype)
starfruit.save()
response_data['personfirstname'] = starfruit.first_name
response_data['personsurname'] = starfruit.surname
response_data['personemail'] = starfruit.email
response_data['personcoachid'] = starfruit.coach_id
response_data['personiscoach'] = starfruit.assign_as_coach
response_data['personposition'] = starfruit.position
response_data['personcontract'] = starfruit.contract_type
response_data['personid'] = starfruit.id
# response_data = {
# ''
# }
print response_data
return JsonResponse(response_data)
else:
print "no post request in view"
return JsonResponse(response_data)
The error I'm getting in the console is just as follows:
(index):845 Uncaught SyntaxError: Unexpected string
and it refers to the line I've highlighted above
var html = '<tr><td>'+json.personid+'</td><td>'+json.personfirstname+' '+json.personsurname'</td><td>'+json.personposition+'</td><td>'+json.personcontract+'</td><td>'+json.personemail+'</td><td>'+json.personcoachid+'</td></tr>';
I'm unsure how else to approach this...
You're missing a + between json.personsurname and the following '</td><td>'.
Generally it's a really bad idea to build up HTML like that; this sort of thing is easy to miss.
I don't want to be a bother, and I probably shouldn't be trying to even manipulate a programming language I know nothing about. But the deployment method this presents is too irresistible not to use. Basically urbackup has this script designed to automatically pull a downloader for a specific computer using its WMI %ComputerName% property. The issue I seem to be having is related to JSON not being able to authenticate with server any more after Python 3.4. I honestly know very little about Python, and if it is too complex for me to fix or would require more work than necessary I understand that, I just figured maybe its a simpler error that can be corrected by someone with a bit of know how.
import http.client as http
import json
from urllib.parse import urlparse
from urllib.parse import urlencode
from base64 import b64encode
import hashlib
import socket
import shutil
import os
#############################
# Settings. Please edit.
#############################
#Your server URL
server_url = 'intentionallyremoved.com'
server_basic_username='intentionallyremoved'
server_basic_password='intentionallyremoved'
#user needs following rights
# "settings": "all"
# "status": "some"
# "add_client": "all"
server_username='intentionallyremoved'
server_password='intentionallyremoved'
#############################
# Global script variables.
# Please do not modify.
#############################
session=""
def get_response(action, params):
global server_url;
global server_basic_username;
global server_basic_password;
global session;
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=UTF-8'
}
if('server_basic_username' in globals() and len(server_basic_username)>0):
userAndPass = b64encode(str.encode(server_basic_username+":"+server_basic_password)).decode("ascii")
headers['Authorization'] = 'Basic %s' % userAndPass
curr_server_url=server_url+"?"+urlencode({"a": action});
if(len(session)>0):
params["ses"]=session
curr_server_url+="&"+urlencode(params);
target = urlparse(curr_server_url)
method = 'GET'
body = ''
if(target.scheme=='http'):
h = http.HTTPConnection(target.hostname, target.port)
elif(target.scheme=='https'):
h = http.HTTPSConnection(target.hostname, target.port)
else:
print('Unkown scheme: '+target.scheme)
raise Exception("Unkown scheme: "+target.scheme)
h.request(
method,
target.path+"?"+target.query,
body,
headers)
return h.getresponse();
def get_json(action, params = {}):
response = get_response(action, params)
if(response.status != 200):
return ""
data = response.readall();
response.close()
return json.loads(data.decode('utf8'))
def download_file(action, outputfn, params):
response = get_response(action, params);
if(response.status!=200):
return False
with open(outputfn, 'wb') as outputf:
shutil.copyfileobj(response, outputf)
return True
def md5(s):
return hashlib.md5(s.encode()).hexdigest()
print("Logging in...")
salt = get_json("salt", {"username": server_username})
if( not ('ses' in salt) ):
print('Username does not exist')
exit(1)
session = salt["ses"];
if( 'salt' in salt ):
password_md5 = md5(salt["rnd"]+md5(salt["salt"]+server_password));
login = get_json("login", { "username": server_username,
"password": password_md5 })
if('success' not in login or not login['success']):
print('Error during login. Password wrong?')
exit(1)
print("Creating client "+socket.gethostname()+"...")
status = get_json("status", { "clientname": socket.gethostname()})
for client in status["client_downloads"]:
if (client["name"] == socket.gethostname()):
print("Downloading Installer...")
if not download_file("download_client", "Client Installer.exe", {"clientid": client["id"]}):
print("Downloading client failed")
exit(1)
print("Sucessfully downloaded client")
os.startfile("Client Installer.exe")
exit(0)
print("Could not find client for download. No permission?")
exit(1)
The error it is outputting looks like this (I've removed applicable server names).
Logging in...
Traceback (most recent call last):
File "\\server\Share\Shortcuts\BackupScript\Script.py", line 110, in <module>
salt = get_json("salt", {"username": server_username})
File "\\server\Share\Shortcuts\BackupScript\Script.py", line 89, in get_json
return json.loads(data.decode('utf8'))
File "C:\Anaconda3\lib\json\__init__.py", line 318, in loads
return _default_decoder.decode(s)
File "C:\Anaconda3\lib\json\decoder.py", line 343, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Anaconda3\lib\json\decoder.py", line 361, in raw_decode
raise ValueError(errmsg("Expecting value", s, err.value)) from None
ValueError: Expecting value: line 1 column 1 (char 0)
>>>
I've tried using different things talking about using different JSON methods that don't involve the decode variable, and using json.dump instead, but they all seem to lead to different errors because I don't know which parts of the code correspond to the parts of the code I'd be changing. This is really just a quality of life tool, and isn't absolutely necessary. But it would be comforting to simply convert this into an MSI I could deploy instead of having to manually one by one go to each of our (over 100) computers and manually do this. Any help would be appreciated :).
Here is the log in javascript from the back end of the server.
g.login1=function ()
{
var username=I('username').value;
var password=I('password').value;
if( username.length==0 )
{
alert(trans("username_empty"));
I('username').focus();
return false;
}
if( password.length==0 )
{
alert(trans("password_empty"));
I('password').focus();
return false;
}
if(!startLoading()) return false;
new getJSON("salt", "username="+username, login2);
return false;
}
function login2(data)
{
if(data.error==0)
{
alert(trans("user_n_exist"));
stopLoading();
I('username').focus();
return;
}
if(data.ses)
g.session=data.ses;
var username=I('username').value;
var password=I('password').value;
var pwmd5=calcMD5(data.rnd+calcMD5(data.salt+password));
new getJSON("login", "username="+username+"&password="+pwmd5, login3);
}
function login3(data)
{
stopLoading();
if(data.error==2)
{
alert(trans("password_wrong"));
I('password').focus();
return;
}
g.allowed_nav_items = [];
if(data.status!="none")
{
g.allowed_nav_items.push(6);
}
if(data.progress!="none")
{
g.allowed_nav_items.push(5);
}
if(data.browse_backups!="none")
{
g.allowed_nav_items.push(4);
}
if(data.logs!="none")
{
g.allowed_nav_items.push(3);
}
if(data.graph!="none")
{
g.allowed_nav_items.push(2);
}
if(data.settings!="none")
{
g.allowed_nav_items.push(1);
}
build_main_nav();
show_status1();
}
Could you try changing line 86 to read
data = response.read()
I don't know what readall() is but it's not listed in the docs for the HTTPResponse object