简体   繁体   English

无法访问函数外部的变量

[英]Cannot Access Variable Outside of Function

I keep getting the following error when trying to access a variable from one function inside another function. 尝试从另一个函数中的一个函数访问变量时,我不断收到以下错误。

NameError: global name 'savemovieurl' is not defined NameError:全局名称'savemovieurl'未定义

how can i access the "savemovieurl" from the function "tmdb_posters" inside "dynamic_data_entry" to save it to the database? 如何从“ dynamic_data_entry”内的函数“ tmdb_posters”访问“ savemovieurl”以将其保存到数据库?

i've tried adding global to the variable name, and had no success. 我试图将全局添加到变量名称,但没有成功。

import requests
import urllib

import sqlite3
import time
import datetime
import random



movie = raw_input('Enter your movie: ')
print('You searched for: ', movie)

def imdb_id_from_title(title):
    """ return IMDb movie id for search string

        Args::
            title (str): the movie title search string
        Returns: 
            str. IMDB id, e.g., 'tt0095016' 
            None. If no match was found
    """
    pattern = 'http://www.imdb.com/xml/find?json=1&nr=1&tt=on&q={movie_title}'
    url = pattern.format(movie_title=urllib.quote(title))
    r = requests.get(url)
    res = r.json()
    # sections in descending order or preference
    for section in ['popular','exact','substring']:
        key = 'title_' + section 
        if key in res:
            return res[key][0]['id']

if __name__=="__main__":
    title = movie
    imdb_info_returned = ("{1}".format(title, imdb_id_from_title(title)))
    print imdb_info_returned


import os
import requests

CONFIG_PATTERN = 'http://api.themoviedb.org/3/configuration?api_key={key}'
IMG_PATTERN = 'http://api.themoviedb.org/3/movie/{imdbid}/images?api_key={key}' 
KEY = '47db65094c31430c5a2b65112088d70e'

imdb_id_input = imdb_info_returned
print('You searched for: ', imdb_id_input)



def _get_json(url):
    r = requests.get(url)
    return r.json()

def _download_images(urls, path='.'):
    """download all images in list 'urls' to 'path' """

    for nr, url in enumerate(urls):
        r = requests.get(url)
        filetype = r.headers['content-type'].split('/')[-1]
        filename = 'poster_{0}.{1}'.format(nr+1,filetype)
        filepath = os.path.join(path, filename)
        with open(filepath,'wb') as w:
            w.write(r.content)

def get_poster_urls(imdbid):
    """ return image urls of posters for IMDB id
        returns all poster images from 'themoviedb.org'. Uses the
        maximum available size. 
        Args:
            imdbid (str): IMDB id of the movie
        Returns:
            list: list of urls to the images
    """
    config = _get_json(CONFIG_PATTERN.format(key=KEY))
    base_url = config['images']['base_url']
    sizes = config['images']['poster_sizes']

    """
        'sizes' should be sorted in ascending order, so
            max_size = sizes[-1]
        should get the largest size as well.        
    """
    def size_str_to_int(x):
        return float("inf") if x == 'original' else int(x[1:])
    max_size = max(sizes, key=size_str_to_int)

    posters = _get_json(IMG_PATTERN.format(key=KEY,imdbid=imdbid))['posters']
    poster_urls = []


    rel_path = posters[0]['file_path']
    url = "{0}{1}{2}".format(base_url, max_size, rel_path)
    poster_urls.append(url) 

    return poster_urls

def tmdb_posters(imdbid, count=None, outpath='.'):    
    urls = get_poster_urls(imdbid)
    if count is not None:
        urls = urls[:count]
    _download_images(urls, outpath)




    savemovieurl = urls
    print savemovieurl





conn = sqlite3.connect('tutorial.db')
c = conn.cursor()



def create_table():
    c.execute("CREATE TABLE IF NOT EXISTS movies(unix REAL, datestamp TEXT, keyword TEXT, value REAL, moviename TEXT, movieimage TEXT, movieurl TEXT)")

def data_entry():
    c.execute("INSERT INTO movies VALUES(1452549219,'2016-01-11 13:53:39','Python',6,'movienamehere1', 'savemovieurl', 'movieurlhere1')")
    conn.commit()
    c.close()
    conn.close()



def dynamic_data_entry(argument) :
    unix = time.time()
    date = str(datetime.datetime.fromtimestamp(unix).strftime('%Y-%m-%d %H: %M: %S'))
    keyword = 'keyword_string'
    movieurl = 'bing.com'
    value = random.randrange(0,10)
    savemovieurl2 = 'testimageurl.com'
    print argument
    c.execute("INSERT INTO movies (unix, datestamp, keyword, value, moviename, movieimage, movieurl) VALUES (?, ?, ?, ?, ?, ?, ?)", (unix, date, keyword, value, movie, savemovieurl2, movieurl))
    conn.commit()

create_table()
#data_entry()

for i in range(10) :
    dynamic_data_entry(savemovieurl)
    time.sleep(1)
c.close()
conn.close()



if __name__=="__main__":
    tmdb_posters(imdb_id_input)

I think this has already been answered here: How do I use a variable so that it is inside and outside of a function 我认为这已经在这里得到解答: 如何使用变量,使其位于函数的内部和外部

I know I should comment this however for some reason I can't so I just thought I'd write it as an answer instead. 我知道我应该对此发表评论,但是由于某些原因我不能发表评论,所以我只是认为我会将其写为答案。 I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM