Docker ModuleNotFoundError,即使该模块不再包含在代码中

问题描述 投票:0回答:2

我写了一个Flask API,我想在docker容器中运行。但是,即使代码中不再包含找不到的模块,Error: While importing "api", an ImportError was raised:仍会不断出现。

发生错误后,我停止,移除并重新启动了Docker容器以运行Flask Api:

docker stop privacy_api
docker rm privacy_api
docker build -t privacy_api_image .
docker run -dit --name=privacy_api -e FLASK_APP=api.py -p 5000:5000 -v main_api:/app --network privacy-network privacy_api_image
5963fb7fa194d6710ae5e713d2060bd0be5338b04636bf306b78bda4bb596524

docker logs -f privacy_api

但是,这是我得到的输出:

* Serving Flask app "api.py"
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
Usage: flask run [OPTIONS]

    Error: While importing "api", an ImportError was raised:

    Traceback (most recent call last):
      File "/usr/local/lib/python3.8/site-packages/flask/cli.py", line 240, in locate_app
        __import__(module_name)
      File "/app/api.py", line 2, in <module>
        from flask_cors import CORS, cross_origin
    ModuleNotFoundError: No module named 'flask_cors'

这是我的api.py代码:

from flask import Flask, request, Response, jsonify
import MySQLdb
import json
import logging
import formscripts as priv
import databreach
from datetime import datetime
import pytz #needs to be added to Docker!

app = Flask(__name__)

def get_db_connection():
    cursor=None
    if not cursor:
        connection = MySQLdb.connect("privacy-mysql", "root", "DockerPasswort!", "privacydatabase")
        cursor = connection.cursor()
    return cursor, connection

@app.route('/data_remove', methods=["POST"])
def data_takedown():
    print("in takedown")
    cursor, connection = get_db_connection()
    data = request.get_json()
    email_login=False
    email_pw=""
    title = data["title"]
    firstname = data["firstname"]
    lastname = data["lastname"]
    suffix = data["suffix"]
    email = data["email"]
    phone_num = data["phone_num"]
    street = data["street"]
    apt = data["apt"]
    city = data["city"]
    state = data["state"]
    country = data["country"]
    zip_code = data["zip_code"]
    cc_last4 = data["cc_last4"]
    data_del_msg = data["data_del_msg"]
    deviceAdID = data["deviceAdID"]
    privacyReg = data["privacyReg"]
    if "email_pw" in data:
        email_login=True
        email_pw=data["email_pw"]
    #############################################
    ####### privacy form script functions #######
    #############################################
    if email_login==True:
        email_result = requests.post('http://localhost:5001/email', json={
    "from_email": email,
    "password": email_pw,
    "to_email": "[email protected]",
    "subject": "Acxiom Opt out request for: "+firstname+" "+lastname+" ("+email+")",
    "message": "Dear Acxiom Team, I would like you to remove my information. This is my name: "+firstname+" "+lastname+" "+suffix+". This is my phone_number: "+phone_num+", my email: "+email+ ". This is my address: Street: "+street+", Apartment: "+apt+", City: "+city+", State: "+state+", Zip: "+zip_code
    })
        #Feel free to test whether it works for you with gmail (it should if you change the commenting for the server in send_email.py) but somehow it doesn't for me
        """
        r = requests.post('http://localhost:5000/email', json={
            "from_email": "[email protected]",
            "password": "Password",
            "to_email": "[email protected]",
            "subject": "subject test",
            "message": "body test"
        })
        """

    adColony = priv.adColony_DoNotSSP(email, firstname, lastname, privacyReg,
                                      deviceAdID)
    petco = priv.petco_delete(firstname, lastname, email, phone_num)
    linkedIn = priv.linkedIn_DataDelete(firstname, lastname, email,
                                        data_del_msg)
    chipotle = priv.chipotle_delete(firstname, lastname, email, phone_num,
                                    cc_last4)
    pipl = priv.pipl_delete(firstname, lastname, email, phone_num,
                            data_del_msg)
    asl = priv.asl_DD_formfill(firstname, lastname, street, city, state,
                               zip_code, phone_num, email)
    bestBuy = priv.bestBuy_DD_formfill(firstname, lastname, country, street,
                                       city, zip_code, phone_num, email)
    booking = priv.booking_DD_formfill(email)
    analyticsIQ=priv.analyticsIQ_DD_formfill(firstname, lastname, country, address, city, state, zipcode, email)
    asl=priv.asl_DD_formfill(firstname, lastname, address, city, state, zipcode, phone, email)

    ############
    #####TODO test whether next three functions are working and otherwise remove (also from database)#####
    ##########
    atlantic=priv.atlantic_DD_formfill(california_resident, email, zipcode)
    instantCheckmate=priv.instantCheckmate_DD_formfill(firstname, lastname, city)
    intelius=priv.intelius_DD_formfill(firstname, lastname, cityState)
    ####### Check for data breach  #######
    databreach=request_answer(email)
    ####### Insert into database   #######
    tz_LA = pytz.timezone('America/Los_Angeles')
    datetime_LA = datetime.now(tz_LA)
    timstamp=datetime_LA.strftime("%H:%M:%S")
    sql='INSERT INTO privacydb (timstamp, adColony, asl, analyticsiq, bestbuy, booking, chipotle, instantcheckmate, intelius, linkedin, petco, pipl, atlantic, databreach) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'
    cursor.execute(sql, [timstamp, adColony, asl, analyticsIQ, bestBuy, booking, chipotle, instantCheckmate, intelius, linkedIn, petco, pipl, atlantic, databreach])
    connection.commit()
    cursor.close()
    connection.close()

    #TODO OUTPUT sending email
    return json.dumps({
        "adColony": adColony,
        "asl": asl,
        "analyticsIQ": analyticsIQ,
        "best buy": bestBuy,
        "booking.com": booking,
        "chipotle": chipotle,
        "instantCheckmate": instantCheckmate,
        "intelius": intelius,
        "linkedIn": linkedIn,
        "petco": petco,
        "pipl": pipl,
        "atlantic": atlantic,
        "databreach": databreach
    }), 200

这是Dockerfile

FROM python:3
COPY . /app
WORKDIR /app
RUN pip install -r requirements-main-api.txt
EXPOSE 5000
ENTRYPOINT ["flask"]
CMD ["run", "--host=0.0.0.0"]

这是requirements-main-api.txt file

flask==1.1.1
mysqlclient==1.4.6
selenium
requests
pytz

由于Cors不再在api.py文件中,因此我不理解该错误。

您有什么想法吗?感谢您的帮助!

python docker cors
2个回答
0
投票

这是因为不满足依赖关系。可以发布您的dockerfile或require.txt的内容以使错误可见吗?


0
投票

您需要将Flask-Cors==1.10.3添加到您的需求-main-api.txt中然后使用--no-cache flag

再次运行dockerfile
© www.soinside.com 2019 - 2024. All rights reserved.