我正在重构/移动我的init文件中的一些代码,以获得更好的可读性并管理我的应用程序的主文件。因此,我尝试将重构文件中的函数导入到init中,但仍然收到此错误,
ImportError: cannot import name 'test_state_locations' from 'app.refactor'下面是我导入的方法:
# File: __init__.py
from .refactor import test_state_locations# File: refactor.py
import requests
from privateinfo import key
from .__init__ import API_BASE_URL
def test_state_locations(state):
url = f'https://covid-19-testing.github.io/locations/{state.lower()}/complete.json'
res = requests.get(url)
testing_data = res.json()
latsLngs = {}
for obj in testing_data:
if obj["physical_address"]:
for o in obj["physical_address"]:
addy = o["address_1"]
city = o["city"]
phone = obj["phones"][0]["number"]
location = f'{addy} {city}'
res2 = requests.get(API_BASE_URL,
params={'key': key, 'location': location})
location_coordinates = res2.json()
lat = location_coordinates["results"][0]["locations"][0]["latLng"]["lat"]
lng = location_coordinates["results"][0]["locations"][0]["latLng"]["lng"]
latsLngs[location] = {'lat': lat, 'lng': lng, 'place': location, 'phone': phone}这是我的应用程序目录的照片:

发布于 2021-02-18 23:21:22
您的refactor.py从__init__.py导入了一些东西;它生成了circular import issue。
#from .__init__ import API_BASE_URL发布于 2021-02-18 23:11:27
您正在进行循环导入。在__init__.py中导入refactor,在refactor.py中循环使用__init__
以下是python处理代码的方式。它首先查看refactor.py并尝试导入__init__。但是要导入__init__,python必须运行文件__init__.py。但同样,__init__.py需要refactor,并且必须返回到refactor.py。在这一点上,python停止循环并引发Import Error。
如果您的导入是循环的,则Python导入会中断。请阅读here了解更多信息。
如果您正在使用Flask框架,这里有一个Youtube教程,可以帮助您组织模块结构以避免循环导入
https://stackoverflow.com/questions/66262521
复制相似问题