无法访问函数外的变量

时间:2016-06-21 23:56:03

标签: python

尝试从另一个函数中的一个函数访问变量时,我一直收到以下错误。

NameError:未定义全局名称“savemovieurl”

如何从“dynamic_data_entry”中的函数“tmdb_posters”访问“savemovieurl”以将其保存到数据库?

我尝试在变量名称中添加全局,但没有成功。

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)

1 个答案:

答案 0 :(得分:0)

我认为这已经在这里得到了解答:How do I use a variable so that it is inside and outside of a function

我知道我应该对此发表评论然而由于某种原因,我不能这样,我只是认为我会把它写成答案。我希望这会有所帮助。