Flask The system cannot find the path specified: '130.127.5.9' - python

I've just started experimenting with flask and
I am trying to list a network driver using it. This is the command that I type on my browser. But I get an error that it cant find the path
http://127.0.0.1:5000/130.13.5.8/D/dir/
The function works for local drivers without an issue
I know why it fails. It needs 2 '\' before the actual ip or 4 '\\' .
But when I try http://127.0.0.1:5000/////130.13.5.8/D/dir/
it doesnt work.
I even tried %F%F it also doesn't seem to do the trick.
#app.route('/<path:filepath>/dir/')
def get_dir(filepath):
dir_listing = ''
for entry in os.listdir(filepath):
entry_type = 'dir' if os.path.isdir(os.path.join(filepath, entry)) else 'file'
dir_listing += '{entry_name}|{entry_type}|'.format(entry_name=entry, entry_type=entry_type)
return dir_listing

For anyone having the same issue my workaround is the following
from ipaddress import ip_address
try:
ip_address(filepath.split('/')[0])
filepath = '\\\\{filepath}'.format(filepath=filepath)
except ValueError as e:
pass

Related

How can I import module python from my local gitlab?

I used github.com/operatorequals/httpimport, but I get an error: "KeyError: 'test_wr'".
File test_wr.py is located in my gitlab (myserver.locals)
import httpimport
url = "http://myserver.locals/admin_user/python_prod/test_all_py/raw/master/test_dir/test_wr.py"
httpimport.INSECURE = True
with httpimport.remote_repo(["test_wr"], url):
import test_wr
test_wr.init_def('Hi')
This code is from test_wr.py:
def init_def(*args):
return args[0]
/admin_user/ - Group
/python_prod/ - Group (or subgroup)
/test_all_py/ - Project
/test_dir/ - the directory where the script is located (also is located init.py)
Please help me in solve problem!
I solved it! Raw url must be: "http://myserver.locals/admin_user/python_prod/test_all_py/raw/8e904cebf45e7025f68927d8aacd9cb669859002/test_dir"

AttributeError: 'NoneType' object has no attribute 'shape' What is wrong in my code?

I got an error,AttributeError: 'NoneType' object has no attribute 'shape'.I wrote codes in views.py
import os
import cv2
from pathlib import Path
import random
path = Path(__file__).parent
path /= "../../image1"
path1 = Path(__file__).parent
path1 /= "../../image2"
index_list =[]
for i in path.iterdir():
i = str(i)
print(i)
if i.split(".")[-1].lower() in {"jpeg", "jpg", "png"}:
list_img = cv2.imread(i)
index_list.append(list_img)
num = 0
for j in path.iterdir():
j = str(j)
if j.split(".")[-1].lower() in {"jpeg", "jpg", "png"}:
img = cv2.imread(j)
num += 1
random_int = random.randint(0, 9)
index = index_list[random_int]
height1 = index.shape[0]
width1 = index.shape[1]
print(height1)
print(width1)
When I run this code,I got an error, height1 = index.shape[0]
AttributeError: 'NoneType' object has no attribute 'shape' .
In image1's folder,5 images are in there like photo1,photo2,photo3,photo4,photo5.I debuted this program,so I found photo3 causes this error,and I deleted photo3 from image1's folder.And I run this program again,photo2 causes this error.I really cannot understand why this error happens.I think maybe wrong path of the folder causes this error,but it is wrong.How should I fix this?What is wrong in my code?
The variable index is None, which means that one or more items in index_list is None. This is probably because an image you opened with cv2.imread() earlier couldn't be found. As the documentation notes, "Even if the image path is wrong, it won’t throw any error, but print img will give you None."
This is an error condition that you should test for when it might have occurred and, when it is found, handle (say, by displaying an error message and refraining from saving it for further processing). Do not, as you are doing now, ignore the error condition and allow the problem to propagate to later code, where you then have to figure out how index got to be None. If you had written even the most basic error handling, your question would be "why isn't cvv.imread() finding my image files?" rather than "why is Python complaining about a NoneType object?"
To detect errors, you could use something like this:
list_img = cv2.imread(i)
if list_img is None:
print("Couldn't open file %s" % i)
else:
index_list.append(list_img)
This will at least tell if you if's trying to open the files that you think it is. My guess is that it's not finding any of your files, because you're getting a list of files from a directory that's not the working directory, but you're not specifying that directory name when opening the files. Therefore it's looking for the files in the working directory, where they're not.

subprocess.Popen fails in nginx

I am developing a simple website using Flask + gunicorn + nginx on a Raspberry Pi with Rasbian Jessie.
I am stuck at launching a process with this Python code:
def which(program):
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
mplayer_path = which("mplayer")
try:
player = subprocess.Popen([mplayer_path, mp3], stdin=subprocess.PIPE)
except:
return render_template('no_mp3s.html', mp3_message=sys.exc_info())
"mp3" is the path to an mp3 file while "mplayer_path" is the absolute path to mplayer, as returned by the which function described in this answer.
The code works in development when I launch flask directly. In production, when I access the website through nginx, I get the following error message through the no_mp3s.html template:
type 'exceptions.AttributeError'
AttributeError("'NoneType' object has no attribute 'rfind'",)
traceback object at 0x7612ab98
I suspect a permission issue with nginx, but being very new with Linux I am a bit lost!
Edit:
I should add that nowhere in my code (which fits in a single file) I call rfind(). Also, I am sure that the error is caught in this specific try/except because it is the only one that outputs to no_mp3s.html.
Edit:
Following blubberdiblub comments I found out that it is the which function that does not work when the app is run in nginx. Hard coding the path to mplayer seems to work!

WLST execute stored variable "connect()" statement

So, I am passing a environment variable from bash to python;
#!/usr/bin/env python2
import os
#connect("weblogic", "weblogic", url=xxx.xxx.xxx.xxx:xxxx)
os.environ['bash_variable']
via wlst.sh I can print exported bash_variable, but how do I execute stored variable? Basically, I am trying to remove the original connect statement and pass a variable that has said information. Thanks
Question though, why wouldn't you called the script with the variable as an argument and use sys.argv[] ?
By example something like this.
import os
import sys
import traceback
from java.io import *
from java.lang import *
wlDomain = sys.argv[1]
wlDomPath = sys.argv[2]
wlNMHost = sys.argv[3]
wlNMPort = sys.argv[4]
wlDPath="%s/%s" %(wlDomPath,wlDomain)
wlNMprop="/apps/bea/wls/scripts/.shadow/NM.prop"
try:
print "Connection to Node Manager"
print ""
loadProperties(wlNMprop)
nmConnect(username=NMuser,password=NMpass,host=wlNMHost,port=wlNMPort,domainName=wlDomain,domainDir=wlDPath,mType='ssl',verbose='true')
except:
print "Fatal Error : No Connection to Node Manager"
exit()
print "Connected to Node Manager"
The NM.prop file is a 600 file with the username/password for the NM.
EDIT :
So from what I understand you want to do something like this :
URLS = ['t3s://Host1:Port1','t3s://Host2:Port2','t3s://Host3:Port3']
for urls in URLS:
connect('somebody','password',urls)
{bunch of commands}
disconnect()
And the values of the list URLS would be define by the environment.
The way I see it you have 3 choices :
Have 1 script per environment, more or less identical save for the URLS list
Have 1 script but with a conditionnal branching on sys.argv[1] (the environment as a parameter) and create the list there.
Have 1 script which use a parameter file for each environment according to the environment. Each parameter file containing the list in question.
Something like that :
propENV = sys.argv[1]
propPath = "/path1/path2"
propFile = "%s/%s" %(propPath,propENV)
loadProperties(propFile)
I would probably use the properties file option myself as it is more flexible from an operational standpoint...at least IMHO.

invalid path ,Backslashes not allowed [duplicate]

This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Closed 7 months ago.
I am trying to implement a dropbox app which downloads files from user's Dropbox account.While creating destination path in user's local directory,it crashes saying
Error occured [400] {u'path : u''invalid path /New folder\\img1.jpg : character at index 11 backslashes not allowed}
I thought the dropbox's folder hierarchy uses forward slashes to represent nesting of dorectories, and windows uses backward slashes, so they might be conflicting. Then I used python's BIF replace() as follows for different paths
sample_path.replace( "\\", "/" )
but still
complete_path
variable in my code is giving path containing backslash,after which the program crashes.
the folder hierarchy in my dropbox account is :
New Folder :
Img1.jpg
dtu.jpg
img.jpg
the code is :
def download_file(self,source_path,target_path):
print 'Downloading %s' % source_path
file_path = os.path.expanduser(target_path)
(dir_path,tail) = os.path.split(target_path)
self.check_dir(dir_path)
to_file = open(file_path,"wb")
print source_path+"!!!!!!!!!!!!!!!!!!!!!!!!!!"
source_path.replace("\\","/")
f= self.mClient.get_file(source_path) # request to server !
to_file.write(f.read())
return
def download_folder(self, folderPath):
# try to download 5 times to handle http 5xx errors from dropbox
try:
response = self.mClient.metadata(folderPath)
# also ensure that response includes content
if 'contents' in response:
for f in response['contents']:
name = os.path.basename(f['path'])
complete_path = os.path.join(folderPath, name)
if f['is_dir']:
# do recursion to also download this folder
self.download_folder(complete_path)
else:
# download the file
self.download_file(complete_path, os.path.join(self._target_folder, complete_path))
else:
raise ValueError
except (rest.ErrorResponse, rest.RESTSocketError, ValueError) as error:
print 'An error occured while listing a directory. Will try again in some seconds.'
print "Error occured "+ str(error)
Try this in the Python console to see the issue:
>>> x = "hello"
>>> x.replace("hello", "goodbye")
'goodbye'
>>> x
'hello'
Calling replace on a string doesn't actually modify the string. It returns a new string with the replacement. So you probably want to do this instead:
source_path = source_path.replace("\\", "/")

Categories

Resources