【问题标题】:flask program giving module not found找不到烧瓶程序提供模块
【发布时间】:2018-02-07 01:29:56
【问题描述】:

我正在按照这个可爱的指南https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uwsgi-and-nginx-on-centos-7 使用flask 和uWSGI 构建一个python Web 应用程序,它的效果非常好。我想说我已经在项目文件中安装了每个模块和依赖项。我现在尝试构建工作脚本,现在我的 init.py 文件如下所示:

from flask import Flask
import pylab as pl
import numpy as np
import pandas as pd

from sklearn import svm
from sklearn import tree
import matplotlib.pyplot as plt
from sklearn import linear_model
from sklearn.pipeline import Pipeline
from sklearn.metrics import confusion_matrix
from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import SGDClassifier
from mlxtend.plotting import plot_decision_regions
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer

app = Flask(__name__)

@app.route("/")


def hello():
    data = pd.read_csv('test1.csv', error_bad_lines=False, delimiter=',')
        numpy_array = data.as_matrix()
        #print numpy_array

        #text in column 1, classifier in column 2.
        X = numpy_array[:,0]
        Y = numpy_array[:,1]
        Y=Y.astype(np.str)

        #divide the test set and set the variable to their correct label/text
        X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.4, random_state=42)

        #MultinomialNB
        text_clf = Pipeline([('vect', CountVectorizer(stop_words='english')), ('tfidf', TfidfTransformer()),('clf', MultinomialNB()),])

        text_clf = text_clf.fit(X_train.astype('U'),Y_train.astype('U'))
        predicted = text_clf.predict(X_test)
        # print the actual accuracy
        print "MNB accuracy: ", np.mean(predicted == Y_test)

        #make the confusion matrix
        y_actu = pd.Series(Y_test, name='Actual')
        y_pred = pd.Series(predicted, name='Predicted')
        df_confusion = pd.crosstab(y_actu, y_pred)
        print df_confusion

        print"-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------$

       #SVM
    vect = CountVectorizer(min_df=0., max_df=1.0)
       X = vect.fit_transform(X_train.astype('U'))
       min_frequency = 22

       text_clf_svm = Pipeline([('vect', CountVectorizer(min_df=min_frequency, stop_words='english')), ('tfidf', TfidfTransformer()),('clf-svm', SGDClassifier(loss='hinge', penalty='l2', alpha=1e-03, n_iter=1000, random_state=21))])

       text_clf_svm = text_clf_svm.fit(X_train.astype('U'),Y_train.astype('U'))
       predicted_svm = text_clf_svm.predict(X_test)
       # print the actual accuracy
       print "svm accuracy: ", np.mean(predicted_svm == Y_test)

       #make the confusion matrix
       y_actu = pd.Series(Y_test, name='Actual')
       y_pred = pd.Series(predicted_svm, name='Predicted')
       df_confusion = pd.crosstab(y_actu, y_pred)

       print df_confusion


if __name__ == "__main__":
   app.run()

就我而言,这一切都很好,确保将所有依赖项和模块安装在我运行代码的文件夹中。但是当我运行它时,我收到以下错误

[root@python-political-bias-app fyp]# semodule -i mynginx.pp
[root@python-political-bias-app fyp]# env/bin/uwsgi --socket 127.0.0.1:8080 -w WSGI:app &
[1] 1710
[root@python-political-bias-app fyp]# *** Starting uWSGI 2.0.15 (64bit) on [Wed Feb  7 01:16:21 2018] ***
compiled with version: 4.8.5 20150623 (Red Hat 4.8.5-16) on 06 February 2018 20:03:13
os: Linux-3.10.0-693.17.1.el7.x86_64 #1 SMP Thu Jan 25 20:13:58 UTC 2018
nodename: python-political-bias-app
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 1
current working directory: /root/fyp
detected binary path: /root/fyp/env/bin/uwsgi
uWSGI running as root, you can use --uid/--gid/--chroot options
*** WARNING: you are running uWSGI as root !!! (use the --uid flag) *** 
*** WARNING: you are running uWSGI without its master process manager ***
your processes number limit is 3807
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uwsgi socket 0 bound to TCP address 127.0.0.1:8080 fd 3
Python version: 2.7.5 (default, Aug  4 2017, 00:39:18)  [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)]
*** Python threads support is disabled. You can enable it with --enable-threads ***
Python main interpreter initialized at 0x74bba0
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 60 seconds
mapped 72768 bytes (71 KB) for 1 cores
*** Operational MODE: single process ***
Traceback (most recent call last):
  File "./WSGI.py", line 1, in <module>
    from app import app
  File "./app/__init__.py", line 2, in <module>
    import pylab as pl
ImportError: No module named pylab
unable to load app 0 (mountpoint='') (callable not found or import error)
*** no app loaded. going in full dynamic mode ***
*** uWSGI is running in multiple interpreter mode ***

我不知道为什么,任何指针都会有帮助,代码本身在本地运行得很好,所以我不确定发生了什么。

【问题讨论】:

  • 系统是否安装了pylab?
  • 如上所述,是的,我在文件夹中安装了 matplot lib 和 pylab,我正在运行它,这是一个 centOS 7 服务器
  • 我实际上不建议使用 pylab,旧的代码示例通常都有它。如果你真的需要 pyploy,只需使用 ` from matplotlib import pylab` matplotlib.org/faq/…
  • 我删除了 pylab 进行测试,每个模块都出现同样的错误,似乎找不到正确的路径来修改它?
  • 您是否记得运行source env//bin/activate 在虚拟环境中工作?似乎您可能已经在 python 基础中安装了 deps,而不是虚拟环境,反之亦然。

标签: python nginx flask uwsgi


【解决方案1】:

您很可能遇到了由极度过时的软件或旧库引起的 2/3 转换编译器翻译问题。您看到的错误可能是深深嵌入的,但在 GCC 编译时显示为接近程序表面的表面错误。因此,该问题比用户 cdrom 和您的回溯错误报告所指出的 2/3 转换问题更深一些。

确保使用 pip 或 conda 将 python 和所有依赖的库更新到最新版本

我可以看到以下软件/库已过时,可能会导致您的错误:

Python 版本:2.7.5(2013 年 5 月)--> 2.7.14

GCC 4.8.5 (2013/2015) --> 7.3

uWSGI 2.0.15 --> 2.0.16

正如您所见,回溯被剪裁/损坏只是为了显示核心问题。当代码在 python 中运行时,通常在回溯中应该有很多行来显示它是从哪里弹出的,但事实并非如此。这可能是因为 GCC 编译器无法正确处理。

Traceback(最近一次调用最后一次): 文件“./WSGI.py”,第 1 行,在 从应用导入应用 文件“./app/init.py”,第 2 行,在 将pylab导入为pl

删除pylap import statement,因为它没有在您提供的脚本代码中使用,因此保持原样没有任何意义。

提示:为了清楚起见,减少导入语句并显示默认编码惰性:

from sklearn import svm
from sklearn import tree

应该是:

from sklearn import svm, tree

我希望您可以通过更新软件来消除错误。享受;-)

【讨论】:

    【解决方案2】:

    我认为您正在尝试使用为 python3 制作的 python2 模块运行。

    一些模块名称自 python3 以来已更改,python2 无法找到

    尝试使用 python3 运行您的代码。您将不得不对您的代码进行一些更改(python2 中的print"..." 必须是 python3 中的print(...)),但我认为这是您正在阅读的指南所使用的版本。

    【讨论】:

    • 如果是这种情况,它不会在模块导入时崩溃,而是在 python 语法上崩溃。我试图在 ubuntu flask python3 python2 和它们的每一个可能的组合中安装这个烧瓶思考,并且我得到导入错误非常单一的时间,etiehr 指的是我试图导入的特定模块或只是指向 tat USWGI (ImportError: No module命名为'wsgi')。它的一致问题跨平台,我已经在虚拟环境的内外安装了模块。任何导致答案的线索都将获得赏金
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-31
    • 2012-07-20
    • 1970-01-01
    • 2016-01-28
    • 2013-09-01
    • 1970-01-01
    相关资源
    最近更新 更多