Flask 项目总是出现错误 “We’re sorry, but something went wrong”。

huangapple go评论49阅读模式
英文:

Flask project always got error "We're sorry, but something went wrong"

问题

I'm a beginner in Flask and I have developed a face-detection application based on it. I had many problems when deploy project on a cPanel host and can solve that one by one. But now have another problem that always say me We're sorry, but something went wrong and I do not know what is problem because has no error in log file.

I have a python_files directory included three files like app.py, passenger_wsgi.py, and prediction_blueprint.py and following are the things that are inside.

app.py file:

import os
from flask import Flask, render_template, request, redirect
from werkzeug.utils import secure_filename
from prediction_blueprint import prediction_blueprint

app = Flask(__name__, template_folder='../templates', static_folder='../static')
app.config['TEMPLATES_AUTO_RELOAD'] = True

app.register_blueprint(prediction_blueprint)

@app.route('/')
def index():
    return render_template('./index.html')

@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['file']
    fn = secure_filename(file.filename)
    file.save(os.path.join('../uploads', fn))
    return {
        "success": True,
        "message": fn
    }

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

passenger_wsgi.py file:

import imp
import os
import sys

sys.path.insert(0, os.path.dirname(__file__))
wsgi = imp.load_source('wsgi', 'app.py')

application = wsgi.app

prediction_blueprint.py:

from flask import Blueprint, Flask, request
from keras_vggface import VGGFace, utils
from keras_vggface.utils import preprocess_input
from mtcnn import MTCNN
import cv2 as cv
import numpy as np
import json, requests

prediction_blueprint = Blueprint('prediction_blueprint', __name)

vggface = VGGFace(model='vgg16')
detector_obj = MTCNN()

@prediction_blueprint.route('/predict', methods=['POST'])
def index():
    image = request.get_json().get('image')

    face = extract_face('../uploads/' + image).astype('float32')
    input_sample = np.expand_dims(face, axis=0)
    samples = preprocess_input(input_sample)

    pred = vggface.predict(samples)

    output = utils.decode_predictions(pred)

    founded_person = output[0][0][0].replace("b'", "").replace("'", "")

    result = {
        "success": True,
        "message": {}
    }

    if founded_person:
        celeb_name = get_best_title_wiki_page(founded_person)

        if celeb_name:
            result['message']['celeb_name'] = celeb_name

            celeb_images = get_celeb_images(celeb_name)

            if celeb_images:
                result['message']['celeb_images'] = celeb_images

            return result
        else:
            return {
                "success": False,
                "message": "Best Title Not Found!"
            }

    else:
        return {
            "success": False,
            "message": "Not Found any things !",
        }

def extract_face(address):
    img = cv.imread(address)

    rgb_img = cv.cvtColor(img, cv.COLOR_BGR2RGB)

    face = detector_obj.detect_faces(rgb_img)[0]
    x, y, w, h = face['box']

    actual_face = img[y:y + h, x:x + w]
    actual_face = cv.resize(actual_face, (224, 224))

    return np.asarray(actual_face)

def get_best_title_wiki_page(celeb_name):
    endpoint = "https://en.wikipedia.org/w/api.php"
    parameters = {
        "action": "query",
        "list": "search",
        "srsearch": celeb_name,
        "format": "json",
        "origin": "*"
    }

    best_title = None

    try:
        response = requests.get(endpoint, params=parameters)
        data = json.loads(response.text)
        best_title = data["query"]["search"][0]["title"]
    except Exception as e:
        print(e)

    return best_title

def get_celeb_images(celeb_name):
    endpoint = "https://en.wikipedia.org/w/api.php"
    parameters = {
        "action": "query",
        "titles": celeb_name,
        "prop": "images",
        "iiprop": "url",
        "format": "json",
        "origin": "*"
    }

    try:
        response = requests.get(endpoint, params=parameters)
        data = json.loads(response.text)

        page_id = list(data["query"]["pages"].keys())[0]
        images = data["query"]["pages"][page_id]["images"]

        filtered_images = [image for image in images if "file:" + celeb_name.lower() in image["title"].lower() or "file:" + celeb_name.lower().replace(" ", "") in image["title"].lower()]

        image_urls = ["https://en.wikipedia.org/wiki/Special:Redirect/file/{}".format(image['title'].replace('File:', '')) for image in filtered_images]

        cel_images = image_urls[0:4]

        return cel_images

    except Exception as e:
        print("Getting Images API request Failed", e)

These are all things that I have written. All packages are installed properly, but I do not know which problem caused the We're sorry, but something went wrong message.

Of course, I have a warning like this in the log.log file, while I think it cannot cause the problem:

App 631448 output: /opt/passenger-5.3.7-13.el7.cloudlinux/src/helper-scripts/wsgi-loader.py:26: DeprecationWarning: the imp module is deprecated in favor of importlib; see the module's documentation for alternative uses
App 631448 output:   import sys, os, io, re, imp, threading, signal, traceback, socket, select, struct, logging, errno
英文:

I'm a beginner in Flask and I have developed a face-detection application based on it. I had many problems when deploy project on a cPanel host and can solve that one by one. But now have another problem that always say me We're sorry, but something went wrong and I do not know what is problem because has no error in log file.

I have a python_files directory included three files like app.py , passenger_wsgi.py and prediction_blueprint.py and following are the things that are inside.

app.py file :

import os
from flask import Flask, render_template, request, redirect
from werkzeug.utils import secure_filename
from prediction_blueprint import prediction_blueprint
# from time import sleep
app = Flask(__name__, template_folder='../templates', static_folder='../static')
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.register_blueprint(prediction_blueprint)
@app.route('/')
def index():  # put application's code here
return render_template('./index.html')
@app.route('/upload', methods=['POST'])
def upload():
file = request.files['file']
fn = secure_filename(file.filename)
# sleep(3)
file.save(os.path.join('../uploads', fn))
return {
"success": True,
"message": fn
}
if __name__ == '__main__':
app.run()

passenger_wsgi.py file:

import imp
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
wsgi = imp.load_source('wsgi', 'app.py')
application = wsgi.app

and prediction_blueprint.py

from flask import Blueprint, Flask, request
from keras_vggface import VGGFace, utils
from keras_vggface.utils import preprocess_input
from mtcnn import MTCNN
import cv2 as cv
import numpy as np
import json, requests
prediction_blueprint = Blueprint('prediction_blueprint', __name__)
vggface = VGGFace(model='vgg16')
detector_obj = MTCNN()
@prediction_blueprint.route('/predict', methods=['POST'])
def index():
image = request.get_json().get('image')
face = extract_face('../uploads/' + image).astype('float32')
input_sample = np.expand_dims(face, axis=0)
samples = preprocess_input(input_sample)
pred = vggface.predict(samples)
output = utils.decode_predictions(pred)
founded_person = output[0][0][0].replace("b'", "").replace("'", "")
result = {
"success": True,
"message": {}
}
if founded_person:
celeb_name = get_best_title_wiki_page(founded_person)
if celeb_name:
result['message']['celeb_name'] = celeb_name
celeb_images = get_celeb_images(celeb_name)
if celeb_images:
result['message']['celeb_images'] = celeb_images
return result
else:
return {
"success": False,
"message": "Best Title Not Found!"
}
else:
return {
"success": False,
"message": "Not Found any things !",
}
def extract_face(address):
img = cv.imread(address)
rgb_img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
face = detector_obj.detect_faces(rgb_img)[0]
x, y, w, h = face['box']
actual_face = img[y:y + h, x:x + w]  # This crop only section of image that contain person Face
actual_face = cv.resize(actual_face, (224, 224))
return np.asarray(actual_face)
def get_best_title_wiki_page(celeb_name):
endpoint = "https://en.wikipedia.org/w/api.php"
parameters = {
"action": "query",
"list": "search",
"srsearch": celeb_name,
"format": "json",
"origin": "*"
}
best_title = None
try:
response = requests.get(endpoint, params=parameters)
data = json.loads(response.text)
best_title = data["query"]["search"][0]["title"]
except Exception as e:
print(e)
return best_title
def get_celeb_images(celeb_name):
endpoint = "https://en.wikipedia.org/w/api.php"
parameters = {
"action": "query",
"titles": celeb_name,
"prop": "images",
"iiprop": "url",
"format": "json",
"origin": "*"
}
try:
response = requests.get(endpoint, params=parameters)
data = json.loads(response.text)
page_id = list(data["query"]["pages"].keys())[0]
images = data["query"]["pages"][page_id]["images"]
filtered_images = [image for image in images if
"file:" + celeb_name.lower() in image[
"title"].lower() or "file:" + celeb_name.lower().replace(" ", "") in image[
"title"].lower()]
image_urls = [f"https://en.wikipedia.org/wiki/Special:Redirect/file/{image['title'].replace('File:', '')}" for
image in filtered_images]
cel_images = image_urls[0:4]
return cel_images
except Exception as e:
print("Getting Images API request Failed", e)

these are all things that I have wrote , all packages are installed properly But I so not know which problem caused We're sorry, but something went wrong message?

Of course, I have a warning like this in log.log file while I think it cannot cause the problem :

App 631448 output: /opt/passenger-5.3.7-13.el7.cloudlinux/src/helper-scripts/wsgi-loader.py:26: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses
App 631448 output:   import sys, os, io, re, imp, threading, signal, traceback, socket, select, struct, logging, errno

答案1

得分: 2

在你的 **passenger_wsgi.py** 文件中

替换

`import imp` -> `from importlib.machinery import SourceFileLoader`


`imp.load_source('wsgi', 'app.py')` -> `SourceFileLoader('wsgi', 'app.py').load_module()`

在较新的 Python 版本3.12?),`imp` 将不再存在可以被 `importlib` 替代但是他们已经提前警告你了所以你会收到一个错误警告

```python
from importlib.machinery import SourceFileLoader
import os
import sys


sys.path.insert(0, os.path.dirname(__file__))
wsgi = SourceFileLoader('wsgi', 'app.py').load_module()

application = wsgi.app
英文:

in your passenger_wsgi.py file:

replace:

import imp -> from importlib.machinery import SourceFileLoader

and

imp.load_source('wsgi', 'app.py') -> SourceFileLoader('wsgi', 'app.py').load_module()

imp won't exist anymore in newer python versions (3.12?) and can be replaced by importlib. But they warn you about it already beforehand that's why you get an error warning.

from importlib.machinery import SourceFileLoader
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
wsgi = SourceFileLoader('wsgi', 'app.py').load_module()
application = wsgi.app

huangapple
  • 本文由 发表于 2023年2月26日 23:41:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75573094.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定