I'm trying to get this code working, but it keeps coming up with the error in the title. I don't get it. The function "url" is set before the "get_media" function, and the same function call thing works with other functions I've set, but it says otherwise. I've looked at similar question's answers, but I cannot understand any of them, because the answers are designed around their complicated code, and they offer up no proper explanation as to how it works.
def url(path):
if path.find("?") != -1:
pre = "&"
else:
pre = "?"
return protocol +"://" +host +base_path +path +pre +"access_token=" +access_token
def get_media(insta_id, max_id=None):
insta_id = str(insta_id)
path = url("/users/%s/media/recent/") # ERROR COMES UP HERE
if max_id is not None:
path = path +"&max_id=%s" % max_id
url = urllib.request.urlopen(path)
url = url.read().decode("utf-8")
url = json.loads(url)
return url
Any help appreciated. Tell me if you need more code to work with.
B
You assign to a local variable called "url" later in your function. Because of that, Python treats every reference to "url" within that function as local. But of course you haven't defined that local variable yet, hence the error.
Use a different name for the local "url" variable. (It's never a URL anyway, so you should definitely use a better name.)
Just need to tell python this is global variable inside function
url = "" # <------ 1. declare url outsite function/def
def get_media():
global url # <-------- 2. add here "global" tell the system this is global variable
# ....
url = "my text"
print(url) # will display "my text"
Related
What I'm trying to do is have it replace all urls from an html file.
This is what I have done but I realized it also deletes everything else after it.
s = 'https://12345678.com/'
site_link = "google"
print(s[:8] + site_link)
It would return as https://google
I have made a code sample.
In this, link_template is a template for a link, and ***** represents where your site_name will go. It might look a bit confusing at first, but if you run it you'll understand.
# change this to change your URL
link_template = 'https://*****.com/'
# a site name, from your example
site_name = 'google'
# this is your completed link
site_link = site_name.join(link_template.split('*****'))
# prints the result
print(site_link)
Additionally, you can make a function for it:
def name_to_link(link_template,site_name):
return site_name.join(link_template.split('*****'))
And then you can use the function like this:
link = name_to_link('https://translate.*****.com/','google')
print(link)
beginner Python user here.
So, I´m trying to make a program that orders the files of my (many) Downloads folder.
I made a class object to work with the many folders:
class cContenedora:
def __int__(self, nCarp, dCarp): #nCarp Stands is the file name and dCarp Stands for file directory.
self.nCarp = nCarp
self.dCarp = dCarp
So, y wrote a instance like this:
Download = cContenedora()
Download.nCarp = "Downloads/"
#The side bar is for making a path to move my archives from with shutil.move(path, dest)
Download.dCarp = "/Users/MyName/Download/"
#This is for searching the folder with os.listdir(Something.dCarp)
Then, I wrote my function, and it goes something like this:
def ordenador(carpetaContenedora, formato, directorioFinal): #carpetaContenedora is a Download Folder
carpetaContenedora = cContenedora() #carpetaContenedora one of the class objects
dirCCont = os.listdir(carpetaContenedora.dCarp) #The to directory is carpetaContenedora.cCarp
for a in dirCCont:
if a.endswith(formato):
path = "/Users/Aurelio Induni/" + carpetaContenedora().nCarp + a
try:
shutil.move(path, directorioFinal)
print(Fore.GREEN + a + "fue movido exitosamente.")
except:
print(Fore.RED + "Error con el archivo" + a)
pass
for trys in range(len(listaCarpetasDestino)-1): #Is a list full of directories.
for container in listaCarpetasFuente: #A short list of all my Downloads Folder.
for formatx in listaFormatos: #listaFormatos is a list ful of format extensions like ".pdf"
#try: #I disabled this to see the error istead of "Error Total"
ordenador(container, formatx, listaCarpetasDestino[trys])
#except:
#print(Fore.RED + "Error Total") #I disabled this to see the error.
But every time I run it I get the following:
AttributeError: 'cContenedora' object has no attribute 'dCarp'
It says the error is in line 47 (the one with the os.listdir(carpetaContenedora.dCarp))
I´m sure is something small. Python is so amazing, but it also can be so frustrating not knowing what´s wrong.
There is a spelling mistake in the initialization of your instance. It should be "init" instead of "int".
In the class cContenedora, the function should be
class cContenedora:
def __init__(self, nCarp, dCarp):
self.nCarp = nCarp
self.dCarp = dCarp
Additionally, When you are passing in the parameter. Make sure to pass in both of the parameters in the line with Value.
CContenedora(nCarp="something",dCarp="something")
Your class initializer, i.e., __init__() function has 2 parameters nCarp and dCarp but when you are actually creating the object there are no parameters passed.
Your function ordenador takes the first parameter as carpetaContenedora, on the first line same variable is assigned a new object of cContenedora, at this line the original values you passed are lost forever.
This could be the reason it is giving for the error.
Refer this link for more details on how to create classes and instantiate the object.
I am writing a Python program that responds to request and vocalizes a response back to the user. Below is a sample of two functions. How can I do this without using a global variable and still get back a non-repeating, random response?
# stores prior response
website_result = 'first_response.wav'
def launch_website():
# if service is offline return with default msg otherwise launch service
if is_connected() == 'FALSE':
arg = 'this_service_is_offline.wav'
return arg
else:
site = 'http://www.somesite.com'
launch_it(site)
return launch_website_response()
def launch_website_response():
# using the global variable inside function
global website_result
# possible responses
RESPONSES = ['first_response.wav', 'second_response.wav', 'third_response.wav']
# ensures a non-repeating response
tmp = random.choice(RESPONSES)
while website_result == tmp:
tmp = random.choice(RESPONSES)
website_result = tmp
return website_result
Your website_result variable indicates that you to have some sort of persistent state. Maybe you could consider storing it in a text file and access it everytime you need it and change it afterward (this works if you don't have to do too many calls to it, otherwise you will get in I/O limitations).
I don't know about the specifics of your application, but it might happen that you could also make your two functions take website_result as an argument as suggested by #JGut.
I'm trying to pass a number through URL and retrieve it on another page. If I try to specify the variable type, i get a malformed URL error and it won't compile. If I don't specify the var type, it will run, but the variable becomes Type None. I can't cast it to an int either. How can I pass it as an Integer...? Thanks in advance.
This gives me a malformed URL error:
#app.route('/iLike/<int: num>', methods=['GET','POST'])
def single2(num):
This runs but gives me a var of type none that I can't work with:
#app.route('/iLike/<num>', methods=['GET','POST'])
def single2(num):
try:
location = session.get('location')
transType = session.get('transType')
data = session.get('data')
**num = request.args.get('num')**
You are mixing route parameters and request arguments here.
Parameters you specify in the route are route parameters and are a way to declare variable rules. The values for these parameters are passed as function arguments to the route function. So in your case, for your <num> url part, the value is passed as the function argument num.
Request arguments are independent of routes and are passed to URLs as GET parameters. You can access them through the request object. This is what you are doing with request.args.get().
A full example would look like this:
#app.route('/iLike/<int:num>')
def single2(num):
print(num, request.args.get('num'))
Opening /iLike/123 would now result in 123 None. The request argument is empty because you didn’t specify one. You can do that by opening /iLike/123?num=456, which would result in 123 456.
You recieve None here:
num = request.args.get('num')
because you're not passing num as element of querystring.
When use request.args.get('num')?
If we would have URL like this one:
localhost:8080/iLike?num=2
But it's not your case. You pass num already to a function as an argument. So in your case just use:
#app.route('/iLike/<num>', methods=['GET','POST'])
def single2(num):
try:
location = session.get('location')
transType = session.get('transType')
data = session.get('data')
print(num)
In your second example, instead of num = request.args.get('num') try to simply use num. Since you specified it as an input to your route/function, you should be able to access it directly.
Try this:
#app.route('/iLike/<int:num>', methods=['GET','POST'])
def single2(num):
print(num)
Other issues aside, the direct cause of the "malformed URL" error is the space you included in the URL:
'/iLike/<int: num>'
Instead of this:
'/iLike/<int:num>'
I'm getting an unusual error, which I believe arises from using the same name for both a variable and a function. I didn't realise this could cause problems for Python. Can anyone shed some light?
Code (inside Class definition):
def post(self):
username = self.request.get("username")
password = self.request.get("password")
verify = self.request.get("verify")
email = self.request.get("email")
error_username = error_username(username) # SOURCE OF ERROR
error_password = error_password(password)
error_verify = error_verify(password, verify)
error_email = error_email(email)
if all( [error_username == "", error_password == "",
error_verify == "", error_email == ""] ):
self.redirect("/unit2/welcome?username=%s" % escape_html(username))
else:
self.write_form(username, email, error_username,
error_password, error_verify, error_email)
Error given:
File "/Users/max/python_projects/max-dev-udacity/signup.py", line 91, in post
error_password = error_password(password)
UnboundLocalError: local variable 'error_password' referenced before assignment
INFO 2014-07-22 18:03:12,466 module.py:640] default: "POST /unit2/signup HTTP/1.1" 500 228
error_username() is imported at the top of the sheet.
Note, when I change error_username() to some other function name, this error no longer occurs. Rather, the error occurs on the following line, presumably for the same reason.
You cannot use the same name for a function and a local name, no.
The scope of a name is determined at compile time based on binding behaviour; if you use a name as a function parameter, or as an import target, or you assign to it in a function, then it is a local name throughout the function.
As such, in the post() function, each of error_username, error_password, error_verify and error_email are local names; you have lines assigning values to each. You cannot use these names as globals first, then treat them as locals later.
Rename the local names, they are masking the functions.