简体   繁体   English

Python/Flask 登录表单在 IIS 上引发 500 错误

[英]Python/Flask Login form throws 500 error on IIS

Due to my restrictions at work, I have to rely on hosting my webapp on IIS 7.5 .由于我的工作限制,我不得不依靠在IIS 7.5上托管我的 web 应用程序。 I configured IIS to serve the application via wfastcgi.py .我将IIS配置为通过wfastcgi.py为应用程序提供服务

The issue is, that a login form, throws an HTTP 500 error on IIS, when clicking on the login button.问题是,当单击登录按钮时,登录表单会在 IIS 上引发HTTP 500错误。 The site gets loaded without issue.该网站被加载没有问题。 Also, code works perfectly fine, when I am running it on the flask development server.此外,当我在 Flask 开发服务器上运行代码时,代码工作得非常好。

I have an extended version of the code, with access to a sqlite DB.我有代码的扩展版本,可以访问 sqlite 数据库。 I was able to narrow down the issue to the login session creation part.我能够将问题缩小到登录会话创建部分。 I am not sure, whether the issue is about the way how IIS handles POST and GET requests with wfastcgi.py , or something else.我不确定问题是关于IIS如何使用wfastcgi.py处理POSTGET请求的方式,还是其他什么。

Here's the simplified version of the code, which throws the same error: UPDATE : Changed the view functions to the proper return redirect.这是代码的简化版本,它抛出相同的错误: UPDATE : 将视图函数更改为正确的返回重定向。

import wiw_ad_controller as parser
import sys
from flask import Flask, flash, render_template, redirect, url_for, request, session, abort
import os



app = Flask(__name__)

@app.route('/')
@app.route('/index', methods=['GET', 'POST'])
def index():
    if not session.get('logged_in'):

        return render_template('login.html')        
    else:
        return render_template('index.html')        


@app.route('/login', methods=['POST'])
def login():
    if request.form['username'] == 'admin' and request.form['password'] == 'admin':
        session['logged_in'] = True
        flash("Login was successfull")
    else:
        flash("Wrong password!")
    return redirect(url_for('index')) 


@app.route('/search', methods=['GET','POST'])
def lookup_data():
    if (session.get('logged_in')==True):
        if request.method == 'POST' or request.method == 'GET':

            if (request.form['gpn'] and request.form['gpn'].isdigit()):

                #code removed - not needed
                return render_template('fetched_data.html', user_wiw=user_wiw, user_ad=user_ad)
            else:
                flash('Wrong ID')
            return index()
    return redirect(url_for('index')) 


@app.route("/logout")   
def logout():
    session['logged_in'] = False
    return redirect(url_for('index')) 


@app.errorhandler(500)
def internal_error(exception):
    app.logger.exception(exception)
    return render_template('500.html'), 500 


@app.errorhandler(404)
def internal_error(exception):
    app.logger.exception(exception)
    return render_template('404.html'), 404




if __name__ == '__main__':
    app.secret_key=os.urandom(12)
    app.run(debug=True)

Found out the issue.发现问题了。 I didn't realize, that by calling my script via wfastcgi.py , the main function never runs.我没有意识到,通过wfastcgi.py调用我的脚本,主函数永远不会运行。

The login feature did not work, because it needed app.secret_key=os.urandom(12) to be run first.登录功能不起作用,因为它需要先运行app.secret_key=os.urandom(12)

I used the following code by Miguel Grinberg to find out what the issue is, since debug=True did not provide any output in a IIS prod environment.我使用Miguel Grinberg的以下代码来找出问题所在,因为debug=True没有在IIS prod 环境中提供任何输出。

@app.errorhandler(500)
def internal_error(exception):
    app.logger.exception(exception)
    file_handler = RotatingFileHandler('C:\inetpub\wwwroot\logs.log', 'a', 1 * 1024 * 1024, 10)
    file_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
    app.logger.setLevel(logging.INFO)
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)
    app.logger.info('microblog startup')
    return render_template('500.html'), 500 

Hope, this will help others in the same situation as me.希望,这将帮助其他与我处于相同情况的人。

Note: Read/Write permissions have to be set on wwwroot and all files in order for this to work.注意:必须在 wwwroot 和所有文件上设置读/写权限才能使其工作。

You also need to import logging, from logging import RotatingFileHandler, import render_template from flask, create 500.html file in tempaltes folder.您还需要导入日志,从日志导入 RotatingFileHandler,从 Flask 导入 render_template,在 tempaltes 文件夹中创建 500.html 文件。

The return of your view functions ( search() and login() ) is incorrect.您的视图函数( search()login() )的返回不正确。 Eg例如

return redirect(url_for('index'))

should be used for returning to the index page.应该用于返回到索引页。

See the Flask documentation on redirects.请参阅有关重定向的Flask 文档

I had this same error but my app already had a secret key.我有同样的错误,但我的应用程序已经有一个密钥。

Alas!唉! after two days of searching I used your function to display the traceback and I narrowed down to my problem.经过两天的搜索,我用你的函数来显示回溯,我缩小了我的问题。

The process executing the app did not have access to the database.执行应用程序的进程无权访问数据库。 This problem is related to configuration of iis.这个问题和iis的配置有关。 The identity of the application pool has to have access to the DB.应用程序池的身份必须有权访问数据库。 U can change this identity as instructed here您可以按照此处的说明更改此身份

For other problems anyone faces in iis using Flask I would recommend googling them with using the name asp.net not python or flask eg: Use : "IIS internal server error asp.net" Instead of : "IIS internal server error flask"对于任何人在使用 Flask 的 iis 中面临的其他问题,我建议使用名称 asp.net 而不是 python 或 flask 来搜索它们,例如:使用:“IIS 内部服务器错误 asp.net”而不是:“IIS 内部服务器错误烧瓶”

Guys I had the same problem.伙计们,我遇到了同样的问题。 Here is the solution which works for most people.这是适用于大多数人的解决方案。 This issue happens because the server connects to the database without the secret_key or something.发生此问题是因为服务器在没有 secret_key 或其他东西的情况下连接到数据库。

Make sure you put the following line right under your declaration of the Flask app (In the example app = Flask())确保将以下行放在 Flask 应用程序声明的正下方(在示例中 app = Flask())

app.secret_key=os.urandom(12)
app.run(debug=True)

With the above you will easily be able to debug the issue.有了上面的内容,您就可以轻松地调试问题了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM