python导入错误:没有名为app的模块

时间:2016-03-23 21:50:11

标签: python python-2.7 flask

首先,我在__init__.py文件夹

中创建了app
from flask import Flask

app = Flask(__name__)
from app import views

然后,我在同一个app文件夹中创建了views.py

from app import app

@app.route('/')
@app.route('/index')
def index():
    return "Hello, World!

最后,我在另一个文件夹中创建了run.py

#!flask/bin/python
from app import app 
app.run()

所以,我的烧瓶树就像

/microblog
    /app
        /__init__.py
        /views.py
    /flask
    /tmp
        /run.py

但是,当我尝试运行run.py时,我收到错误

Traceback (most recent call last):
 File "/home/shubham/Microblog/tmp/run.py", line 2, in <module>
    from app import app 
ImportError: No module named app
[Finished in 0.2s with exit code 1]
[shell_cmd: python -u "/home/shubham/Microblog/tmp/run.py"]
[dir: /home/shubham/Microblog/tmp]
[path:      /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games]

1 个答案:

答案 0 :(得分:0)

您的问题是您对进口,变量名称和包之间的差异没有清楚的了解。以及进口如何运作。

当您构建Python软件包时,您通常会在其文件夹中包含setup.pyREADME和其他各种文件,然后是您的软件包文件夹。你可能想要这样的东西:

├── microblog
│   ├── __init__.py
│   ├── server.py
│   └── views.py
├── README
├── MANIFEST.in
└── setup.py

如果您确实并不想将您的网址处理程序放在与您的应用相同的位置,那么您已经有点倒退了。你应该这样做:

server.py

from flask import Flask
from . import views

app = Flask(__name__)
app.register_blueprint(views.microblog)


def run():
    app.run(debug=True)

views.py

from flask import Blueprint

microblog = Blueprint('microblog', __name__)

@microblog.route('/')
@microblog.route('/index')
def index():
    return 'Hello, world!'

setup.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from setuptools import setup

setup(
    name='microblog',
    version='0.1.0',
    description='My microblog',
    author='Me',
    author_email='me@example.com',
    url='http://my.cool.example.com',
    packages=[
        'microblog',
    ],
    entry_points={
        'console_scripts': [
            'start-my-blog = microblog.server:run'
        ],
    },
    package_dir={'microblog': 'microblog'},
    include_package_data=True,
    install_requires=['flask',
    ],
    license="BSD",
    zip_safe=False,
    keywords='',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Natural Language :: English',
        'Programming Language :: Python :: 3.4',
    ],
)

现在,您可以创建自己的virtualenv,安装您的应用程序,然后运行它:

$ mkvirtualenv microblog
$ workon microblog
(microblog) $ python -m pip install -e .
# a bunch of install happens here, flask & what-not
$ start-my-blog

如果要更改要运行的命令的名称,您可以在setup.py中执行此操作。从这样的结构开始将为您节省很多麻烦。