【问题标题】:How to use folders in my project using Flask + WSGI?如何使用 Flask + WSGI 在我的项目中使用文件夹?
【发布时间】:2019-06-14 05:28:58
【问题描述】:

我可以使用 Flask + WSGI 成功运行“hello world”应用程序...但是使用“文件夹”中的“routes.py”更改我的项目结构会使服务器出错...

mod_wsgi (pid=9):目标 WSGI 脚本“/var/www/myfirstapp/hello.wsgi”无法作为 Python 模块加载。

mod_wsgi (pid=9):处理 WSGI 脚本“/var/www/myfirstapp/hello.wsgi”时发生异常

从文件夹.路由导入 simple_page

ImportError: 没有名为 folder.routes 的模块

这是我的项目树:

├── folder
│   └── routes.py
├── hello.conf
├── hello.py
├── hello.wsgi
└── README.md

hello.py:

from flask import Flask
from folder.routes import simple_page # works in dev but not with wsgi.. Why?


app = Flask(__name__)
app.register_blueprint(simple_page)

routes.py:

from flask import Blueprint, render_template, abort
from jinja2 import TemplateNotFound

simple_page = Blueprint('simple_page', __name__,
                        template_folder='templates')

@simple_page.route('/')
def index():
    try:
        return "Hello world"
    except TemplateNotFound:
        abort(404)

hello.conf

<VirtualHost *>
    ServerName example.com
    WSGIScriptAlias / /var/www/myfirstapp/hello.wsgi
    WSGIDaemonProcess hello python-path=/var/www/myfirstapp:/var/www/myfirstapp/.env/lib/python3.5/site-packages
    <Directory /var/www/myfirstapp>
       WSGIProcessGroup hello
       WSGIApplicationGroup %{GLOBAL}
        Order deny,allow
        Allow from all
    </Directory>
</VirtualHost>

hello.wsgi:

import sys
sys.path.insert(0, "/var/www/myfirstapp")
from hello import app as application

注意:我不明白为什么 WSGI 对根文件夹中的 routes.py (导入路由)“很好”,但抱怨在 hello 中导入“folder.routes”(hello.py)。 py 如果我把同一个文件放在“文件夹”中...

【问题讨论】:

  • 在文件夹中放一个空的__init__.py文件,看看是否可行。
  • 没用... :(

标签: python flask wsgi


【解决方案1】:

我找到了一个解决方案,引用了 WSGIDaemonProcess hello.conf 行中的相应模块(文件夹):

pythonpath=/var/www/myfirstapp/.env/lib/python3.5/sitepackages:/var/www/myfirstapp/:/var/www/myfirstapp/folder

比在 routes.py 中: 而不是from folder.routes import simple_page,我们有import routes

项目树也发生了一些变化:

├── myfirstapp
│   ├── folder
│   │   └── routes.py
│   └── __init__.py
├── hello.wsgi
└── README.md

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-30
    • 2017-10-29
    • 2022-10-04
    • 2018-01-26
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多