簡體   English   中英

NameError:未定義名稱“athena”,從另一個 jupyter notebook 導入 athena 查詢 function 時

[英]NameError: name 'athena' is not defined , when importing athena query function from another jupyter notebook

我的 query_distinct_data() function 在運行時成功執行。 但是,當我嘗試使用 Jupyter 筆記本將 query_distinct_data() 從我的 function 頁面 map_distinct_data 導入到我的主頁時,出現以下錯誤。

NameError: name 'athena' is not defined

下面是我的主頁

import pandas as pd
import requests
import xml.etree.ElementTree as ET
from datetime import date
import boto3
import time
import geopandas
import folium

from ipynb.fs.full.qld_2 import qld_data
from ipynb.fs.full.vic_2 import vic_data
from ipynb.fs.full.put_to_s3_bucket import put_to_s3_bucket
from ipynb.fs.full.map_distinct_data import query_distinct_data
from ipynb.fs.full.map_distinct_data import distinct_data_df
from ipynb.fs.full.map_distinct_data import create_distinct_data_map

aws_region = "ap-southeast-2"
schema_name = "fire_data"
table_name ='rfs_fire_data'
result_output_location = "s3://camgoo2-rfs-visualisation/query_results/"
bucket='camgoo2-rfs-visualisation'
athena = boto3.client("athena",region_name=aws_region)

qld_data()
vic_data()
put_to_s3_bucket()

execution_id = query_distinct_data()
df = distinct_data_df()
create_distinct_data_map()

下面是我想從 map_distinct_data 筆記本導入的 function。 這成功執行但在嘗試導入到我的主頁時出現錯誤。

def query_distinct_data():
    query = "SELECT DISTINCT * from fire_data.rfs_fire_data where state in ('NSW','VIC','QLD')"
    response = athena.start_query_execution(
        QueryString=query,
        ResultConfiguration={"OutputLocation": result_output_location})
    return response["QueryExecutionId"]

我能夠運行 function query_distinct_data() 並且它在單獨運行時執行。 但是當我嘗試導入 function 時失敗了。

我使用 ipynb.fs.full 導入的其他涉及 athena 的函數在導入時執行正常。

一切都與變量可見性有關 scope ( 1 , 2 )

簡而言之: map_distinct_data模塊對main pageathena變量一無所知。

好的和正確的方法是將 function 內部的athena變量作為參數傳遞:

from ipynb.fs.full.map_distinct_data import create_distinct_data_map

...
athena = boto3.client("athena",region_name=aws_region)

execution_id = create_distinct_data_map(athena)

其中create_distinct_data_map應定義為

def create_distinct_data_map(athena):
   ...

第二種方法是在導入模塊中設置變量:

from ipynb.fs.full.map_distinct_data import create_distinct_data_map
from ipynb.fs.full import map_distinct_data

athena = boto3.client("athena",region_name=aws_region)

map_distinct_data.athena = athena

execution_id = create_distinct_data_map()

即使第二種方式有效,它也是一種非常糟糕的風格。

下面是Python中關於封裝的一些必須知道的信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM