我从Djanjo 1.8升级到2.1
我注意到当我尝试使用导入的模块时,找不到该模块
示例1
from pandas import DataFrame
data = [list1,list2,list3]
DataFrame.from_records(data, columns = ['Word','Score','Word','Score','Word'])
Word Score Word Score Word
0 (word1, 0.6037212610244751) (word2, 0.5418980717658997) (word3, 0.5389199256896973) (word4, 0.51054847240448) (word5, 0.49834704399108887)
1 (word6, 0.6037212610244751) (word7, 0.5418980717658997) (word8, 0.5389199256896973) (word9, 0.51054847240448) (word10, 0.49834704399108887)
2 (word11, 0.6037212610244751) (word12, 0.5418980717658997) (word13, 0.5389199256896973) (word14, 0.51054847240448) (word15, 0.49834704399108887)
这将导致from var_dump import var_dump
from django.db import connection
def get_available_id():
with connection.cursor() as cursor:
query = """SELECT
*
FROM
`stackoverflow`
;"""
cursor.execute(query)
row = cursor.fetchone()
return row
var_dump(get_available_id())
完全转储
NameError: name 'connection' is not defined
如果我在功能root@fbb4988d3d17:/var/www/api.domain.com# python manage.py shell < sql/import.py
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 353, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/shell.py", line 92, in handle
exec(sys.stdin.read())
File "<string>", line 27, in <module>
File "<string>", line 8, in get_available_id
NameError: name 'connection' is not defined
中导入connection
模块,一切正常
示例2
get_answers
这有效。
我该怎么做才能确保示例1与全局导入一起使用。
我正在运行这样的代码
from var_dump import var_dump
def get_available_id():
from django.db import connection
with connection.cursor() as cursor:
query = """SELECT
*
FROM
`stackoverflow`
;"""
cursor.execute(query)
row = cursor.fetchone()
return row
var_dump(get_available_id())
答案 0 :(得分:0)
通过将我要运行的类移到单独的文件中来解决问题。
#class_a.py
import re
class A:
def word_to_list(str):
words = re.split("(\s+)", str)
return words
a = A()
a.word_to_list('bob is your uncle')
运行python manage.py shell < sql/class_a.py
会产生NameError: name 're' is not defined
解决方案是
#class_a.py
import re
class A:
def word_to_list(str):
words = re.split("(\s+)", str)
return words
然后
#runner.py
from class_a import A
a = A()
a.word_to_list('bob is your uncle')
运行python manage.py shell < sql/runner.py