TypeError: can only concatenate str (not "DeferredAttribute") to str - django

I am wondering anyone can help me in one of the thing I cannot get my around it and really bothering as I spent last two on it but couldnt make it.
Basically, I am building an App (Django Python) to restore the information regarding all the network device e.g hostname, IP Address, S/N, Rack info etc. but I also to enable few options like Add, Edit, Delete and Connect next to device entery. I was able to create all the options except Connect option where I am completely stuck, I am trying to query database to get the IP address information and then using Popen module to open a putty window with the ssh to that IP Address device related, I tried everything I could but nothing worked, thereofrore, asking your help if you have any idea about this ? or any other alternative method for a user when he click on connect the putty or similar app will open and he just put the login credentials and get into the device.
I am sharing my code here, let me know if I am doing something wrong.
on the show all device page, i have this code, show.html
<td>Connect</td>
<!--<td>Connect</td>-->
I tried both ways, with id and ip address entry in the database
on view.py
def connect(request, ip_address):
hostlist_ip = HostList.ip_address
print(hostlist_ip)
Popen("putty.exe" + hostlist_ip)
return redirect('/show')
and in the url.py
path('connect/<str:ip_address>', views.connect),
or
path('connect/<str:ip_address>', views.connect),
Since I am also printing the the output on the terminal I notice that it is not returning the actually IP address but return this;
<django.db.models.query_utils.DeferredAttribute object at 0x04B77C50>
and on the web I receiving this error
TypeError at /connect/10.10.32.10
can only concatenate str (not "DeferredAttribute") to str
Request Method: GET
Request URL: http://localhost:8000/connect/10.10.32.10
Django Version: 2.2.3
Exception Type: TypeError
Exception Value:
can only concatenate str (not "DeferredAttribute") to str
let me know if you can help.
Just a F.Y.I I already tested the Popen via python but since we not getting the actual IP address from the database I am seeing this and I am a complete newbie with html/css and Djano, however I have some basic knowledge of python, so please ignore my any stupid comments in the post.
Many thanks

ahh I cannot believe I spend two day to troubleshoot this and just changed the name from ip_address to ip_add and it is working now :) i think as I mentioned above in the comment, it probably confusing with the built in module
here is simple solution:
views.py
def connect(request, ip_add):
import os
from subprocess import Popen
Popen("powershell putty.exe " + ip_add)
return redirect('/show')
url.py
path('connect/<str:ip_add>', views.connect),
I may have to find out a way if user is using the mac or linux, how I am going to change this powershell to something else. but anyhow it is working for windows
thanks all for the responses.

Related

Problems with MSF4J and #MatrixParam

Folks, I have found what seems to be a problem with / (bug in ?) MSF4J as including an #MatrixParam annotated variable in a URI causes the affected (micro)service to either 'hang' indefinitely, or if accessed via a browser, to give a "404 Not Found" message for the path/endpoint, even when correct.
Here is a code fragment that illustrates the problem - it compiles ok (eclipse/maven) and deploys without errors using microservicesrunner() in the usual way.
package org.test.service;
import javax.ws.rs.GET;
import javax.ws.rs.MatrixParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
#Path("books")
public class MPTest { // MatrixParam Test
#GET
#Produces(MediaType.TEXT_PLAIN)
#Path("/query")
// method to respond to 'GET' requests
public Response getListOfBooks(#MatrixParam("Author") String author) {
// do something in here to get book data from DB and sort by titles
List<String> titles = .......;
return Response.status(200) .entity("List of Books by " +author+ "ordered by title " + titles).build();
}
}
With this code fragment, accessing the URL "(host:8080)/books/query;Author=MickeyMouse" should cause a list of books by that author to be retrieved from the DB (I have omitted the actual code that does so for clarity, as it is not relevant to this post).
However, it does not get there, so that code isnt executed. As far as I can tell with a debugger, no #MatricParam value is retrieved - it remains null until the process times out. Things like curl and wget just hang until they time out, and from a browser, the best I can get is a 404 not found error for the URI, even though it is valid.
However, if I replace the #MatrixParam with a #PathParam it works perfectly, and can I get the URL string retrieved in its entirity. The URI that I get is as expected - no odd hex characters, no typos, and so forth. The URI entered is what you get back. So, no problem there.
Behaviour is also consistent across platforms (couple of flavours of Linux, and three versions of Windoze), so it is not anything to do with the OS itself. Similarly, I get the same behavior with multiple clients and tools, so it isnt a problem there either.
So, it appears to be a problem within the MSF4J framework / domain, and I could use some support / help / suggestions here as I've reached the point of tearing my hair out..... Any ideas, folks?
The only reference I can find to a similar problem was closed as 'off topic' without a reply (see Rest API Matrix param annotation) so I think that this needs re-opening as it seems to be a genuine problem....
Regards, and thanks in advance for any help,
Rick
#MatrixParam is not supported with MSF4J at the moment. You can create a GitHub issue. So we can implement that support in future releases.

Getting an 500 internal error when uploading file using cgi and python

Hi I have a project that involves uploading documents. I am using html for the front end and python for the backend. I've managed to link my html and python file but I'm having a problem with the server. At first I though it was a random thing but I'm pretty sure it's because of what I added to the python code. I have:
import cgi
import sys
import os
htmlform = cgi.FieldStorage()
file_data = htmlform['myfile']
if not fileitem.file:
return
(name,ext) = os.path.splitext( fileitem.filename)
#if ext == “.jpg” or ext == “.png” or ext == “.gif”:
#ioFlag = “wb”
#else:
#ioFlag = “w”
I was able to log into my page go to the html form submit the form and got to a basic success html page I had below the above input. Now Im pretty new to python and didnt realise that the if statements should be indented. And I get a 500 internal error when I uncommented the if statement. I did it once and then went through commenting out my code being completely confused as to why I was getting error but after a while it just started working again. My guess is the incorrect if statement somehow got it stuck. I expect after about an hour it'll be working again but ideally I'd like to know if I could stop the process on the server if possible. I was following this guide http://www.alwaysgetbetter.com/blog/2009/01/02/python-file-upload/
Fixed it! The problem seems to be the indentation. If you're ever unsure about this stuff look at the error logs. I'm using an apache server and I dont have access to the error logs so I used
sudo cat /etc/log/apache2/error.log
It gave me the answer and this should hopefully help you even if your question is unrelated.
EDIT: An for completeness sake file_data should be fileitem

QWebView - Error 400 when giving url

I'm trying to build a little application that needs to run the url that is generated by the script at this link: http://blogs.aws.amazon.com/security/post/Tx70F69I9G8TYG/How-to-enable-cross-account-access-to-the-AWS-Management-Console
The application is build with Qt4 and Pyqt4. I create a QWebView and want to load the url that is generated at the end of the script in the link inside the webview.
url = QUrl(ConnectionScript.generateURL())
self.webView.load(url)
self.webView.show()
but this code gives me a "HTTP Status 400 - BadRequest" error. I've tried to change the "load" with "setUrl" but there is no change.
The useful code is only this, other lines are just setting up the GUI (and it's doing fine). Any suggestion about how to fix this and what might the problem be? I think it's something very easy to fix but i can't do it right...
Edit1: i forgot to mention that when i open the generated link in a web browser (like chrome or firefox) all goes well and it gives me no such error
Found out that the problem was this line of code:
request_parameters += urllib.quote_plus("https://console.aws.amazon.com/")
The quote_plus encoded : / so the webView load couldn't process the url in the right way.
Just don't use the urllib.quote_plus method and everything will go as expected.

c++ getaddrinfo doesnt process for big URL's

C++ Sockets. Getting information from a website.
I am trying to read content from web using sockets. using the following code.
int status = getaddrinfo(l_url.c_str(), "http", &l_address, &l_addr_ll);
if (status != 0 ){
printf("\n ***** getaddrinfo() failed: %s\n", gai_strerror(status));
return FAILURE;
}
The code works fine for urls like "www.yahoo.com", "www.google.com" however it doesnt work for url's like "www.google.com/nexus".
Any URL's having a "/" are not working with this code. Am i missing anything?
getaddrinfo gives you information about network addresses, not about URLs. A URL is not a network address, though it often contains one. A string like "www.google.com/nexus" is neither a URL nor an address (though it might well be part of a URL), so its not suprising that getaddrinfo fails for it.
The man page says that the first parameter is supposed to be a host name. The host name is just the first part up to the top level domain. Everything thereafter does not belong to the host name. Take care, some parts before may also not belong to the hostname, especially if you see an # in your URL.
Have a look into wikipedia for URL, there is a lengthy explanation which part of a URL actually is the host name you can put into your function.
As per the man page. one needs to pass the URL information to getaddressinfo method. FOr this, the user must pass the name of the website. like "www.google.com"
However while requesting for data, the user posts a request, at that point, the user could post URL like "www.google.com/nexus"
The address will be same for a URL. however the request varies, hence one needs to get the address of the website using only till ".com". Once address info is received, further requests could be made accordingly.

c# app connectivity issue

I am new to C# and would be really grateful if someone could provide some insight on the following problem: I have written a c# app that gets the html content of a website, quite simply using a webclient. The problem is that if I run it for multiple websites I see that sometimes I get no results for some of them, like it was never connected to that website at that instance. I initially thought it was my internet connection but the same happened when I tried on a different wifi. It is worth mentioning that I have the same prob on another of my appcs when trying to connect to a webservice. My question is: does anybody know how can this be fixed? Does it have to do with the timeout time of something like that?
Thank you very much in advance
This is the code but it's not really an issue of coding:
var client = new WebClient();
try
{
var htmlcode = client.DownloadString(site);
int NumberOfTrues = Regex.Matches(htmlcode.ToLower(), key).Count;
}
catch (Exception)
{
messagebox.show("could not be loaded");
}
This was solved by defining the default proxy server in app config.